]> git.openstreetmap.org Git - nominatim.git/blob - lib/classes/SetupClass.php
120f625eadd8b5a44429614a7503d7e2fe9516e7
[nominatim.git] / lib / classes / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 class SetupFunctions
6 {
7     protected $iCacheMemory;            // set in constructor
8     protected $iInstances;              // set in constructor
9     protected $sModulePath;             // set in constructor
10     protected $aDSNInfo;                // set in constructor = DB::parseDSN(CONST_Database_DSN);
11     protected $sVerbose;                // set in constructor
12     protected $sIgnoreErrors;           // set in constructor
13     protected $bEnableDiffUpdates;      // set in constructor
14     protected $bEnableDebugStatements;  // set in constructor
15     protected $bNoPartitions;           // set in constructor
16     protected $oDB = null;              // set in setupDB (earliest) or later in loadData, importData, drop, createSqlFunctions, importTigerData
17                                                 // pgsqlRunPartitionScript, calculatePostcodes, ..if no already set
18
19     public function __construct($aCMDResult)
20     {
21         // by default, use all but one processor, but never more than 15.
22         $this->iInstances = isset($aCMDResult['threads'])
23             ? $aCMDResult['threads']
24             : (min(16, getProcessorCount()) - 1);
25
26
27         if ($this->iInstances < 1) {
28             $this->iInstances = 1;
29             warn('resetting threads to '.$this->iInstances);
30         }
31
32         // Assume we can steal all the cache memory in the box (unless told otherwise)
33         if (isset($aCMDResult['osm2pgsql-cache'])) {
34             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
35         } else {
36             $this->iCacheMemory = getCacheMemoryMB();
37         }
38
39         $this->sModulePath = CONST_Database_Module_Path;
40         info('module path: ' . $this->sModulePath);
41        
42         // prepares DB for import or update, sets the Data Source Name
43         $this->aDSNInfo = \DB::parseDSN(CONST_Database_DSN);
44         if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
45  
46         // setting member variables based on command line options stored in $aCMDResult
47         $this->sVerbose = $aCMDResult['verbose'];
48         $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
49
50         //setting default values which are not set by the update.php array
51         if (isset($aCMDResult['ignore-errors'])) {
52             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
53         } else {
54             $this->sIgnoreErrors = false;
55         }
56         if (isset($aCMDResult['enable-debug-statements'])) {
57             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
58         } else {
59             $this->bEnableDebugStatements = false;
60         }
61         if (isset($aCMDResult['no-partitions'])) {
62             $this->bNoPartitions = $aCMDResult['no-partitions'];
63         } else {
64             $this->bNoPartitions = false;
65         }
66     }
67
68     public function createDB()
69     {
70         info('Create DB');
71         $sDB = \DB::connect(CONST_Database_DSN, false);
72         if (!\PEAR::isError($sDB)) {
73             fail('database already exists ('.CONST_Database_DSN.')');
74         }
75
76         $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
77         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
78             $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
79         }
80
81         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
82             $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
83         }
84
85         $aProcEnv = null;
86         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
87             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
88         }
89
90         $result = runWithEnv($sCreateDBCmd, $aProcEnv);
91         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
92     }
93
94     public function setupDB()
95     {
96         info('Setup DB');
97         $this->oDB =& getDB();
98
99         $fPostgresVersion = getPostgresVersion($this->oDB);
100         echo 'Postgres version found: '.$fPostgresVersion."\n";
101
102         if ($fPostgresVersion < 9.1) {
103             fail('Minimum supported version of Postgresql is 9.1.');
104         }
105
106         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
107         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
108
109         // For extratags and namedetails the hstore_to_json converter is
110         // needed which is only available from Postgresql 9.3+. For older
111         // versions add a dummy function that returns nothing.
112         $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
113
114         if ($iNumFunc == 0) {
115             $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
116             warn('Postgresql is too old. extratags and namedetails API not available.');
117         }
118
119
120         $fPostgisVersion = getPostgisVersion($this->oDB);
121         echo 'Postgis version found: '.$fPostgisVersion."\n";
122
123         if ($fPostgisVersion < 2.1) {
124             // Functions were renamed in 2.1 and throw an annoying deprecation warning
125             $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
126             $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
127         }
128         if ($fPostgisVersion < 2.2) {
129             $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
130         }
131
132         $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
133         if ($i == 0) {
134             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
135             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
136             exit(1);
137         }
138
139         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
140             echo 'Error: you need to download the country_osm_grid first:';
141             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
142             exit(1);
143         }
144         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
145         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
146         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
147         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
148
149
150         if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
151             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
152         } else {
153             warn('external UK postcode table not found.');
154         }
155
156         if (CONST_Use_Extra_US_Postcodes) {
157             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
158         }
159
160         if ($this->bNoPartitions) {
161             $this->pgsqlRunScript('update country_name set partition = 0');
162         }
163
164         // the following will be needed by create_functions later but
165         // is only defined in the subsequently called T
166         // Create dummies here that will be overwritten by the proper
167         // versions in create-tables.
168         $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
169         $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
170     }
171
172     public function importData($sOSMFile)
173     {
174         info('Import data');
175
176         $osm2pgsql = CONST_Osm2pgsql_Binary;
177         if (!file_exists($osm2pgsql)) {
178             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
179             echo "Normally you should not need to set this manually.\n";
180             fail("osm2pgsql not found in '$osm2pgsql'");
181         }
182
183
184
185         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
186             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
187         }
188
189         if (CONST_Tablespace_Osm2pgsql_Data)
190             $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
191         if (CONST_Tablespace_Osm2pgsql_Index)
192             $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
193         if (CONST_Tablespace_Place_Data)
194             $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
195         if (CONST_Tablespace_Place_Index)
196             $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
197         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
198         $osm2pgsql .= ' -C '.$this->iCacheMemory;
199         $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
200         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
201             $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
202         }
203         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
204             $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
205         }
206         $aProcEnv = null;
207         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
208             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
209         }
210         $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
211         runWithEnv($osm2pgsql, $aProcEnv);
212         if ($this->oDB == null) $this->oDB =& getDB();
213         if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
214             fail('No Data');
215         }
216     }
217
218     public function createFunctions()
219     {
220         info('Create Functions');
221
222         $this->createSqlFunctions();
223     }
224
225     public function createTables()
226     {
227         info('Create Tables');
228
229         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
230         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
231         $sTemplate = $this->replaceTablespace(
232             '{ts:address-data}',
233             CONST_Tablespace_Address_Data,
234             $sTemplate
235         );
236         $sTemplate = $this->replaceTablespace(
237             '{ts:address-index}',
238             CONST_Tablespace_Address_Index,
239             $sTemplate
240         );
241         $sTemplate = $this->replaceTablespace(
242             '{ts:search-data}',
243             CONST_Tablespace_Search_Data,
244             $sTemplate
245         );
246         $sTemplate = $this->replaceTablespace(
247             '{ts:search-index}',
248             CONST_Tablespace_Search_Index,
249             $sTemplate
250         );
251         $sTemplate = $this->replaceTablespace(
252             '{ts:aux-data}',
253             CONST_Tablespace_Aux_Data,
254             $sTemplate
255         );
256         $sTemplate = $this->replaceTablespace(
257             '{ts:aux-index}',
258             CONST_Tablespace_Aux_Index,
259             $sTemplate
260         );
261
262         $this->pgsqlRunScript($sTemplate, false);
263     }
264
265     public function createPartitionTables()
266     {
267         info('Create Partition Tables');
268
269         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
270         $sTemplate = $this->replaceTablespace(
271             '{ts:address-data}',
272             CONST_Tablespace_Address_Data,
273             $sTemplate
274         );
275
276         $sTemplate = $this->replaceTablespace(
277             '{ts:address-index}',
278             CONST_Tablespace_Address_Index,
279             $sTemplate
280         );
281
282         $sTemplate = $this->replaceTablespace(
283             '{ts:search-data}',
284             CONST_Tablespace_Search_Data,
285             $sTemplate
286         );
287
288         $sTemplate = $this->replaceTablespace(
289             '{ts:search-index}',
290             CONST_Tablespace_Search_Index,
291             $sTemplate
292         );
293
294         $sTemplate = $this->replaceTablespace(
295             '{ts:aux-data}',
296             CONST_Tablespace_Aux_Data,
297             $sTemplate
298         );
299
300         $sTemplate = $this->replaceTablespace(
301             '{ts:aux-index}',
302             CONST_Tablespace_Aux_Index,
303             $sTemplate
304         );
305
306         $this->pgsqlRunPartitionScript($sTemplate);
307     }
308
309     public function createPartitionFunctions()
310     {
311         info('Create Partition Functions');
312
313         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
314         $this->pgsqlRunPartitionScript($sTemplate);
315     }
316
317     public function importWikipediaArticles()
318     {
319         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
320         $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
321         if (file_exists($sWikiArticlesFile)) {
322             info('Importing wikipedia articles');
323             $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
324         } else {
325             warn('wikipedia article dump file not found - places will have default importance');
326         }
327         if (file_exists($sWikiRedirectsFile)) {
328             info('Importing wikipedia redirects');
329             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
330         } else {
331             warn('wikipedia redirect dump file not found - some place importance values may be missing');
332         }
333         echo ' finish wikipedia';
334     }
335
336     public function loadData($bDisableTokenPrecalc)
337     {
338         info('Drop old Data');
339
340         if ($this->oDB == null) $this->oDB =& getDB();
341
342         if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
343         echo '.';
344         if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
345         echo '.';
346         if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
347         echo '.';
348         if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
349         echo '.';
350         if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
351         echo '.';
352         if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
353         echo '.';
354         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
355         echo '.';
356         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
357         echo '.';
358         if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
359         echo '.';
360         if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
361         echo '.';
362
363         $sSQL = 'select distinct partition from country_name';
364         $aPartitions = chksql($this->oDB->getCol($sSQL));
365         if (!$this->bNoPartitions) $aPartitions[] = 0;
366         foreach ($aPartitions as $sPartition) {
367             if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
368             echo '.';
369         }
370
371         // used by getorcreate_word_id to ignore frequent partial words
372         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
373         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
374         if (!pg_query($this->oDB->connection, $sSQL)) {
375             fail(pg_last_error($this->oDB->connection));
376         }
377         echo ".\n";
378
379         // pre-create the word list
380         if (!$bDisableTokenPrecalc) {
381             info('Loading word list');
382             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
383         }
384
385         info('Load Data');
386         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
387         $aDBInstances = array();
388         $iLoadThreads = max(1, $this->iInstances - 1);
389         for ($i = 0; $i < $iLoadThreads; $i++) {
390             $aDBInstances[$i] =& getDB(true);
391             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
392             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
393             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
394             $sSQL .= ' and ST_IsValid(geometry)';
395             if ($this->sVerbose) echo "$sSQL\n";
396             if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
397                 fail(pg_last_error($aDBInstances[$i]->connection));
398             }
399         }
400
401         // last thread for interpolation lines
402         $aDBInstances[$iLoadThreads] =& getDB(true);
403         $sSQL = 'insert into location_property_osmline';
404         $sSQL .= ' (osm_id, address, linegeo)';
405         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
406         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
407         if ($this->sVerbose) echo "$sSQL\n";
408         if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
409             fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
410         }
411
412         $bFailed = false;
413         for ($i = 0; $i <= $iLoadThreads; $i++) {
414             while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
415                 $resultStatus = pg_result_status($hPGresult);
416                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
417                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
418                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
419                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
420                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
421                     $resultError = pg_result_error($hPGresult);
422                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
423                     $bFailed = true;
424                 }
425             }
426         }
427         if ($bFailed) {
428             fail('SQL errors loading placex and/or location_property_osmline tables');
429         }
430         echo "\n";
431         info('Reanalysing database');
432         $this->pgsqlRunScript('ANALYSE');
433
434         $sDatabaseDate = getDatabaseDate($this->oDB);
435         pg_query($this->oDB->connection, 'TRUNCATE import_status');
436         if ($sDatabaseDate === false) {
437             warn('could not determine database date.');
438         } else {
439             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
440             pg_query($this->oDB->connection, $sSQL);
441             echo "Latest data imported from $sDatabaseDate.\n";
442         }
443     }
444
445     public function importTigerData()
446     {
447         info('Import Tiger data');
448
449         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
450         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
451         $sTemplate = $this->replaceTablespace(
452             '{ts:aux-data}',
453             CONST_Tablespace_Aux_Data,
454             $sTemplate
455         );
456         $sTemplate = $this->replaceTablespace(
457             '{ts:aux-index}',
458             CONST_Tablespace_Aux_Index,
459             $sTemplate
460         );
461         $this->pgsqlRunScript($sTemplate, false);
462
463         $aDBInstances = array();
464         for ($i = 0; $i < $this->iInstances; $i++) {
465             $aDBInstances[$i] =& getDB(true);
466         }
467
468         foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
469             echo $sFile.': ';
470             $hFile = fopen($sFile, 'r');
471             $sSQL = fgets($hFile, 100000);
472             $iLines = 0;
473             while (true) {
474                 for ($i = 0; $i < $this->iInstances; $i++) {
475                     if (!pg_connection_busy($aDBInstances[$i]->connection)) {
476                         while (pg_get_result($aDBInstances[$i]->connection));
477                         $sSQL = fgets($hFile, 100000);
478                         if (!$sSQL) break 2;
479                         if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
480                         $iLines++;
481                         if ($iLines == 1000) {
482                             echo '.';
483                             $iLines = 0;
484                         }
485                     }
486                 }
487                 usleep(10);
488             }
489             fclose($hFile);
490
491             $bAnyBusy = true;
492             while ($bAnyBusy) {
493                 $bAnyBusy = false;
494                 for ($i = 0; $i < $this->iInstances; $i++) {
495                     if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
496                 }
497                 usleep(10);
498             }
499             echo "\n";
500         }
501
502         info('Creating indexes on Tiger data');
503         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
504         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
505         $sTemplate = $this->replaceTablespace(
506             '{ts:aux-data}',
507             CONST_Tablespace_Aux_Data,
508             $sTemplate
509         );
510         $sTemplate = $this->replaceTablespace(
511             '{ts:aux-index}',
512             CONST_Tablespace_Aux_Index,
513             $sTemplate
514         );
515         $this->pgsqlRunScript($sTemplate, false);
516     }
517
518     public function calculatePostcodes($bCMDResultAll)
519     {
520         info('Calculate Postcodes');
521         if ($this->oDB == null) $this->oDB =& getDB();
522         if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
523             fail(pg_last_error($this->oDB->connection));
524         }
525
526
527         $sSQL  = 'INSERT INTO location_postcode';
528         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
529         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
530         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
531         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
532         $sSQL .= '  FROM placex';
533         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
534         $sSQL .= '       AND geometry IS NOT null';
535         $sSQL .= ' GROUP BY country_code, pc';
536
537         if (!pg_query($this->oDB->connection, $sSQL)) {
538             fail(pg_last_error($this->oDB->connection));
539         }
540
541         if (CONST_Use_Extra_US_Postcodes) {
542             // only add postcodes that are not yet available in OSM
543             $sSQL  = 'INSERT INTO location_postcode';
544             $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
545             $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
546             $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
547             $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
548             $sSQL .= '        (SELECT postcode FROM location_postcode';
549             $sSQL .= "          WHERE country_code = 'us')";
550             if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
551         }
552
553         // add missing postcodes for GB (if available)
554         $sSQL  = 'INSERT INTO location_postcode';
555         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
556         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
557         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
558         $sSQL .= '           (SELECT postcode FROM location_postcode';
559         $sSQL .= "             WHERE country_code = 'gb')";
560         if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
561
562         if (!$bCMDResultAll) {
563             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
564             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
565             if (!pg_query($this->oDB->connection, $sSQL)) {
566                 fail(pg_last_error($this->oDB->connection));
567             }
568         }
569         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
570         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
571
572         if (!pg_query($this->oDB->connection, $sSQL)) {
573             fail(pg_last_error($this->oDB->connection));
574         }
575     }
576
577     public function index($bIndexNoanalyse)
578     {
579         $sOutputFile = '';
580         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
581             .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
582         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
583             $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
584         }
585         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
586             $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
587         }
588         $aProcEnv = null;
589         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
590             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
591         }
592
593         info('Index ranks 0 - 4');
594         $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
595         if ($iStatus != 0) {
596             fail('error status ' . $iStatus . ' running nominatim!');
597         }
598         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
599         info('Index ranks 5 - 25');
600         $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
601         if ($iStatus != 0) {
602             fail('error status ' . $iStatus . ' running nominatim!');
603         }
604         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
605         info('Index ranks 26 - 30');
606         $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
607         if ($iStatus != 0) {
608             fail('error status ' . $iStatus . ' running nominatim!');
609         }
610         info('Index postcodes');
611         if ($this->oDB == null) $this->oDB =& getDB();
612         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
613         if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
614     }
615
616     public function createSearchIndices()
617     {
618         info('Create Search indices');
619
620         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
621         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
622         $sTemplate = $this->replaceTablespace(
623             '{ts:address-index}',
624             CONST_Tablespace_Address_Index,
625             $sTemplate
626         );
627         $sTemplate = $this->replaceTablespace(
628             '{ts:search-index}',
629             CONST_Tablespace_Search_Index,
630             $sTemplate
631         );
632         $sTemplate = $this->replaceTablespace(
633             '{ts:aux-index}',
634             CONST_Tablespace_Aux_Index,
635             $sTemplate
636         );
637         $this->pgsqlRunScript($sTemplate);
638     }
639
640     public function createCountryNames()
641     {
642         info('Create search index for default country names');
643
644         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
645         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
646         $this->pgsqlRunScript('select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x');
647         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
648         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
649             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
650         if (CONST_Languages) {
651             $sSQL .= 'in ';
652             $sDelim = '(';
653             foreach (explode(',', CONST_Languages) as $sLang) {
654                 $sSQL .= $sDelim."'name:$sLang'";
655                 $sDelim = ',';
656             }
657             $sSQL .= ')';
658         } else {
659             // all include all simple name tags
660             $sSQL .= "like 'name:%'";
661         }
662         $sSQL .= ') v';
663         $this->pgsqlRunScript($sSQL);
664     }
665
666     public function drop()
667     {
668         info('Drop tables only required for updates');
669
670         // The implementation is potentially a bit dangerous because it uses
671         // a positive selection of tables to keep, and deletes everything else.
672         // Including any tables that the unsuspecting user might have manually
673         // created. USE AT YOUR OWN PERIL.
674         // tables we want to keep. everything else goes.
675         $aKeepTables = array(
676                         '*columns',
677                         'import_polygon_*',
678                         'import_status',
679                         'place_addressline',
680                         'location_postcode',
681                         'location_property*',
682                         'placex',
683                         'search_name',
684                         'seq_*',
685                         'word',
686                         'query_log',
687                         'new_query_log',
688                         'spatial_ref_sys',
689                         'country_name',
690                         'place_classtype_*'
691                        );
692
693         if ($this->oDB = null) $this->oDB =& getDB();
694         $aDropTables = array();
695         $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
696
697         foreach ($aHaveTables as $sTable) {
698             $bFound = false;
699             foreach ($aKeepTables as $sKeep) {
700                 if (fnmatch($sKeep, $sTable)) {
701                     $bFound = true;
702                     break;
703                 }
704             }
705             if (!$bFound) array_push($aDropTables, $sTable);
706         }
707         foreach ($aDropTables as $sDrop) {
708             if ($this->sVerbose) echo "dropping table $sDrop\n";
709             @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
710             // ignore warnings/errors as they might be caused by a table having
711             // been deleted already by CASCADE
712         }
713
714         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
715             if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
716             unlink(CONST_Osm2pgsql_Flatnode_File);
717         }
718     }
719
720     private function pgsqlRunDropAndRestore($sDumpFile)
721     {
722         if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
723         $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
724         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
725             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
726         }
727         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
728             $sCMD .= ' -U '.$this->aDSNInfo['username'];
729         }
730         $aProcEnv = null;
731         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
732             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
733         }
734         $iReturn = runWithEnv($sCMD, $aProcEnv);    // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
735     }
736                      
737     private function pgsqlRunScript($sScript, $bfatal = true)
738     {
739         runSQLScript(
740             $sScript,
741             $bfatal,
742             $this->sVerbose,
743             $this->sIgnoreErrors
744         );
745     }
746
747     private function createSqlFunctions()
748     {
749         $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
750         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
751         if ($this->bEnableDiffUpdates) {
752             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
753         }
754         if ($this->bEnableDebugStatements) {
755             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
756         }
757         if (CONST_Limit_Reindexing) {
758             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
759         }
760         if (!CONST_Use_US_Tiger_Data) {
761             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
762         }
763         if (!CONST_Use_Aux_Location_data) {
764             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
765         }
766         $this->pgsqlRunScript($sTemplate);
767     }
768
769     private function pgsqlRunPartitionScript($sTemplate)
770     {
771         if ($this->oDB == null) $this->oDB =& getDB();
772
773         $sSQL = 'select distinct partition from country_name';
774         $aPartitions = chksql($this->oDB->getCol($sSQL));
775         if (!$this->bNoPartitions) $aPartitions[] = 0;
776
777         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
778         foreach ($aMatches as $aMatch) {
779             $sResult = '';
780             foreach ($aPartitions as $sPartitionName) {
781                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
782             }
783             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
784         }
785
786         $this->pgsqlRunScript($sTemplate);
787     }
788
789     private function pgsqlRunScriptFile($sFilename)
790     {
791         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
792
793         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
794         if (!$this->sVerbose) {
795             $sCMD .= ' -q';
796         }
797         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
798             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
799         }
800         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
801             $sCMD .= ' -U '.$this->aDSNInfo['username'];
802         }
803         $aProcEnv = null;
804         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
805             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
806         }
807         $ahGzipPipes = null;
808         if (preg_match('/\\.gz$/', $sFilename)) {
809             $aDescriptors = array(
810                              0 => array('pipe', 'r'),
811                              1 => array('pipe', 'w'),
812                              2 => array('file', '/dev/null', 'a')
813                             );
814             $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
815             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
816             $aReadPipe = $ahGzipPipes[1];
817             fclose($ahGzipPipes[0]);
818         } else {
819             $sCMD .= ' -f '.$sFilename;
820             $aReadPipe = array('pipe', 'r');
821         }
822         $aDescriptors = array(
823                          0 => $aReadPipe,
824                          1 => array('pipe', 'w'),
825                          2 => array('file', '/dev/null', 'a')
826                         );
827         $ahPipes = null;
828         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
829         if (!is_resource($hProcess)) fail('unable to start pgsql');
830         // TODO: error checking
831         while (!feof($ahPipes[1])) {
832             echo fread($ahPipes[1], 4096);
833         }
834         fclose($ahPipes[1]);
835         $iReturn = proc_close($hProcess);
836         if ($iReturn > 0) {
837             fail("pgsql returned with error code ($iReturn)");
838         }
839         if ($ahGzipPipes) {
840             fclose($ahGzipPipes[1]);
841             proc_close($hGzipProcess);
842         }
843     }
844
845     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
846     {
847         if ($sTablespace) {
848             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
849         } else {
850             $sSql = str_replace($sTemplate, '', $sSql);
851         }
852         return $sSql;
853     }
854 }