3 namespace Nominatim\Setup;
5 require_once(CONST_LibDir.'/Shell.php');
9 protected $iCacheMemory;
10 protected $iInstances;
11 protected $sModulePath;
15 protected $sIgnoreErrors;
16 protected $bEnableDiffUpdates;
17 protected $bEnableDebugStatements;
18 protected $bNoPartitions;
20 protected $oDB = null;
21 protected $oNominatimCmd;
23 public function __construct(array $aCMDResult)
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);
30 if ($this->iInstances < 1) {
31 $this->iInstances = 1;
32 warn('resetting threads to '.$this->iInstances);
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;
41 // Otherwise: Assume we can steal all the cache memory in the box.
42 $this->iCacheMemory = getCacheMemoryMB();
45 $this->sModulePath = getSetting('DATABASE_MODULE_PATH');
46 if (!$this->sModulePath) {
47 $this->sModulePath = CONST_Default_ModulePath;
49 info('module path: ' . $this->sModulePath);
51 // parse database string
52 $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
53 if (!isset($this->aDSNInfo['port'])) {
54 $this->aDSNInfo['port'] = 5432;
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'];
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'];
65 $this->sIgnoreErrors = false;
67 if (isset($aCMDResult['enable-debug-statements'])) {
68 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
70 $this->bEnableDebugStatements = false;
72 if (isset($aCMDResult['no-partitions'])) {
73 $this->bNoPartitions = $aCMDResult['no-partitions'];
75 $this->bNoPartitions = false;
77 if (isset($aCMDResult['enable-diff-updates'])) {
78 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
80 $this->bEnableDiffUpdates = false;
83 $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
85 $this->oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
87 $this->oNominatimCmd->addParams('--quiet');
89 if ($this->bVerbose) {
90 $this->oNominatimCmd->addParams('--verbose');
94 public function createDB()
97 $oDB = new \Nominatim\DB;
99 if ($oDB->checkConnection()) {
100 fail('database already exists ('.getSetting('DATABASE_DSN').')');
103 $oCmd = (new \Nominatim\Shell('createdb'))
104 ->addParams('-E', 'UTF-8')
105 ->addParams('-p', $this->aDSNInfo['port']);
107 if (isset($this->aDSNInfo['username'])) {
108 $oCmd->addParams('-U', $this->aDSNInfo['username']);
110 if (isset($this->aDSNInfo['password'])) {
111 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
113 if (isset($this->aDSNInfo['hostspec'])) {
114 $oCmd->addParams('-h', $this->aDSNInfo['hostspec']);
116 $oCmd->addParams($this->aDSNInfo['database']);
118 $result = $oCmd->run();
119 if ($result != 0) fail('Error executing external command: '.$oCmd->escapedCmd());
122 public function setupDB()
126 $fPostgresVersion = $this->db()->getPostgresVersion();
127 echo 'Postgres version found: '.$fPostgresVersion."\n";
129 if ($fPostgresVersion < 9.03) {
130 fail('Minimum supported version of Postgresql is 9.3.');
133 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
134 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
136 $fPostgisVersion = $this->db()->getPostgisVersion();
137 echo 'Postgis version found: '.$fPostgisVersion."\n";
139 if ($fPostgisVersion < 2.2) {
140 echo "Minimum required Postgis version 2.2\n";
144 $sPgUser = getSetting('DATABASE_WEBUSER');
145 $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
147 echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
148 echo "\n createuser ".$sPgUser."\n\n";
152 // Try accessing the C module, so we know early if something is wrong
153 $this->checkModulePresence(); // raises exception on failure
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";
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');
165 $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
166 if (file_exists($sPostcodeFilename)) {
167 $this->pgsqlRunScriptFile($sPostcodeFilename);
169 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
172 $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
173 if (file_exists($sPostcodeFilename)) {
174 $this->pgsqlRunScriptFile($sPostcodeFilename);
176 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
179 if ($this->bNoPartitions) {
180 $this->pgsqlRunScript('update country_name set partition = 0');
184 public function importData($sOSMFile)
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()."'");
194 $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
195 $oCmd->addParams('--style', getImportStyle());
197 if (getSetting('FLATNODE_FILE')) {
198 $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
200 if (getSetting('TABLESPACE_OSM_DATA')) {
201 $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
203 if (getSetting('TABLESPACE_OSM_INDEX')) {
204 $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
206 if (getSetting('TABLESPACE_PLACE_DATA')) {
207 $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
209 if (getSetting('TABLESPACE_PLACE_INDEX')) {
210 $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
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']);
221 if (isset($this->aDSNInfo['username'])) {
222 $oCmd->addParams('--username', $this->aDSNInfo['username']);
224 if (isset($this->aDSNInfo['password'])) {
225 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
227 if (isset($this->aDSNInfo['hostspec'])) {
228 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
230 $oCmd->addParams('--database', $this->aDSNInfo['database']);
231 $oCmd->addParams($sOSMFile);
234 if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
239 $this->dropTable('planet_osm_nodes');
240 $this->removeFlatnodeFile();
244 public function createFunctions()
246 info('Create Functions');
248 // Try accessing the C module, so we know early if something is wrong
249 $this->checkModulePresence(); // raises exception on failure
251 $this->createSqlFunctions();
254 public function createTables($bReverseOnly = false)
256 info('Create Tables');
258 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
259 $sTemplate = $this->replaceSqlPatterns($sTemplate);
261 $this->pgsqlRunScript($sTemplate, false);
264 $this->dropTable('search_name');
267 (clone($this->oNominatimCmd))->addParams('refresh', '--address-levels')->run();
270 public function createTableTriggers()
272 info('Create Tables');
274 $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
275 $sTemplate = $this->replaceSqlPatterns($sTemplate);
277 $this->pgsqlRunScript($sTemplate, false);
280 public function createPartitionTables()
282 info('Create Partition Tables');
284 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
285 $sTemplate = $this->replaceSqlPatterns($sTemplate);
287 $this->pgsqlRunPartitionScript($sTemplate);
290 public function createPartitionFunctions()
292 info('Create Partition Functions');
294 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
295 $this->pgsqlRunPartitionScript($sTemplate);
298 public function importWikipediaArticles()
300 $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
301 $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
302 if (file_exists($sWikiArticlesFile)) {
303 info('Importing wikipedia articles and redirects');
304 $this->dropTable('wikipedia_article');
305 $this->dropTable('wikipedia_redirect');
306 $this->pgsqlRunScriptFile($sWikiArticlesFile);
308 warn('wikipedia importance dump file not found - places will have default importance');
312 public function loadData($bDisableTokenPrecalc)
314 info('Drop old Data');
318 $oDB->exec('TRUNCATE word');
320 $oDB->exec('TRUNCATE placex');
322 $oDB->exec('TRUNCATE location_property_osmline');
324 $oDB->exec('TRUNCATE place_addressline');
326 $oDB->exec('TRUNCATE location_area');
328 if (!$this->dbReverseOnly()) {
329 $oDB->exec('TRUNCATE search_name');
332 $oDB->exec('TRUNCATE search_name_blank');
334 $oDB->exec('DROP SEQUENCE seq_place');
336 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
339 $sSQL = 'select distinct partition from country_name';
340 $aPartitions = $oDB->getCol($sSQL);
342 if (!$this->bNoPartitions) $aPartitions[] = 0;
343 foreach ($aPartitions as $sPartition) {
344 $oDB->exec('TRUNCATE location_road_'.$sPartition);
348 // used by getorcreate_word_id to ignore frequent partial words
349 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
350 $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
354 // pre-create the word list
355 if (!$bDisableTokenPrecalc) {
356 info('Loading word list');
357 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
361 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
363 $aDBInstances = array();
364 $iLoadThreads = max(1, $this->iInstances - 1);
365 for ($i = 0; $i < $iLoadThreads; $i++) {
366 // https://secure.php.net/manual/en/function.pg-connect.php
367 $DSN = getSetting('DATABASE_DSN');
368 $DSN = preg_replace('/^pgsql:/', '', $DSN);
369 $DSN = preg_replace('/;/', ' ', $DSN);
370 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
371 pg_ping($aDBInstances[$i]);
374 for ($i = 0; $i < $iLoadThreads; $i++) {
375 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
376 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
377 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
378 $sSQL .= ' and ST_IsValid(geometry)';
379 if ($this->bVerbose) echo "$sSQL\n";
380 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
381 fail(pg_last_error($aDBInstances[$i]));
385 // last thread for interpolation lines
386 // https://secure.php.net/manual/en/function.pg-connect.php
387 $DSN = getSetting('DATABASE_DSN');
388 $DSN = preg_replace('/^pgsql:/', '', $DSN);
389 $DSN = preg_replace('/;/', ' ', $DSN);
390 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
391 pg_ping($aDBInstances[$iLoadThreads]);
392 $sSQL = 'insert into location_property_osmline';
393 $sSQL .= ' (osm_id, address, linegeo)';
394 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
395 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
396 if ($this->bVerbose) echo "$sSQL\n";
397 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
398 fail(pg_last_error($aDBInstances[$iLoadThreads]));
402 for ($i = 0; $i <= $iLoadThreads; $i++) {
403 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
404 $resultStatus = pg_result_status($hPGresult);
405 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
406 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
407 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
408 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
409 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
410 $resultError = pg_result_error($hPGresult);
411 echo '-- error text ' . $i . ': ' . $resultError . "\n";
417 fail('SQL errors loading placex and/or location_property_osmline tables');
420 for ($i = 0; $i < $this->iInstances; $i++) {
421 pg_close($aDBInstances[$i]);
425 info('Reanalysing database');
426 $this->pgsqlRunScript('ANALYSE');
428 $sDatabaseDate = getDatabaseDate($oDB);
429 $oDB->exec('TRUNCATE import_status');
430 if (!$sDatabaseDate) {
431 warn('could not determine database date.');
433 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
435 echo "Latest data imported from $sDatabaseDate.\n";
439 public function importTigerData($sTigerPath)
441 info('Import Tiger data');
443 $aFilenames = glob($sTigerPath.'/*.sql');
444 info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
445 if (empty($aFilenames)) {
446 warn('Tiger data import selected but no files found in path '.$sTigerPath);
449 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
450 $sTemplate = $this->replaceSqlPatterns($sTemplate);
452 $this->pgsqlRunScript($sTemplate, false);
454 $aDBInstances = array();
455 for ($i = 0; $i < $this->iInstances; $i++) {
456 // https://secure.php.net/manual/en/function.pg-connect.php
457 $DSN = getSetting('DATABASE_DSN');
458 $DSN = preg_replace('/^pgsql:/', '', $DSN);
459 $DSN = preg_replace('/;/', ' ', $DSN);
460 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
461 pg_ping($aDBInstances[$i]);
464 foreach ($aFilenames as $sFile) {
466 $hFile = fopen($sFile, 'r');
467 $sSQL = fgets($hFile, 100000);
470 for ($i = 0; $i < $this->iInstances; $i++) {
471 if (!pg_connection_busy($aDBInstances[$i])) {
472 while (pg_get_result($aDBInstances[$i]));
473 $sSQL = fgets($hFile, 100000);
475 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
477 if ($iLines == 1000) {
490 for ($i = 0; $i < $this->iInstances; $i++) {
491 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
498 for ($i = 0; $i < $this->iInstances; $i++) {
499 pg_close($aDBInstances[$i]);
502 info('Creating indexes on Tiger data');
503 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
504 $sTemplate = $this->replaceSqlPatterns($sTemplate);
506 $this->pgsqlRunScript($sTemplate, false);
509 public function calculatePostcodes($bCMDResultAll)
511 info('Calculate Postcodes');
512 $this->db()->exec('TRUNCATE location_postcode');
514 $sSQL = 'INSERT INTO location_postcode';
515 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
516 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
517 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
518 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
519 $sSQL .= ' FROM placex';
520 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
521 $sSQL .= ' AND geometry IS NOT null';
522 $sSQL .= ' GROUP BY country_code, pc';
523 $this->db()->exec($sSQL);
525 // only add postcodes that are not yet available in OSM
526 $sSQL = 'INSERT INTO location_postcode';
527 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
528 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
529 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
530 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
531 $sSQL .= ' (SELECT postcode FROM location_postcode';
532 $sSQL .= " WHERE country_code = 'us')";
533 $this->db()->exec($sSQL);
535 // add missing postcodes for GB (if available)
536 $sSQL = 'INSERT INTO location_postcode';
537 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
538 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
539 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
540 $sSQL .= ' (SELECT postcode FROM location_postcode';
541 $sSQL .= " WHERE country_code = 'gb')";
542 $this->db()->exec($sSQL);
544 if (!$bCMDResultAll) {
545 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
546 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
547 $this->db()->exec($sSQL);
550 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
551 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
552 $this->db()->exec($sSQL);
555 public function index($bIndexNoanalyse)
557 $this->checkModulePresence(); // raises exception on failure
559 $oBaseCmd = (clone $this->oNominatimCmd)->addParams('index');
561 info('Index ranks 0 - 4');
562 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
564 $iStatus = $oCmd->run();
566 fail('error status ' . $iStatus . ' running nominatim!');
568 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
570 info('Index administrative boundaries');
571 $oCmd = (clone $oBaseCmd)->addParams('--boundaries-only');
572 $iStatus = $oCmd->run();
574 fail('error status ' . $iStatus . ' running nominatim!');
577 info('Index ranks 5 - 25');
578 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 5, '--maxrank', 25);
579 $iStatus = $oCmd->run();
581 fail('error status ' . $iStatus . ' running nominatim!');
584 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
586 info('Index ranks 26 - 30');
587 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 26);
588 $iStatus = $oCmd->run();
590 fail('error status ' . $iStatus . ' running nominatim!');
593 info('Index postcodes');
594 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
595 $this->db()->exec($sSQL);
598 public function createSearchIndices()
600 info('Create Search indices');
602 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
603 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
604 $aInvalidIndices = $this->db()->getCol($sSQL);
606 foreach ($aInvalidIndices as $sIndexName) {
607 info("Cleaning up invalid index $sIndexName");
608 $this->db()->exec("DROP INDEX $sIndexName;");
611 $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
613 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
615 if (!$this->dbReverseOnly()) {
616 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
618 $sTemplate = $this->replaceSqlPatterns($sTemplate);
620 $this->pgsqlRunScript($sTemplate);
623 public function createCountryNames()
625 info('Create search index for default country names');
627 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
628 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
629 $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');
630 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
631 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
632 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
633 $sLanguages = getSetting('LANGUAGES');
637 foreach (explode(',', $sLanguages) as $sLang) {
638 $sSQL .= $sDelim."'name:$sLang'";
643 // all include all simple name tags
644 $sSQL .= "like 'name:%'";
647 $this->pgsqlRunScript($sSQL);
650 public function drop()
652 info('Drop tables only required for updates');
654 // The implementation is potentially a bit dangerous because it uses
655 // a positive selection of tables to keep, and deletes everything else.
656 // Including any tables that the unsuspecting user might have manually
657 // created. USE AT YOUR OWN PERIL.
658 // tables we want to keep. everything else goes.
659 $aKeepTables = array(
665 'location_property*',
678 $aDropTables = array();
679 $aHaveTables = $this->db()->getListOfTables();
681 foreach ($aHaveTables as $sTable) {
683 foreach ($aKeepTables as $sKeep) {
684 if (fnmatch($sKeep, $sTable)) {
689 if (!$bFound) array_push($aDropTables, $sTable);
691 foreach ($aDropTables as $sDrop) {
692 $this->dropTable($sDrop);
695 $this->removeFlatnodeFile();
699 * Setup the directory for the API scripts.
703 public function setupWebsite()
705 if (!is_dir(CONST_InstallDir.'/website')) {
706 info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
707 mkdir(CONST_InstallDir.'/website');
720 foreach ($aScripts as $sScript) {
721 $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
723 fwrite($rFile, "<?php\n\n");
724 fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
726 fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
727 fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
728 fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
729 fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
730 fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
731 fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
732 fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
733 fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
734 fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
735 fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
736 fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
737 fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
738 fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
739 fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
740 fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
741 fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
742 fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
744 // XXX scripts should go into the library.
745 fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
748 chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
753 * Return the connection to the database.
755 * @return Database object.
757 * Creates a new connection if none exists yet. Otherwise reuses the
758 * already established connection.
760 private function db()
762 if (is_null($this->oDB)) {
763 $this->oDB = new \Nominatim\DB();
764 $this->oDB->connect();
770 private function removeFlatnodeFile()
772 $sFName = getSetting('FLATNODE_FILE');
773 if ($sFName && file_exists($sFName)) {
774 if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
779 private function pgsqlRunScript($sScript, $bfatal = true)
789 private function createSqlFunctions()
791 $sBasePath = CONST_DataDir.'/sql/functions/';
792 $sTemplate = file_get_contents($sBasePath.'utils.sql');
793 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
794 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
795 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
796 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
797 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
798 if ($this->db()->tableExists('place')) {
799 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
801 if ($this->db()->tableExists('placex')) {
802 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
804 if ($this->db()->tableExists('location_postcode')) {
805 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
807 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
808 if ($this->bEnableDiffUpdates) {
809 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
811 if ($this->bEnableDebugStatements) {
812 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
814 if (getSettingBool('LIMIT_REINDEXING')) {
815 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
817 if (!getSettingBool('USE_US_TIGER_DATA')) {
818 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
820 if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
821 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
824 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
825 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
827 $this->pgsqlRunScript($sTemplate);
830 private function pgsqlRunPartitionScript($sTemplate)
832 $sSQL = 'select distinct partition from country_name';
833 $aPartitions = $this->db()->getCol($sSQL);
834 if (!$this->bNoPartitions) $aPartitions[] = 0;
836 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
837 foreach ($aMatches as $aMatch) {
839 foreach ($aPartitions as $sPartitionName) {
840 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
842 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
845 $this->pgsqlRunScript($sTemplate);
848 private function pgsqlRunScriptFile($sFilename)
850 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
852 $oCmd = (new \Nominatim\Shell('psql'))
853 ->addParams('--port', $this->aDSNInfo['port'])
854 ->addParams('--dbname', $this->aDSNInfo['database']);
856 if (!$this->bVerbose) {
857 $oCmd->addParams('--quiet');
859 if (isset($this->aDSNInfo['hostspec'])) {
860 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
862 if (isset($this->aDSNInfo['username'])) {
863 $oCmd->addParams('--username', $this->aDSNInfo['username']);
865 if (isset($this->aDSNInfo['password'])) {
866 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
869 if (preg_match('/\\.gz$/', $sFilename)) {
870 $aDescriptors = array(
871 0 => array('pipe', 'r'),
872 1 => array('pipe', 'w'),
873 2 => array('file', '/dev/null', 'a')
875 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
877 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
878 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
879 $aReadPipe = $ahGzipPipes[1];
880 fclose($ahGzipPipes[0]);
882 $oCmd->addParams('--file', $sFilename);
883 $aReadPipe = array('pipe', 'r');
885 $aDescriptors = array(
887 1 => array('pipe', 'w'),
888 2 => array('file', '/dev/null', 'a')
892 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
893 if (!is_resource($hProcess)) fail('unable to start pgsql');
894 // TODO: error checking
895 while (!feof($ahPipes[1])) {
896 echo fread($ahPipes[1], 4096);
899 $iReturn = proc_close($hProcess);
901 fail("pgsql returned with error code ($iReturn)");
904 fclose($ahGzipPipes[1]);
905 proc_close($hGzipProcess);
909 private function replaceSqlPatterns($sSql)
911 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
914 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
915 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
916 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
917 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
918 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
919 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
922 foreach ($aPatterns as $sPattern => $sTablespace) {
924 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
926 $sSql = str_replace($sPattern, '', $sSql);
934 * Drop table with the given name if it exists.
936 * @param string $sName Name of table to remove.
940 private function dropTable($sName)
942 if ($this->bVerbose) echo "Dropping table $sName\n";
943 $this->db()->deleteTable($sName);
947 * Check if the database is in reverse-only mode.
949 * @return True if there is no search_name table and infrastructure.
951 private function dbReverseOnly()
953 return !($this->db()->tableExists('search_name'));
957 * Try accessing the C module, so we know early if something is wrong.
959 * Raises Nominatim\DatabaseError on failure
961 private function checkModulePresence()
963 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
964 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
965 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
967 $oDB = new \Nominatim\DB();
969 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');