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