3 namespace Nominatim\Setup;
5 require_once(CONST_LibDir.'/setup/AddressLevelParser.php');
6 require_once(CONST_LibDir.'/Shell.php');
10 protected $iCacheMemory;
11 protected $iInstances;
12 protected $sModulePath;
16 protected $sIgnoreErrors;
17 protected $bEnableDiffUpdates;
18 protected $bEnableDebugStatements;
19 protected $bNoPartitions;
21 protected $oDB = null;
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', CONST_InstallDir.'/module');
46 info('module path: ' . $this->sModulePath);
48 // parse database string
49 $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
50 if (!isset($this->aDSNInfo['port'])) {
51 $this->aDSNInfo['port'] = 5432;
54 // setting member variables based on command line options stored in $aCMDResult
55 $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
56 $this->bVerbose = $aCMDResult['verbose'];
58 //setting default values which are not set by the update.php array
59 if (isset($aCMDResult['ignore-errors'])) {
60 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
62 $this->sIgnoreErrors = false;
64 if (isset($aCMDResult['enable-debug-statements'])) {
65 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
67 $this->bEnableDebugStatements = false;
69 if (isset($aCMDResult['no-partitions'])) {
70 $this->bNoPartitions = $aCMDResult['no-partitions'];
72 $this->bNoPartitions = false;
74 if (isset($aCMDResult['enable-diff-updates'])) {
75 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
77 $this->bEnableDiffUpdates = false;
80 $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
83 public function createDB()
86 $oDB = new \Nominatim\DB;
88 if ($oDB->checkConnection()) {
89 fail('database already exists ('.getSetting('DATABASE_DSN').')');
92 $oCmd = (new \Nominatim\Shell('createdb'))
93 ->addParams('-E', 'UTF-8')
94 ->addParams('-p', $this->aDSNInfo['port']);
96 if (isset($this->aDSNInfo['username'])) {
97 $oCmd->addParams('-U', $this->aDSNInfo['username']);
99 if (isset($this->aDSNInfo['password'])) {
100 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
102 if (isset($this->aDSNInfo['hostspec'])) {
103 $oCmd->addParams('-h', $this->aDSNInfo['hostspec']);
105 $oCmd->addParams($this->aDSNInfo['database']);
107 $result = $oCmd->run();
108 if ($result != 0) fail('Error executing external command: '.$oCmd->escapedCmd());
111 public function setupDB()
115 $fPostgresVersion = $this->db()->getPostgresVersion();
116 echo 'Postgres version found: '.$fPostgresVersion."\n";
118 if ($fPostgresVersion < 9.03) {
119 fail('Minimum supported version of Postgresql is 9.3.');
122 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
123 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
125 $fPostgisVersion = $this->db()->getPostgisVersion();
126 echo 'Postgis version found: '.$fPostgisVersion."\n";
128 if ($fPostgisVersion < 2.2) {
129 echo "Minimum required Postgis version 2.2\n";
133 $sPgUser = getSetting('DATABASE_WEBUSER');
134 $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
136 echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
137 echo "\n createuser ".$sPgUser."\n\n";
141 // Try accessing the C module, so we know early if something is wrong
142 $this->checkModulePresence(); // raises exception on failure
144 if (!file_exists(CONST_DataDir.'/data/country_osm_grid.sql.gz')) {
145 echo 'Error: you need to download the country_osm_grid first:';
146 echo "\n wget -O ".CONST_DataDir."/data/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
149 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_name.sql');
150 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_osm_grid.sql.gz');
151 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/gb_postcode_table.sql');
152 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/us_postcode_table.sql');
154 $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
155 if (file_exists($sPostcodeFilename)) {
156 $this->pgsqlRunScriptFile($sPostcodeFilename);
158 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
161 $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
162 if (file_exists($sPostcodeFilename)) {
163 $this->pgsqlRunScriptFile($sPostcodeFilename);
165 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
168 if ($this->bNoPartitions) {
169 $this->pgsqlRunScript('update country_name set partition = 0');
173 public function importData($sOSMFile)
177 if (!file_exists(getOsm2pgsqlBinary())) {
178 echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
179 echo "Normally you should not need to set this manually.\n";
180 fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
183 $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
184 $oCmd->addParams('--style', getImportStyle());
186 if (getSetting('FLATNODE_FILE')) {
187 $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
189 if (getSetting('TABLESPACE_OSM_DATA')) {
190 $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
192 if (getSetting('TABLESPACE_OSM_INDEX')) {
193 $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
195 if (getSetting('TABLESPACE_PLACE_DATA')) {
196 $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
198 if (getSetting('TABLESPACE_PLACE_INDEX')) {
199 $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
201 $oCmd->addParams('--latlong', '--slim', '--create');
202 $oCmd->addParams('--output', 'gazetteer');
203 $oCmd->addParams('--hstore');
204 $oCmd->addParams('--number-processes', 1);
205 $oCmd->addParams('--with-forward-dependencies', 'false');
206 $oCmd->addParams('--log-progress', 'true');
207 $oCmd->addParams('--cache', $this->iCacheMemory);
208 $oCmd->addParams('--port', $this->aDSNInfo['port']);
210 if (isset($this->aDSNInfo['username'])) {
211 $oCmd->addParams('--username', $this->aDSNInfo['username']);
213 if (isset($this->aDSNInfo['password'])) {
214 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
216 if (isset($this->aDSNInfo['hostspec'])) {
217 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
219 $oCmd->addParams('--database', $this->aDSNInfo['database']);
220 $oCmd->addParams($sOSMFile);
223 if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
228 $this->dropTable('planet_osm_nodes');
229 $this->removeFlatnodeFile();
233 public function createFunctions()
235 info('Create Functions');
237 // Try accessing the C module, so we know early if something is wrong
238 $this->checkModulePresence(); // raises exception on failure
240 $this->createSqlFunctions();
243 public function createTables($bReverseOnly = false)
245 info('Create Tables');
247 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
248 $sTemplate = $this->replaceSqlPatterns($sTemplate);
250 $this->pgsqlRunScript($sTemplate, false);
253 $this->dropTable('search_name');
256 $oAlParser = new AddressLevelParser(getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json'));
257 $oAlParser->createTable($this->db(), 'address_levels');
260 public function createTableTriggers()
262 info('Create Tables');
264 $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
265 $sTemplate = $this->replaceSqlPatterns($sTemplate);
267 $this->pgsqlRunScript($sTemplate, false);
270 public function createPartitionTables()
272 info('Create Partition Tables');
274 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
275 $sTemplate = $this->replaceSqlPatterns($sTemplate);
277 $this->pgsqlRunPartitionScript($sTemplate);
280 public function createPartitionFunctions()
282 info('Create Partition Functions');
284 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
285 $this->pgsqlRunPartitionScript($sTemplate);
288 public function importWikipediaArticles()
290 $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
291 $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
292 if (file_exists($sWikiArticlesFile)) {
293 info('Importing wikipedia articles and redirects');
294 $this->dropTable('wikipedia_article');
295 $this->dropTable('wikipedia_redirect');
296 $this->pgsqlRunScriptFile($sWikiArticlesFile);
298 warn('wikipedia importance dump file not found - places will have default importance');
302 public function loadData($bDisableTokenPrecalc)
304 info('Drop old Data');
308 $oDB->exec('TRUNCATE word');
310 $oDB->exec('TRUNCATE placex');
312 $oDB->exec('TRUNCATE location_property_osmline');
314 $oDB->exec('TRUNCATE place_addressline');
316 $oDB->exec('TRUNCATE location_area');
318 if (!$this->dbReverseOnly()) {
319 $oDB->exec('TRUNCATE search_name');
322 $oDB->exec('TRUNCATE search_name_blank');
324 $oDB->exec('DROP SEQUENCE seq_place');
326 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
329 $sSQL = 'select distinct partition from country_name';
330 $aPartitions = $oDB->getCol($sSQL);
332 if (!$this->bNoPartitions) $aPartitions[] = 0;
333 foreach ($aPartitions as $sPartition) {
334 $oDB->exec('TRUNCATE location_road_'.$sPartition);
338 // used by getorcreate_word_id to ignore frequent partial words
339 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
340 $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
344 // pre-create the word list
345 if (!$bDisableTokenPrecalc) {
346 info('Loading word list');
347 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
351 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
353 $aDBInstances = array();
354 $iLoadThreads = max(1, $this->iInstances - 1);
355 for ($i = 0; $i < $iLoadThreads; $i++) {
356 // https://secure.php.net/manual/en/function.pg-connect.php
357 $DSN = getSetting('DATABASE_DSN');
358 $DSN = preg_replace('/^pgsql:/', '', $DSN);
359 $DSN = preg_replace('/;/', ' ', $DSN);
360 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
361 pg_ping($aDBInstances[$i]);
364 for ($i = 0; $i < $iLoadThreads; $i++) {
365 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
366 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
367 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
368 $sSQL .= ' and ST_IsValid(geometry)';
369 if ($this->bVerbose) echo "$sSQL\n";
370 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
371 fail(pg_last_error($aDBInstances[$i]));
375 // last thread for interpolation lines
376 // https://secure.php.net/manual/en/function.pg-connect.php
377 $DSN = getSetting('DATABASE_DSN');
378 $DSN = preg_replace('/^pgsql:/', '', $DSN);
379 $DSN = preg_replace('/;/', ' ', $DSN);
380 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
381 pg_ping($aDBInstances[$iLoadThreads]);
382 $sSQL = 'insert into location_property_osmline';
383 $sSQL .= ' (osm_id, address, linegeo)';
384 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
385 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
386 if ($this->bVerbose) echo "$sSQL\n";
387 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
388 fail(pg_last_error($aDBInstances[$iLoadThreads]));
392 for ($i = 0; $i <= $iLoadThreads; $i++) {
393 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
394 $resultStatus = pg_result_status($hPGresult);
395 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
396 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
397 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
398 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
399 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
400 $resultError = pg_result_error($hPGresult);
401 echo '-- error text ' . $i . ': ' . $resultError . "\n";
407 fail('SQL errors loading placex and/or location_property_osmline tables');
410 for ($i = 0; $i < $this->iInstances; $i++) {
411 pg_close($aDBInstances[$i]);
415 info('Reanalysing database');
416 $this->pgsqlRunScript('ANALYSE');
418 $sDatabaseDate = getDatabaseDate($oDB);
419 $oDB->exec('TRUNCATE import_status');
420 if (!$sDatabaseDate) {
421 warn('could not determine database date.');
423 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
425 echo "Latest data imported from $sDatabaseDate.\n";
429 public function importTigerData($sTigerPath)
431 info('Import Tiger data');
433 $aFilenames = glob($sTigerPath.'/*.sql');
434 info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
435 if (empty($aFilenames)) {
436 warn('Tiger data import selected but no files found in path '.$sTigerPath);
439 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
440 $sTemplate = $this->replaceSqlPatterns($sTemplate);
442 $this->pgsqlRunScript($sTemplate, false);
444 $aDBInstances = array();
445 for ($i = 0; $i < $this->iInstances; $i++) {
446 // https://secure.php.net/manual/en/function.pg-connect.php
447 $DSN = getSetting('DATABASE_DSN');
448 $DSN = preg_replace('/^pgsql:/', '', $DSN);
449 $DSN = preg_replace('/;/', ' ', $DSN);
450 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
451 pg_ping($aDBInstances[$i]);
454 foreach ($aFilenames as $sFile) {
456 $hFile = fopen($sFile, 'r');
457 $sSQL = fgets($hFile, 100000);
460 for ($i = 0; $i < $this->iInstances; $i++) {
461 if (!pg_connection_busy($aDBInstances[$i])) {
462 while (pg_get_result($aDBInstances[$i]));
463 $sSQL = fgets($hFile, 100000);
465 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
467 if ($iLines == 1000) {
480 for ($i = 0; $i < $this->iInstances; $i++) {
481 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
488 for ($i = 0; $i < $this->iInstances; $i++) {
489 pg_close($aDBInstances[$i]);
492 info('Creating indexes on Tiger data');
493 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
494 $sTemplate = $this->replaceSqlPatterns($sTemplate);
496 $this->pgsqlRunScript($sTemplate, false);
499 public function calculatePostcodes($bCMDResultAll)
501 info('Calculate Postcodes');
502 $this->db()->exec('TRUNCATE location_postcode');
504 $sSQL = 'INSERT INTO location_postcode';
505 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
506 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
507 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
508 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
509 $sSQL .= ' FROM placex';
510 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
511 $sSQL .= ' AND geometry IS NOT null';
512 $sSQL .= ' GROUP BY country_code, pc';
513 $this->db()->exec($sSQL);
515 // only add postcodes that are not yet available in OSM
516 $sSQL = 'INSERT INTO location_postcode';
517 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
518 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
519 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
520 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
521 $sSQL .= ' (SELECT postcode FROM location_postcode';
522 $sSQL .= " WHERE country_code = 'us')";
523 $this->db()->exec($sSQL);
525 // add missing postcodes for GB (if available)
526 $sSQL = 'INSERT INTO location_postcode';
527 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
528 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
529 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
530 $sSQL .= ' (SELECT postcode FROM location_postcode';
531 $sSQL .= " WHERE country_code = 'gb')";
532 $this->db()->exec($sSQL);
534 if (!$bCMDResultAll) {
535 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
536 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
537 $this->db()->exec($sSQL);
540 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
541 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
542 $this->db()->exec($sSQL);
545 public function index($bIndexNoanalyse)
547 $this->checkModulePresence(); // raises exception on failure
549 $oBaseCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
550 ->addParams('--database', $this->aDSNInfo['database'])
551 ->addParams('--port', $this->aDSNInfo['port'])
552 ->addParams('--threads', $this->iInstances);
554 if (!$this->bQuiet) {
555 $oBaseCmd->addParams('-v');
557 if ($this->bVerbose) {
558 $oBaseCmd->addParams('-v');
560 if (isset($this->aDSNInfo['hostspec'])) {
561 $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
563 if (isset($this->aDSNInfo['username'])) {
564 $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
566 if (isset($this->aDSNInfo['password'])) {
567 $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
570 info('Index ranks 0 - 4');
571 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
572 echo $oCmd->escapedCmd();
574 $iStatus = $oCmd->run();
576 fail('error status ' . $iStatus . ' running nominatim!');
578 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
580 info('Index administrative boundaries');
581 $oCmd = (clone $oBaseCmd)->addParams('-b');
582 $iStatus = $oCmd->run();
584 fail('error status ' . $iStatus . ' running nominatim!');
587 info('Index ranks 5 - 25');
588 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
589 $iStatus = $oCmd->run();
591 fail('error status ' . $iStatus . ' running nominatim!');
594 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
596 info('Index ranks 26 - 30');
597 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
598 $iStatus = $oCmd->run();
600 fail('error status ' . $iStatus . ' running nominatim!');
603 info('Index postcodes');
604 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
605 $this->db()->exec($sSQL);
608 public function createSearchIndices()
610 info('Create Search indices');
612 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
613 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
614 $aInvalidIndices = $this->db()->getCol($sSQL);
616 foreach ($aInvalidIndices as $sIndexName) {
617 info("Cleaning up invalid index $sIndexName");
618 $this->db()->exec("DROP INDEX $sIndexName;");
621 $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
623 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
625 if (!$this->dbReverseOnly()) {
626 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
628 $sTemplate = $this->replaceSqlPatterns($sTemplate);
630 $this->pgsqlRunScript($sTemplate);
633 public function createCountryNames()
635 info('Create search index for default country names');
637 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
638 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
639 $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');
640 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
641 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
642 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
643 $sLanguages = getSetting('LANGUAGES');
647 foreach (explode(',', $sLanguages) as $sLang) {
648 $sSQL .= $sDelim."'name:$sLang'";
653 // all include all simple name tags
654 $sSQL .= "like 'name:%'";
657 $this->pgsqlRunScript($sSQL);
660 public function drop()
662 info('Drop tables only required for updates');
664 // The implementation is potentially a bit dangerous because it uses
665 // a positive selection of tables to keep, and deletes everything else.
666 // Including any tables that the unsuspecting user might have manually
667 // created. USE AT YOUR OWN PERIL.
668 // tables we want to keep. everything else goes.
669 $aKeepTables = array(
675 'location_property*',
688 $aDropTables = array();
689 $aHaveTables = $this->db()->getListOfTables();
691 foreach ($aHaveTables as $sTable) {
693 foreach ($aKeepTables as $sKeep) {
694 if (fnmatch($sKeep, $sTable)) {
699 if (!$bFound) array_push($aDropTables, $sTable);
701 foreach ($aDropTables as $sDrop) {
702 $this->dropTable($sDrop);
705 $this->removeFlatnodeFile();
709 * Setup the directory for the API scripts.
713 public function setupWebsite()
715 if (!is_dir(CONST_InstallDir.'/website')) {
716 info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
717 mkdir(CONST_InstallDir.'/website');
730 foreach($aScripts as $sScript) {
731 $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
733 fwrite($rFile, "<?php\n\n");
734 fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
736 fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
737 fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
738 fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
740 fwrite($rFile, "if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));\n\n");
742 fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
743 fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
744 fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
745 fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
746 fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
747 fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
748 fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
749 fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
750 fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
751 fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
752 fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
753 fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
754 fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
755 fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
757 // XXX scripts should go into the library.
758 fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
761 chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
766 * Return the connection to the database.
768 * @return Database object.
770 * Creates a new connection if none exists yet. Otherwise reuses the
771 * already established connection.
773 private function db()
775 if (is_null($this->oDB)) {
776 $this->oDB = new \Nominatim\DB();
777 $this->oDB->connect();
783 private function removeFlatnodeFile()
785 $sFName = getSetting('FLATNODE_FILE');
786 if ($sFName && file_exists($sFName)) {
787 if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
792 private function pgsqlRunScript($sScript, $bfatal = true)
802 private function createSqlFunctions()
804 $sBasePath = CONST_DataDir.'/sql/functions/';
805 $sTemplate = file_get_contents($sBasePath.'utils.sql');
806 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
807 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
808 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
809 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
810 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
811 if ($this->db()->tableExists('place')) {
812 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
814 if ($this->db()->tableExists('placex')) {
815 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
817 if ($this->db()->tableExists('location_postcode')) {
818 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
820 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
821 if ($this->bEnableDiffUpdates) {
822 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
824 if ($this->bEnableDebugStatements) {
825 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
827 if (getSettingBool('LIMIT_REINDEXING')) {
828 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
830 if (!getSettingBool('USE_US_TIGER_DATA')) {
831 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
833 if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
834 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
837 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
838 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
840 $this->pgsqlRunScript($sTemplate);
843 private function pgsqlRunPartitionScript($sTemplate)
845 $sSQL = 'select distinct partition from country_name';
846 $aPartitions = $this->db()->getCol($sSQL);
847 if (!$this->bNoPartitions) $aPartitions[] = 0;
849 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
850 foreach ($aMatches as $aMatch) {
852 foreach ($aPartitions as $sPartitionName) {
853 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
855 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
858 $this->pgsqlRunScript($sTemplate);
861 private function pgsqlRunScriptFile($sFilename)
863 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
865 $oCmd = (new \Nominatim\Shell('psql'))
866 ->addParams('--port', $this->aDSNInfo['port'])
867 ->addParams('--dbname', $this->aDSNInfo['database']);
869 if (!$this->bVerbose) {
870 $oCmd->addParams('--quiet');
872 if (isset($this->aDSNInfo['hostspec'])) {
873 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
875 if (isset($this->aDSNInfo['username'])) {
876 $oCmd->addParams('--username', $this->aDSNInfo['username']);
878 if (isset($this->aDSNInfo['password'])) {
879 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
882 if (preg_match('/\\.gz$/', $sFilename)) {
883 $aDescriptors = array(
884 0 => array('pipe', 'r'),
885 1 => array('pipe', 'w'),
886 2 => array('file', '/dev/null', 'a')
888 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
890 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
891 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
892 $aReadPipe = $ahGzipPipes[1];
893 fclose($ahGzipPipes[0]);
895 $oCmd->addParams('--file', $sFilename);
896 $aReadPipe = array('pipe', 'r');
898 $aDescriptors = array(
900 1 => array('pipe', 'w'),
901 2 => array('file', '/dev/null', 'a')
905 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
906 if (!is_resource($hProcess)) fail('unable to start pgsql');
907 // TODO: error checking
908 while (!feof($ahPipes[1])) {
909 echo fread($ahPipes[1], 4096);
912 $iReturn = proc_close($hProcess);
914 fail("pgsql returned with error code ($iReturn)");
917 fclose($ahGzipPipes[1]);
918 proc_close($hGzipProcess);
922 private function replaceSqlPatterns($sSql)
924 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
927 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
928 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
929 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
930 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
931 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
932 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
935 foreach ($aPatterns as $sPattern => $sTablespace) {
937 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
939 $sSql = str_replace($sPattern, '', $sSql);
947 * Drop table with the given name if it exists.
949 * @param string $sName Name of table to remove.
953 private function dropTable($sName)
955 if ($this->bVerbose) echo "Dropping table $sName\n";
956 $this->db()->deleteTable($sName);
960 * Check if the database is in reverse-only mode.
962 * @return True if there is no search_name table and infrastructure.
964 private function dbReverseOnly()
966 return !($this->db()->tableExists('search_name'));
970 * Try accessing the C module, so we know early if something is wrong.
972 * Raises Nominatim\DatabaseError on failure
974 private function checkModulePresence()
976 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
977 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
978 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
980 $oDB = new \Nominatim\DB();
982 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');