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