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