]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/setup/SetupClass.php
port setup-website to python
[nominatim.git] / lib-php / 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                 if (!file_exists($sDest)) {
152                     mkdir($sDest);
153                 }
154                 if (!copy(CONST_Default_ModulePath.'/nominatim.so', $sDest.'/nominatim.so')) {
155                     echo "Failed to copy database module to $sDest.";
156                     exit(1);
157                 }
158                 chmod($sDest.'/nominatim.so', 0755);
159                 info("Database module installed at $sDest.");
160             } else {
161                 info('Running from build directory. Leaving database module as is.');
162             }
163         } else {
164             info('Using database module from DATABASE_MODULE_PATH ('.getSetting('DATABASE_MODULE_PATH').').');
165         }
166         // Try accessing the C module, so we know early if something is wrong
167         $this->checkModulePresence(); // raises exception on failure
168
169         $this->pgsqlRunScriptFile(CONST_DataDir.'/country_name.sql');
170         $this->pgsqlRunScriptFile(CONST_DataDir.'/country_osm_grid.sql.gz');
171
172         if ($this->bNoPartitions) {
173             $this->pgsqlRunScript('update country_name set partition = 0');
174         }
175     }
176
177     public function importData($sOSMFile)
178     {
179         info('Import data');
180
181         if (!file_exists(getOsm2pgsqlBinary())) {
182             echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
183             echo "Normally you should not need to set this manually.\n";
184             fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
185         }
186
187         $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
188         $oCmd->addParams('--style', getImportStyle());
189
190         if (getSetting('FLATNODE_FILE')) {
191             $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
192         }
193         if (getSetting('TABLESPACE_OSM_DATA')) {
194             $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
195         }
196         if (getSetting('TABLESPACE_OSM_INDEX')) {
197             $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
198         }
199         if (getSetting('TABLESPACE_PLACE_DATA')) {
200             $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
201         }
202         if (getSetting('TABLESPACE_PLACE_INDEX')) {
203             $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
204         }
205         $oCmd->addParams('--latlong', '--slim', '--create');
206         $oCmd->addParams('--output', 'gazetteer');
207         $oCmd->addParams('--hstore');
208         $oCmd->addParams('--number-processes', 1);
209         $oCmd->addParams('--with-forward-dependencies', 'false');
210         $oCmd->addParams('--log-progress', 'true');
211         $oCmd->addParams('--cache', $this->iCacheMemory);
212         $oCmd->addParams('--port', $this->aDSNInfo['port']);
213
214         if (isset($this->aDSNInfo['username'])) {
215             $oCmd->addParams('--username', $this->aDSNInfo['username']);
216         }
217         if (isset($this->aDSNInfo['password'])) {
218             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
219         }
220         if (isset($this->aDSNInfo['hostspec'])) {
221             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
222         }
223         $oCmd->addParams('--database', $this->aDSNInfo['database']);
224         $oCmd->addParams($sOSMFile);
225         $oCmd->run();
226
227         if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
228             fail('No Data');
229         }
230
231         if ($this->bDrop) {
232             $this->dropTable('planet_osm_nodes');
233             $this->removeFlatnodeFile();
234         }
235     }
236
237     public function createFunctions()
238     {
239         info('Create Functions');
240
241         // Try accessing the C module, so we know early if something is wrong
242         $this->checkModulePresence(); // raises exception on failure
243
244         $this->createSqlFunctions();
245     }
246
247     public function createTables($bReverseOnly = false)
248     {
249         info('Create Tables');
250
251         $sTemplate = file_get_contents(CONST_SqlDir.'/tables.sql');
252         $sTemplate = $this->replaceSqlPatterns($sTemplate);
253
254         $this->pgsqlRunScript($sTemplate, false);
255
256         if ($bReverseOnly) {
257             $this->dropTable('search_name');
258         }
259
260         (clone($this->oNominatimCmd))->addParams('refresh', '--address-levels')->run();
261     }
262
263     public function createTableTriggers()
264     {
265         info('Create Tables');
266
267         $sTemplate = file_get_contents(CONST_SqlDir.'/table-triggers.sql');
268         $sTemplate = $this->replaceSqlPatterns($sTemplate);
269
270         $this->pgsqlRunScript($sTemplate, false);
271     }
272
273     public function createPartitionTables()
274     {
275         info('Create Partition Tables');
276
277         $sTemplate = file_get_contents(CONST_SqlDir.'/partition-tables.src.sql');
278         $sTemplate = $this->replaceSqlPatterns($sTemplate);
279
280         $this->pgsqlRunPartitionScript($sTemplate);
281     }
282
283     public function createPartitionFunctions()
284     {
285         info('Create Partition Functions');
286         $this->createSqlFunctions(); // also create partition functions
287     }
288
289     public function importWikipediaArticles()
290     {
291         $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_InstallDir);
292         $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
293         if (file_exists($sWikiArticlesFile)) {
294             info('Importing wikipedia articles and redirects');
295             $this->dropTable('wikipedia_article');
296             $this->dropTable('wikipedia_redirect');
297             $this->pgsqlRunScriptFile($sWikiArticlesFile);
298         } else {
299             warn('wikipedia importance dump file not found - places will have default importance');
300         }
301     }
302
303     public function loadData($bDisableTokenPrecalc)
304     {
305         info('Drop old Data');
306
307         $oDB = $this->db();
308
309         $oDB->exec('TRUNCATE word');
310         echo '.';
311         $oDB->exec('TRUNCATE placex');
312         echo '.';
313         $oDB->exec('TRUNCATE location_property_osmline');
314         echo '.';
315         $oDB->exec('TRUNCATE place_addressline');
316         echo '.';
317         $oDB->exec('TRUNCATE location_area');
318         echo '.';
319         if (!$this->dbReverseOnly()) {
320             $oDB->exec('TRUNCATE search_name');
321             echo '.';
322         }
323         $oDB->exec('TRUNCATE search_name_blank');
324         echo '.';
325         $oDB->exec('DROP SEQUENCE seq_place');
326         echo '.';
327         $oDB->exec('CREATE SEQUENCE seq_place start 100000');
328         echo '.';
329
330         $sSQL = 'select distinct partition from country_name';
331         $aPartitions = $oDB->getCol($sSQL);
332
333         if (!$this->bNoPartitions) $aPartitions[] = 0;
334         foreach ($aPartitions as $sPartition) {
335             $oDB->exec('TRUNCATE location_road_'.$sPartition);
336             echo '.';
337         }
338
339         // used by getorcreate_word_id to ignore frequent partial words
340         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
341         $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
342         $oDB->exec($sSQL);
343         echo ".\n";
344
345         // pre-create the word list
346         if (!$bDisableTokenPrecalc) {
347             info('Loading word list');
348             $this->pgsqlRunScriptFile(CONST_DataDir.'/words.sql');
349         }
350
351         info('Load Data');
352         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
353
354         $aDBInstances = array();
355         $iLoadThreads = max(1, $this->iInstances - 1);
356         for ($i = 0; $i < $iLoadThreads; $i++) {
357             // https://secure.php.net/manual/en/function.pg-connect.php
358             $DSN = getSetting('DATABASE_DSN');
359             $DSN = preg_replace('/^pgsql:/', '', $DSN);
360             $DSN = preg_replace('/;/', ' ', $DSN);
361             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
362             pg_ping($aDBInstances[$i]);
363         }
364
365         for ($i = 0; $i < $iLoadThreads; $i++) {
366             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
367             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
368             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
369             $sSQL .= ' and ST_IsValid(geometry)';
370             if ($this->bVerbose) echo "$sSQL\n";
371             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
372                 fail(pg_last_error($aDBInstances[$i]));
373             }
374         }
375
376         // last thread for interpolation lines
377         // https://secure.php.net/manual/en/function.pg-connect.php
378         $DSN = getSetting('DATABASE_DSN');
379         $DSN = preg_replace('/^pgsql:/', '', $DSN);
380         $DSN = preg_replace('/;/', ' ', $DSN);
381         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
382         pg_ping($aDBInstances[$iLoadThreads]);
383         $sSQL = 'insert into location_property_osmline';
384         $sSQL .= ' (osm_id, address, linegeo)';
385         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
386         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
387         if ($this->bVerbose) echo "$sSQL\n";
388         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
389             fail(pg_last_error($aDBInstances[$iLoadThreads]));
390         }
391
392         $bFailed = false;
393         for ($i = 0; $i <= $iLoadThreads; $i++) {
394             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
395                 $resultStatus = pg_result_status($hPGresult);
396                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
397                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
398                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
399                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
400                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
401                     $resultError = pg_result_error($hPGresult);
402                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
403                     $bFailed = true;
404                 }
405             }
406         }
407         if ($bFailed) {
408             fail('SQL errors loading placex and/or location_property_osmline tables');
409         }
410
411         for ($i = 0; $i < $this->iInstances; $i++) {
412             pg_close($aDBInstances[$i]);
413         }
414
415         echo "\n";
416         info('Reanalysing database');
417         $this->pgsqlRunScript('ANALYSE');
418
419         $sDatabaseDate = getDatabaseDate($oDB);
420         $oDB->exec('TRUNCATE import_status');
421         if (!$sDatabaseDate) {
422             warn('could not determine database date.');
423         } else {
424             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
425             $oDB->exec($sSQL);
426             echo "Latest data imported from $sDatabaseDate.\n";
427         }
428     }
429
430     public function importTigerData($sTigerPath)
431     {
432         info('Import Tiger data');
433
434         $aFilenames = glob($sTigerPath.'/*.sql');
435         info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
436         if (empty($aFilenames)) {
437             warn('Tiger data import selected but no files found in path '.$sTigerPath);
438             return;
439         }
440         $sTemplate = file_get_contents(CONST_SqlDir.'/tiger_import_start.sql');
441         $sTemplate = $this->replaceSqlPatterns($sTemplate);
442
443         $this->pgsqlRunScript($sTemplate, false);
444
445         $aDBInstances = array();
446         for ($i = 0; $i < $this->iInstances; $i++) {
447             // https://secure.php.net/manual/en/function.pg-connect.php
448             $DSN = getSetting('DATABASE_DSN');
449             $DSN = preg_replace('/^pgsql:/', '', $DSN);
450             $DSN = preg_replace('/;/', ' ', $DSN);
451             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
452             pg_ping($aDBInstances[$i]);
453         }
454
455         foreach ($aFilenames as $sFile) {
456             echo $sFile.': ';
457             $hFile = fopen($sFile, 'r');
458             $sSQL = fgets($hFile, 100000);
459             $iLines = 0;
460             while (true) {
461                 for ($i = 0; $i < $this->iInstances; $i++) {
462                     if (!pg_connection_busy($aDBInstances[$i])) {
463                         while (pg_get_result($aDBInstances[$i]));
464                         $sSQL = fgets($hFile, 100000);
465                         if (!$sSQL) break 2;
466                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
467                         $iLines++;
468                         if ($iLines == 1000) {
469                             echo '.';
470                             $iLines = 0;
471                         }
472                     }
473                 }
474                 usleep(10);
475             }
476             fclose($hFile);
477
478             $bAnyBusy = true;
479             while ($bAnyBusy) {
480                 $bAnyBusy = false;
481                 for ($i = 0; $i < $this->iInstances; $i++) {
482                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
483                 }
484                 usleep(10);
485             }
486             echo "\n";
487         }
488
489         for ($i = 0; $i < $this->iInstances; $i++) {
490             pg_close($aDBInstances[$i]);
491         }
492
493         info('Creating indexes on Tiger data');
494         $sTemplate = file_get_contents(CONST_SqlDir.'/tiger_import_finish.sql');
495         $sTemplate = $this->replaceSqlPatterns($sTemplate);
496
497         $this->pgsqlRunScript($sTemplate, false);
498     }
499
500     public function calculatePostcodes($bCMDResultAll)
501     {
502         info('Calculate Postcodes');
503         $this->pgsqlRunScriptFile(CONST_SqlDir.'/postcode_tables.sql');
504
505         $sPostcodeFilename = CONST_InstallDir.'/gb_postcode_data.sql.gz';
506         if (file_exists($sPostcodeFilename)) {
507             $this->pgsqlRunScriptFile($sPostcodeFilename);
508         } else {
509             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
510         }
511
512         $sPostcodeFilename = CONST_InstallDir.'/us_postcode_data.sql.gz';
513         if (file_exists($sPostcodeFilename)) {
514             $this->pgsqlRunScriptFile($sPostcodeFilename);
515         } else {
516             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
517         }
518
519
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_SqlDir.'/indices.src.sql');
620         if (!$this->bDrop) {
621             $sTemplate .= file_get_contents(CONST_SqlDir.'/indices_updates.src.sql');
622         }
623         if (!$this->dbReverseOnly()) {
624             $sTemplate .= file_get_contents(CONST_SqlDir.'/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         (clone($this->oNominatimCmd))->addParams('freeze')->run();
661     }
662
663     /**
664      * Setup the directory for the API scripts.
665      *
666      * @return null
667      */
668     public function setupWebsite()
669     {
670         (clone($this->oNominatimCmd))->addParams('refresh', '--website')->run();
671     }
672
673     /**
674      * Return the connection to the database.
675      *
676      * @return Database object.
677      *
678      * Creates a new connection if none exists yet. Otherwise reuses the
679      * already established connection.
680      */
681     private function db()
682     {
683         if (is_null($this->oDB)) {
684             $this->oDB = new \Nominatim\DB();
685             $this->oDB->connect();
686         }
687
688         return $this->oDB;
689     }
690
691     private function removeFlatnodeFile()
692     {
693         $sFName = getSetting('FLATNODE_FILE');
694         if ($sFName && file_exists($sFName)) {
695             if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
696             unlink($sFName);
697         }
698     }
699
700     private function pgsqlRunScript($sScript, $bfatal = true)
701     {
702         runSQLScript(
703             $sScript,
704             $bfatal,
705             $this->bVerbose,
706             $this->sIgnoreErrors
707         );
708     }
709
710     private function createSqlFunctions()
711     {
712         $oCmd = (clone($this->oNominatimCmd))
713                 ->addParams('refresh', '--functions');
714
715         if (!$this->bEnableDiffUpdates) {
716             $oCmd->addParams('--no-diff-updates');
717         }
718
719         if ($this->bEnableDebugStatements) {
720             $oCmd->addParams('--enable-debug-statements');
721         }
722
723         $oCmd->run();
724     }
725
726     private function pgsqlRunPartitionScript($sTemplate)
727     {
728         $sSQL = 'select distinct partition from country_name';
729         $aPartitions = $this->db()->getCol($sSQL);
730         if (!$this->bNoPartitions) $aPartitions[] = 0;
731
732         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
733         foreach ($aMatches as $aMatch) {
734             $sResult = '';
735             foreach ($aPartitions as $sPartitionName) {
736                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
737             }
738             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
739         }
740
741         $this->pgsqlRunScript($sTemplate);
742     }
743
744     private function pgsqlRunScriptFile($sFilename)
745     {
746         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
747
748         $oCmd = (new \Nominatim\Shell('psql'))
749                 ->addParams('--port', $this->aDSNInfo['port'])
750                 ->addParams('--dbname', $this->aDSNInfo['database']);
751
752         if (!$this->bVerbose) {
753             $oCmd->addParams('--quiet');
754         }
755         if (isset($this->aDSNInfo['hostspec'])) {
756             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
757         }
758         if (isset($this->aDSNInfo['username'])) {
759             $oCmd->addParams('--username', $this->aDSNInfo['username']);
760         }
761         if (isset($this->aDSNInfo['password'])) {
762             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
763         }
764         $ahGzipPipes = null;
765         if (preg_match('/\\.gz$/', $sFilename)) {
766             $aDescriptors = array(
767                              0 => array('pipe', 'r'),
768                              1 => array('pipe', 'w'),
769                              2 => array('file', '/dev/null', 'a')
770                             );
771             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
772
773             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
774             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
775             $aReadPipe = $ahGzipPipes[1];
776             fclose($ahGzipPipes[0]);
777         } else {
778             $oCmd->addParams('--file', $sFilename);
779             $aReadPipe = array('pipe', 'r');
780         }
781         $aDescriptors = array(
782                          0 => $aReadPipe,
783                          1 => array('pipe', 'w'),
784                          2 => array('file', '/dev/null', 'a')
785                         );
786         $ahPipes = null;
787
788         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
789         if (!is_resource($hProcess)) fail('unable to start pgsql');
790         // TODO: error checking
791         while (!feof($ahPipes[1])) {
792             echo fread($ahPipes[1], 4096);
793         }
794         fclose($ahPipes[1]);
795         $iReturn = proc_close($hProcess);
796         if ($iReturn > 0) {
797             fail("pgsql returned with error code ($iReturn)");
798         }
799         if ($ahGzipPipes) {
800             fclose($ahGzipPipes[1]);
801             proc_close($hGzipProcess);
802         }
803     }
804
805     private function replaceSqlPatterns($sSql)
806     {
807         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
808
809         $aPatterns = array(
810                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
811                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
812                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
813                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
814                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
815                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
816         );
817
818         foreach ($aPatterns as $sPattern => $sTablespace) {
819             if ($sTablespace) {
820                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
821             } else {
822                 $sSql = str_replace($sPattern, '', $sSql);
823             }
824         }
825
826         return $sSql;
827     }
828
829     /**
830      * Drop table with the given name if it exists.
831      *
832      * @param string $sName Name of table to remove.
833      *
834      * @return null
835      */
836     private function dropTable($sName)
837     {
838         if ($this->bVerbose) echo "Dropping table $sName\n";
839         $this->db()->deleteTable($sName);
840     }
841
842     /**
843      * Check if the database is in reverse-only mode.
844      *
845      * @return True if there is no search_name table and infrastructure.
846      */
847     private function dbReverseOnly()
848     {
849         return !($this->db()->tableExists('search_name'));
850     }
851
852     /**
853      * Try accessing the C module, so we know early if something is wrong.
854      *
855      * Raises Nominatim\DatabaseError on failure
856      */
857     private function checkModulePresence()
858     {
859         $sModulePath = getSetting('DATABASE_MODULE_PATH', CONST_InstallDir.'/module');
860         $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
861         $sSQL .= $sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
862         $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
863
864         $oDB = new \Nominatim\DB();
865         $oDB->connect();
866         $oDB->exec($sSQL, null, 'Database server failed to load '.$sModulePath.'/nominatim.so module');
867     }
868 }