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