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