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_InstallDir.'/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_InstallDir.'/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');
293 $this->createSqlFunctions(); // also create partition functions
296 public function importWikipediaArticles()
298 $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_InstallDir);
299 $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
300 if (file_exists($sWikiArticlesFile)) {
301 info('Importing wikipedia articles and redirects');
302 $this->dropTable('wikipedia_article');
303 $this->dropTable('wikipedia_redirect');
304 $this->pgsqlRunScriptFile($sWikiArticlesFile);
306 warn('wikipedia importance dump file not found - places will have default importance');
310 public function loadData($bDisableTokenPrecalc)
312 info('Drop old Data');
316 $oDB->exec('TRUNCATE word');
318 $oDB->exec('TRUNCATE placex');
320 $oDB->exec('TRUNCATE location_property_osmline');
322 $oDB->exec('TRUNCATE place_addressline');
324 $oDB->exec('TRUNCATE location_area');
326 if (!$this->dbReverseOnly()) {
327 $oDB->exec('TRUNCATE search_name');
330 $oDB->exec('TRUNCATE search_name_blank');
332 $oDB->exec('DROP SEQUENCE seq_place');
334 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
337 $sSQL = 'select distinct partition from country_name';
338 $aPartitions = $oDB->getCol($sSQL);
340 if (!$this->bNoPartitions) $aPartitions[] = 0;
341 foreach ($aPartitions as $sPartition) {
342 $oDB->exec('TRUNCATE location_road_'.$sPartition);
346 // used by getorcreate_word_id to ignore frequent partial words
347 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
348 $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
352 // pre-create the word list
353 if (!$bDisableTokenPrecalc) {
354 info('Loading word list');
355 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
359 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
361 $aDBInstances = array();
362 $iLoadThreads = max(1, $this->iInstances - 1);
363 for ($i = 0; $i < $iLoadThreads; $i++) {
364 // https://secure.php.net/manual/en/function.pg-connect.php
365 $DSN = getSetting('DATABASE_DSN');
366 $DSN = preg_replace('/^pgsql:/', '', $DSN);
367 $DSN = preg_replace('/;/', ' ', $DSN);
368 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
369 pg_ping($aDBInstances[$i]);
372 for ($i = 0; $i < $iLoadThreads; $i++) {
373 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
374 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
375 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
376 $sSQL .= ' and ST_IsValid(geometry)';
377 if ($this->bVerbose) echo "$sSQL\n";
378 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
379 fail(pg_last_error($aDBInstances[$i]));
383 // last thread for interpolation lines
384 // https://secure.php.net/manual/en/function.pg-connect.php
385 $DSN = getSetting('DATABASE_DSN');
386 $DSN = preg_replace('/^pgsql:/', '', $DSN);
387 $DSN = preg_replace('/;/', ' ', $DSN);
388 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
389 pg_ping($aDBInstances[$iLoadThreads]);
390 $sSQL = 'insert into location_property_osmline';
391 $sSQL .= ' (osm_id, address, linegeo)';
392 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
393 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
394 if ($this->bVerbose) echo "$sSQL\n";
395 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
396 fail(pg_last_error($aDBInstances[$iLoadThreads]));
400 for ($i = 0; $i <= $iLoadThreads; $i++) {
401 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
402 $resultStatus = pg_result_status($hPGresult);
403 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
404 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
405 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
406 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
407 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
408 $resultError = pg_result_error($hPGresult);
409 echo '-- error text ' . $i . ': ' . $resultError . "\n";
415 fail('SQL errors loading placex and/or location_property_osmline tables');
418 for ($i = 0; $i < $this->iInstances; $i++) {
419 pg_close($aDBInstances[$i]);
423 info('Reanalysing database');
424 $this->pgsqlRunScript('ANALYSE');
426 $sDatabaseDate = getDatabaseDate($oDB);
427 $oDB->exec('TRUNCATE import_status');
428 if (!$sDatabaseDate) {
429 warn('could not determine database date.');
431 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
433 echo "Latest data imported from $sDatabaseDate.\n";
437 public function importTigerData($sTigerPath)
439 info('Import Tiger data');
441 $aFilenames = glob($sTigerPath.'/*.sql');
442 info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
443 if (empty($aFilenames)) {
444 warn('Tiger data import selected but no files found in path '.$sTigerPath);
447 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
448 $sTemplate = $this->replaceSqlPatterns($sTemplate);
450 $this->pgsqlRunScript($sTemplate, false);
452 $aDBInstances = array();
453 for ($i = 0; $i < $this->iInstances; $i++) {
454 // https://secure.php.net/manual/en/function.pg-connect.php
455 $DSN = getSetting('DATABASE_DSN');
456 $DSN = preg_replace('/^pgsql:/', '', $DSN);
457 $DSN = preg_replace('/;/', ' ', $DSN);
458 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
459 pg_ping($aDBInstances[$i]);
462 foreach ($aFilenames as $sFile) {
464 $hFile = fopen($sFile, 'r');
465 $sSQL = fgets($hFile, 100000);
468 for ($i = 0; $i < $this->iInstances; $i++) {
469 if (!pg_connection_busy($aDBInstances[$i])) {
470 while (pg_get_result($aDBInstances[$i]));
471 $sSQL = fgets($hFile, 100000);
473 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
475 if ($iLines == 1000) {
488 for ($i = 0; $i < $this->iInstances; $i++) {
489 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
496 for ($i = 0; $i < $this->iInstances; $i++) {
497 pg_close($aDBInstances[$i]);
500 info('Creating indexes on Tiger data');
501 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
502 $sTemplate = $this->replaceSqlPatterns($sTemplate);
504 $this->pgsqlRunScript($sTemplate, false);
507 public function calculatePostcodes($bCMDResultAll)
509 info('Calculate Postcodes');
510 $this->db()->exec('TRUNCATE location_postcode');
512 $sSQL = 'INSERT INTO location_postcode';
513 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
514 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
515 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
516 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
517 $sSQL .= ' FROM placex';
518 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
519 $sSQL .= ' AND geometry IS NOT null';
520 $sSQL .= ' GROUP BY country_code, pc';
521 $this->db()->exec($sSQL);
523 // only add postcodes that are not yet available in OSM
524 $sSQL = 'INSERT INTO location_postcode';
525 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
526 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
527 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
528 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
529 $sSQL .= ' (SELECT postcode FROM location_postcode';
530 $sSQL .= " WHERE country_code = 'us')";
531 $this->db()->exec($sSQL);
533 // add missing postcodes for GB (if available)
534 $sSQL = 'INSERT INTO location_postcode';
535 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
536 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
537 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
538 $sSQL .= ' (SELECT postcode FROM location_postcode';
539 $sSQL .= " WHERE country_code = 'gb')";
540 $this->db()->exec($sSQL);
542 if (!$bCMDResultAll) {
543 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
544 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
545 $this->db()->exec($sSQL);
548 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
549 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
550 $this->db()->exec($sSQL);
553 public function index($bIndexNoanalyse)
555 $this->checkModulePresence(); // raises exception on failure
557 $oBaseCmd = (clone $this->oNominatimCmd)->addParams('index');
559 info('Index ranks 0 - 4');
560 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
562 $iStatus = $oCmd->run();
564 fail('error status ' . $iStatus . ' running nominatim!');
566 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
568 info('Index administrative boundaries');
569 $oCmd = (clone $oBaseCmd)->addParams('--boundaries-only');
570 $iStatus = $oCmd->run();
572 fail('error status ' . $iStatus . ' running nominatim!');
575 info('Index ranks 5 - 25');
576 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 5, '--maxrank', 25);
577 $iStatus = $oCmd->run();
579 fail('error status ' . $iStatus . ' running nominatim!');
582 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
584 info('Index ranks 26 - 30');
585 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 26);
586 $iStatus = $oCmd->run();
588 fail('error status ' . $iStatus . ' running nominatim!');
591 info('Index postcodes');
592 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
593 $this->db()->exec($sSQL);
596 public function createSearchIndices()
598 info('Create Search indices');
600 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
601 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
602 $aInvalidIndices = $this->db()->getCol($sSQL);
604 foreach ($aInvalidIndices as $sIndexName) {
605 info("Cleaning up invalid index $sIndexName");
606 $this->db()->exec("DROP INDEX $sIndexName;");
609 $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
611 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
613 if (!$this->dbReverseOnly()) {
614 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
616 $sTemplate = $this->replaceSqlPatterns($sTemplate);
618 $this->pgsqlRunScript($sTemplate);
621 public function createCountryNames()
623 info('Create search index for default country names');
625 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
626 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
627 $this->pgsqlRunScript('select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x');
628 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
629 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
630 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
631 $sLanguages = getSetting('LANGUAGES');
635 foreach (explode(',', $sLanguages) as $sLang) {
636 $sSQL .= $sDelim."'name:$sLang'";
641 // all include all simple name tags
642 $sSQL .= "like 'name:%'";
645 $this->pgsqlRunScript($sSQL);
648 public function drop()
650 info('Drop tables only required for updates');
652 // The implementation is potentially a bit dangerous because it uses
653 // a positive selection of tables to keep, and deletes everything else.
654 // Including any tables that the unsuspecting user might have manually
655 // created. USE AT YOUR OWN PERIL.
656 // tables we want to keep. everything else goes.
657 $aKeepTables = array(
663 'location_property*',
676 $aDropTables = array();
677 $aHaveTables = $this->db()->getListOfTables();
679 foreach ($aHaveTables as $sTable) {
681 foreach ($aKeepTables as $sKeep) {
682 if (fnmatch($sKeep, $sTable)) {
687 if (!$bFound) array_push($aDropTables, $sTable);
689 foreach ($aDropTables as $sDrop) {
690 $this->dropTable($sDrop);
693 $this->removeFlatnodeFile();
697 * Setup the directory for the API scripts.
701 public function setupWebsite()
703 if (!is_dir(CONST_InstallDir.'/website')) {
704 info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
705 mkdir(CONST_InstallDir.'/website');
718 foreach ($aScripts as $sScript) {
719 $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
721 fwrite($rFile, "<?php\n\n");
722 fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
724 fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
725 fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
726 fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
727 fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
728 fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
729 fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
730 fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
731 fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
732 fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
733 fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
734 fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
735 fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
736 fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
737 fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
738 fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
739 fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
740 fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
742 // XXX scripts should go into the library.
743 fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
746 chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
751 * Return the connection to the database.
753 * @return Database object.
755 * Creates a new connection if none exists yet. Otherwise reuses the
756 * already established connection.
758 private function db()
760 if (is_null($this->oDB)) {
761 $this->oDB = new \Nominatim\DB();
762 $this->oDB->connect();
768 private function removeFlatnodeFile()
770 $sFName = getSetting('FLATNODE_FILE');
771 if ($sFName && file_exists($sFName)) {
772 if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
777 private function pgsqlRunScript($sScript, $bfatal = true)
787 private function createSqlFunctions()
789 $oCmd = (clone($this->oNominatimCmd))
790 ->addParams('refresh', '--functions');
792 if (!$this->bEnableDiffUpdates) {
793 $oCmd->addParams('--no-diff-updates');
796 if ($this->bEnableDebugStatements) {
797 $oCmd->addParams('--enable-debug-statements');
803 private function pgsqlRunPartitionScript($sTemplate)
805 $sSQL = 'select distinct partition from country_name';
806 $aPartitions = $this->db()->getCol($sSQL);
807 if (!$this->bNoPartitions) $aPartitions[] = 0;
809 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
810 foreach ($aMatches as $aMatch) {
812 foreach ($aPartitions as $sPartitionName) {
813 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
815 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
818 $this->pgsqlRunScript($sTemplate);
821 private function pgsqlRunScriptFile($sFilename)
823 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
825 $oCmd = (new \Nominatim\Shell('psql'))
826 ->addParams('--port', $this->aDSNInfo['port'])
827 ->addParams('--dbname', $this->aDSNInfo['database']);
829 if (!$this->bVerbose) {
830 $oCmd->addParams('--quiet');
832 if (isset($this->aDSNInfo['hostspec'])) {
833 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
835 if (isset($this->aDSNInfo['username'])) {
836 $oCmd->addParams('--username', $this->aDSNInfo['username']);
838 if (isset($this->aDSNInfo['password'])) {
839 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
842 if (preg_match('/\\.gz$/', $sFilename)) {
843 $aDescriptors = array(
844 0 => array('pipe', 'r'),
845 1 => array('pipe', 'w'),
846 2 => array('file', '/dev/null', 'a')
848 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
850 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
851 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
852 $aReadPipe = $ahGzipPipes[1];
853 fclose($ahGzipPipes[0]);
855 $oCmd->addParams('--file', $sFilename);
856 $aReadPipe = array('pipe', 'r');
858 $aDescriptors = array(
860 1 => array('pipe', 'w'),
861 2 => array('file', '/dev/null', 'a')
865 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
866 if (!is_resource($hProcess)) fail('unable to start pgsql');
867 // TODO: error checking
868 while (!feof($ahPipes[1])) {
869 echo fread($ahPipes[1], 4096);
872 $iReturn = proc_close($hProcess);
874 fail("pgsql returned with error code ($iReturn)");
877 fclose($ahGzipPipes[1]);
878 proc_close($hGzipProcess);
882 private function replaceSqlPatterns($sSql)
884 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
887 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
888 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
889 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
890 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
891 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
892 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
895 foreach ($aPatterns as $sPattern => $sTablespace) {
897 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
899 $sSql = str_replace($sPattern, '', $sSql);
907 * Drop table with the given name if it exists.
909 * @param string $sName Name of table to remove.
913 private function dropTable($sName)
915 if ($this->bVerbose) echo "Dropping table $sName\n";
916 $this->db()->deleteTable($sName);
920 * Check if the database is in reverse-only mode.
922 * @return True if there is no search_name table and infrastructure.
924 private function dbReverseOnly()
926 return !($this->db()->tableExists('search_name'));
930 * Try accessing the C module, so we know early if something is wrong.
932 * Raises Nominatim\DatabaseError on failure
934 private function checkModulePresence()
936 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
937 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
938 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
940 $oDB = new \Nominatim\DB();
942 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');