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