]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/setup/SetupClass.php
Ported createCountryNames() to python and added tests
[nominatim.git] / lib-php / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 require_once(CONST_LibDir.'/Shell.php');
6
7 class SetupFunctions
8 {
9     protected $iInstances;
10     protected $aDSNInfo;
11     protected $bQuiet;
12     protected $bVerbose;
13     protected $sIgnoreErrors;
14     protected $bEnableDiffUpdates;
15     protected $bEnableDebugStatements;
16     protected $bDrop;
17     protected $oDB = null;
18     protected $oNominatimCmd;
19
20     public function __construct(array $aCMDResult)
21     {
22         // by default, use all but one processor, but never more than 15.
23         $this->iInstances = isset($aCMDResult['threads'])
24             ? $aCMDResult['threads']
25             : (min(16, getProcessorCount()) - 1);
26
27         if ($this->iInstances < 1) {
28             $this->iInstances = 1;
29             warn('resetting threads to '.$this->iInstances);
30         }
31
32         // parse database string
33         $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
34         if (!isset($this->aDSNInfo['port'])) {
35             $this->aDSNInfo['port'] = 5432;
36         }
37
38         // setting member variables based on command line options stored in $aCMDResult
39         $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
40         $this->bVerbose = $aCMDResult['verbose'];
41
42         //setting default values which are not set by the update.php array
43         if (isset($aCMDResult['ignore-errors'])) {
44             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
45         } else {
46             $this->sIgnoreErrors = false;
47         }
48         if (isset($aCMDResult['enable-debug-statements'])) {
49             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
50         } else {
51             $this->bEnableDebugStatements = false;
52         }
53         if (isset($aCMDResult['enable-diff-updates'])) {
54             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
55         } else {
56             $this->bEnableDiffUpdates = false;
57         }
58
59         $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
60
61         $this->oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
62         if ($this->bQuiet) {
63             $this->oNominatimCmd->addParams('--quiet');
64         }
65         if ($this->bVerbose) {
66             $this->oNominatimCmd->addParams('--verbose');
67         }
68     }
69
70     public function calculatePostcodes($bCMDResultAll)
71     {
72         info('Calculate Postcodes');
73         $this->pgsqlRunScriptFile(CONST_SqlDir.'/postcode_tables.sql');
74
75         $sPostcodeFilename = CONST_InstallDir.'/gb_postcode_data.sql.gz';
76         if (file_exists($sPostcodeFilename)) {
77             $this->pgsqlRunScriptFile($sPostcodeFilename);
78         } else {
79             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
80         }
81
82         $sPostcodeFilename = CONST_InstallDir.'/us_postcode_data.sql.gz';
83         if (file_exists($sPostcodeFilename)) {
84             $this->pgsqlRunScriptFile($sPostcodeFilename);
85         } else {
86             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
87         }
88
89
90         $this->db()->exec('TRUNCATE location_postcode');
91
92         $sSQL  = 'INSERT INTO location_postcode';
93         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
94         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
95         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
96         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
97         $sSQL .= '  FROM placex';
98         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
99         $sSQL .= '       AND geometry IS NOT null';
100         $sSQL .= ' GROUP BY country_code, pc';
101         $this->db()->exec($sSQL);
102
103         // only add postcodes that are not yet available in OSM
104         $sSQL  = 'INSERT INTO location_postcode';
105         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
106         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
107         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
108         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
109         $sSQL .= '        (SELECT postcode FROM location_postcode';
110         $sSQL .= "          WHERE country_code = 'us')";
111         $this->db()->exec($sSQL);
112
113         // add missing postcodes for GB (if available)
114         $sSQL  = 'INSERT INTO location_postcode';
115         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
116         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
117         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
118         $sSQL .= '           (SELECT postcode FROM location_postcode';
119         $sSQL .= "             WHERE country_code = 'gb')";
120         $this->db()->exec($sSQL);
121
122         if (!$bCMDResultAll) {
123             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
124             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
125             $this->db()->exec($sSQL);
126         }
127
128         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
129         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
130         $this->db()->exec($sSQL);
131     }
132
133     /**
134      * Return the connection to the database.
135      *
136      * @return Database object.
137      *
138      * Creates a new connection if none exists yet. Otherwise reuses the
139      * already established connection.
140      */
141     private function db()
142     {
143         if (is_null($this->oDB)) {
144             $this->oDB = new \Nominatim\DB();
145             $this->oDB->connect();
146         }
147
148         return $this->oDB;
149     }
150
151     private function pgsqlRunScript($sScript, $bfatal = true)
152     {
153         runSQLScript(
154             $sScript,
155             $bfatal,
156             $this->bVerbose,
157             $this->sIgnoreErrors
158         );
159     }
160
161     public function createSqlFunctions()
162     {
163         $oCmd = (clone($this->oNominatimCmd))
164                 ->addParams('refresh', '--functions');
165
166         if (!$this->bEnableDiffUpdates) {
167             $oCmd->addParams('--no-diff-updates');
168         }
169
170         if ($this->bEnableDebugStatements) {
171             $oCmd->addParams('--enable-debug-statements');
172         }
173
174         $oCmd->run(!$this->sIgnoreErrors);
175     }
176
177     private function pgsqlRunScriptFile($sFilename)
178     {
179         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
180
181         $oCmd = (new \Nominatim\Shell('psql'))
182                 ->addParams('--port', $this->aDSNInfo['port'])
183                 ->addParams('--dbname', $this->aDSNInfo['database']);
184
185         if (!$this->bVerbose) {
186             $oCmd->addParams('--quiet');
187         }
188         if (isset($this->aDSNInfo['hostspec'])) {
189             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
190         }
191         if (isset($this->aDSNInfo['username'])) {
192             $oCmd->addParams('--username', $this->aDSNInfo['username']);
193         }
194         if (isset($this->aDSNInfo['password'])) {
195             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
196         }
197         $ahGzipPipes = null;
198         if (preg_match('/\\.gz$/', $sFilename)) {
199             $aDescriptors = array(
200                              0 => array('pipe', 'r'),
201                              1 => array('pipe', 'w'),
202                              2 => array('file', '/dev/null', 'a')
203                             );
204             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
205
206             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
207             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
208             $aReadPipe = $ahGzipPipes[1];
209             fclose($ahGzipPipes[0]);
210         } else {
211             $oCmd->addParams('--file', $sFilename);
212             $aReadPipe = array('pipe', 'r');
213         }
214         $aDescriptors = array(
215                          0 => $aReadPipe,
216                          1 => array('pipe', 'w'),
217                          2 => array('file', '/dev/null', 'a')
218                         );
219         $ahPipes = null;
220
221         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
222         if (!is_resource($hProcess)) fail('unable to start pgsql');
223         // TODO: error checking
224         while (!feof($ahPipes[1])) {
225             echo fread($ahPipes[1], 4096);
226         }
227         fclose($ahPipes[1]);
228         $iReturn = proc_close($hProcess);
229         if ($iReturn > 0) {
230             fail("pgsql returned with error code ($iReturn)");
231         }
232         if ($ahGzipPipes) {
233             fclose($ahGzipPipes[1]);
234             proc_close($hGzipProcess);
235         }
236     }
237
238     private function replaceSqlPatterns($sSql)
239     {
240         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
241
242         $aPatterns = array(
243                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
244                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
245                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
246                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
247                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
248                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
249         );
250
251         foreach ($aPatterns as $sPattern => $sTablespace) {
252             if ($sTablespace) {
253                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
254             } else {
255                 $sSql = str_replace($sPattern, '', $sSql);
256             }
257         }
258
259         return $sSql;
260     }
261 }