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