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');
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'];
86 public function createDB()
89 $oDB = new \Nominatim\DB;
91 if ($oDB->checkConnection()) {
92 fail('database already exists ('.getSetting('DATABASE_DSN').')');
95 $oCmd = (new \Nominatim\Shell('createdb'))
96 ->addParams('-E', 'UTF-8')
97 ->addParams('-p', $this->aDSNInfo['port']);
99 if (isset($this->aDSNInfo['username'])) {
100 $oCmd->addParams('-U', $this->aDSNInfo['username']);
102 if (isset($this->aDSNInfo['password'])) {
103 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
105 if (isset($this->aDSNInfo['hostspec'])) {
106 $oCmd->addParams('-h', $this->aDSNInfo['hostspec']);
108 $oCmd->addParams($this->aDSNInfo['database']);
110 $result = $oCmd->run();
111 if ($result != 0) fail('Error executing external command: '.$oCmd->escapedCmd());
114 public function setupDB()
118 $fPostgresVersion = $this->db()->getPostgresVersion();
119 echo 'Postgres version found: '.$fPostgresVersion."\n";
121 if ($fPostgresVersion < 9.03) {
122 fail('Minimum supported version of Postgresql is 9.3.');
125 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
126 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
128 $fPostgisVersion = $this->db()->getPostgisVersion();
129 echo 'Postgis version found: '.$fPostgisVersion."\n";
131 if ($fPostgisVersion < 2.2) {
132 echo "Minimum required Postgis version 2.2\n";
136 $sPgUser = getSetting('DATABASE_WEBUSER');
137 $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
139 echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
140 echo "\n createuser ".$sPgUser."\n\n";
144 // Try accessing the C module, so we know early if something is wrong
145 $this->checkModulePresence(); // raises exception on failure
147 if (!file_exists(CONST_DataDir.'/data/country_osm_grid.sql.gz')) {
148 echo 'Error: you need to download the country_osm_grid first:';
149 echo "\n wget -O ".CONST_DataDir."/data/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
152 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_name.sql');
153 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_osm_grid.sql.gz');
154 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/gb_postcode_table.sql');
155 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/us_postcode_table.sql');
157 $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
158 if (file_exists($sPostcodeFilename)) {
159 $this->pgsqlRunScriptFile($sPostcodeFilename);
161 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
164 $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
165 if (file_exists($sPostcodeFilename)) {
166 $this->pgsqlRunScriptFile($sPostcodeFilename);
168 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
171 if ($this->bNoPartitions) {
172 $this->pgsqlRunScript('update country_name set partition = 0');
176 public function importData($sOSMFile)
180 if (!file_exists(getOsm2pgsqlBinary())) {
181 echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
182 echo "Normally you should not need to set this manually.\n";
183 fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
186 $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
187 $oCmd->addParams('--style', getImportStyle());
189 if (getSetting('FLATNODE_FILE')) {
190 $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
192 if (getSetting('TABLESPACE_OSM_DATA')) {
193 $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
195 if (getSetting('TABLESPACE_OSM_INDEX')) {
196 $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
198 if (getSetting('TABLESPACE_PLACE_DATA')) {
199 $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
201 if (getSetting('TABLESPACE_PLACE_INDEX')) {
202 $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
204 $oCmd->addParams('--latlong', '--slim', '--create');
205 $oCmd->addParams('--output', 'gazetteer');
206 $oCmd->addParams('--hstore');
207 $oCmd->addParams('--number-processes', 1);
208 $oCmd->addParams('--with-forward-dependencies', 'false');
209 $oCmd->addParams('--log-progress', 'true');
210 $oCmd->addParams('--cache', $this->iCacheMemory);
211 $oCmd->addParams('--port', $this->aDSNInfo['port']);
213 if (isset($this->aDSNInfo['username'])) {
214 $oCmd->addParams('--username', $this->aDSNInfo['username']);
216 if (isset($this->aDSNInfo['password'])) {
217 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
219 if (isset($this->aDSNInfo['hostspec'])) {
220 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
222 $oCmd->addParams('--database', $this->aDSNInfo['database']);
223 $oCmd->addParams($sOSMFile);
226 if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
231 $this->dropTable('planet_osm_nodes');
232 $this->removeFlatnodeFile();
236 public function createFunctions()
238 info('Create Functions');
240 // Try accessing the C module, so we know early if something is wrong
241 $this->checkModulePresence(); // raises exception on failure
243 $this->createSqlFunctions();
246 public function createTables($bReverseOnly = false)
248 info('Create Tables');
250 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
251 $sTemplate = $this->replaceSqlPatterns($sTemplate);
253 $this->pgsqlRunScript($sTemplate, false);
256 $this->dropTable('search_name');
259 $oAlParser = new AddressLevelParser(getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json'));
260 $oAlParser->createTable($this->db(), 'address_levels');
263 public function createTableTriggers()
265 info('Create Tables');
267 $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
268 $sTemplate = $this->replaceSqlPatterns($sTemplate);
270 $this->pgsqlRunScript($sTemplate, false);
273 public function createPartitionTables()
275 info('Create Partition Tables');
277 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
278 $sTemplate = $this->replaceSqlPatterns($sTemplate);
280 $this->pgsqlRunPartitionScript($sTemplate);
283 public function createPartitionFunctions()
285 info('Create Partition Functions');
287 $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
288 $this->pgsqlRunPartitionScript($sTemplate);
291 public function importWikipediaArticles()
293 $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
294 $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
295 if (file_exists($sWikiArticlesFile)) {
296 info('Importing wikipedia articles and redirects');
297 $this->dropTable('wikipedia_article');
298 $this->dropTable('wikipedia_redirect');
299 $this->pgsqlRunScriptFile($sWikiArticlesFile);
301 warn('wikipedia importance dump file not found - places will have default importance');
305 public function loadData($bDisableTokenPrecalc)
307 info('Drop old Data');
311 $oDB->exec('TRUNCATE word');
313 $oDB->exec('TRUNCATE placex');
315 $oDB->exec('TRUNCATE location_property_osmline');
317 $oDB->exec('TRUNCATE place_addressline');
319 $oDB->exec('TRUNCATE location_area');
321 if (!$this->dbReverseOnly()) {
322 $oDB->exec('TRUNCATE search_name');
325 $oDB->exec('TRUNCATE search_name_blank');
327 $oDB->exec('DROP SEQUENCE seq_place');
329 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
332 $sSQL = 'select distinct partition from country_name';
333 $aPartitions = $oDB->getCol($sSQL);
335 if (!$this->bNoPartitions) $aPartitions[] = 0;
336 foreach ($aPartitions as $sPartition) {
337 $oDB->exec('TRUNCATE location_road_'.$sPartition);
341 // used by getorcreate_word_id to ignore frequent partial words
342 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
343 $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
347 // pre-create the word list
348 if (!$bDisableTokenPrecalc) {
349 info('Loading word list');
350 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
354 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
356 $aDBInstances = array();
357 $iLoadThreads = max(1, $this->iInstances - 1);
358 for ($i = 0; $i < $iLoadThreads; $i++) {
359 // https://secure.php.net/manual/en/function.pg-connect.php
360 $DSN = getSetting('DATABASE_DSN');
361 $DSN = preg_replace('/^pgsql:/', '', $DSN);
362 $DSN = preg_replace('/;/', ' ', $DSN);
363 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
364 pg_ping($aDBInstances[$i]);
367 for ($i = 0; $i < $iLoadThreads; $i++) {
368 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
369 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
370 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
371 $sSQL .= ' and ST_IsValid(geometry)';
372 if ($this->bVerbose) echo "$sSQL\n";
373 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
374 fail(pg_last_error($aDBInstances[$i]));
378 // last thread for interpolation lines
379 // https://secure.php.net/manual/en/function.pg-connect.php
380 $DSN = getSetting('DATABASE_DSN');
381 $DSN = preg_replace('/^pgsql:/', '', $DSN);
382 $DSN = preg_replace('/;/', ' ', $DSN);
383 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
384 pg_ping($aDBInstances[$iLoadThreads]);
385 $sSQL = 'insert into location_property_osmline';
386 $sSQL .= ' (osm_id, address, linegeo)';
387 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
388 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
389 if ($this->bVerbose) echo "$sSQL\n";
390 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
391 fail(pg_last_error($aDBInstances[$iLoadThreads]));
395 for ($i = 0; $i <= $iLoadThreads; $i++) {
396 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
397 $resultStatus = pg_result_status($hPGresult);
398 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
399 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
400 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
401 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
402 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
403 $resultError = pg_result_error($hPGresult);
404 echo '-- error text ' . $i . ': ' . $resultError . "\n";
410 fail('SQL errors loading placex and/or location_property_osmline tables');
413 for ($i = 0; $i < $this->iInstances; $i++) {
414 pg_close($aDBInstances[$i]);
418 info('Reanalysing database');
419 $this->pgsqlRunScript('ANALYSE');
421 $sDatabaseDate = getDatabaseDate($oDB);
422 $oDB->exec('TRUNCATE import_status');
423 if (!$sDatabaseDate) {
424 warn('could not determine database date.');
426 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
428 echo "Latest data imported from $sDatabaseDate.\n";
432 public function importTigerData($sTigerPath)
434 info('Import Tiger data');
436 $aFilenames = glob($sTigerPath.'/*.sql');
437 info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
438 if (empty($aFilenames)) {
439 warn('Tiger data import selected but no files found in path '.$sTigerPath);
442 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
443 $sTemplate = $this->replaceSqlPatterns($sTemplate);
445 $this->pgsqlRunScript($sTemplate, false);
447 $aDBInstances = array();
448 for ($i = 0; $i < $this->iInstances; $i++) {
449 // https://secure.php.net/manual/en/function.pg-connect.php
450 $DSN = getSetting('DATABASE_DSN');
451 $DSN = preg_replace('/^pgsql:/', '', $DSN);
452 $DSN = preg_replace('/;/', ' ', $DSN);
453 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
454 pg_ping($aDBInstances[$i]);
457 foreach ($aFilenames as $sFile) {
459 $hFile = fopen($sFile, 'r');
460 $sSQL = fgets($hFile, 100000);
463 for ($i = 0; $i < $this->iInstances; $i++) {
464 if (!pg_connection_busy($aDBInstances[$i])) {
465 while (pg_get_result($aDBInstances[$i]));
466 $sSQL = fgets($hFile, 100000);
468 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
470 if ($iLines == 1000) {
483 for ($i = 0; $i < $this->iInstances; $i++) {
484 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
491 for ($i = 0; $i < $this->iInstances; $i++) {
492 pg_close($aDBInstances[$i]);
495 info('Creating indexes on Tiger data');
496 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
497 $sTemplate = $this->replaceSqlPatterns($sTemplate);
499 $this->pgsqlRunScript($sTemplate, false);
502 public function calculatePostcodes($bCMDResultAll)
504 info('Calculate Postcodes');
505 $this->db()->exec('TRUNCATE location_postcode');
507 $sSQL = 'INSERT INTO location_postcode';
508 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
509 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
510 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
511 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
512 $sSQL .= ' FROM placex';
513 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
514 $sSQL .= ' AND geometry IS NOT null';
515 $sSQL .= ' GROUP BY country_code, pc';
516 $this->db()->exec($sSQL);
518 // only add postcodes that are not yet available in OSM
519 $sSQL = 'INSERT INTO location_postcode';
520 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
521 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
522 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
523 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
524 $sSQL .= ' (SELECT postcode FROM location_postcode';
525 $sSQL .= " WHERE country_code = 'us')";
526 $this->db()->exec($sSQL);
528 // add missing postcodes for GB (if available)
529 $sSQL = 'INSERT INTO location_postcode';
530 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
531 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
532 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
533 $sSQL .= ' (SELECT postcode FROM location_postcode';
534 $sSQL .= " WHERE country_code = 'gb')";
535 $this->db()->exec($sSQL);
537 if (!$bCMDResultAll) {
538 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
539 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
540 $this->db()->exec($sSQL);
543 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
544 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
545 $this->db()->exec($sSQL);
548 public function index($bIndexNoanalyse)
550 $this->checkModulePresence(); // raises exception on failure
552 $oBaseCmd = (new \Nominatim\Shell(getSetting('NOMINATIM_TOOL')))
553 ->addParams('index');
556 $oBaseCmd->addParams('-q');
558 if ($this->bVerbose) {
559 $oBaseCmd->addParams('-v');
562 info('Index ranks 0 - 4');
563 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
564 echo $oCmd->escapedCmd();
566 $iStatus = $oCmd->run();
568 fail('error status ' . $iStatus . ' running nominatim!');
570 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
572 info('Index administrative boundaries');
573 $oCmd = (clone $oBaseCmd)->addParams('--boundaries-only');
574 $iStatus = $oCmd->run();
576 fail('error status ' . $iStatus . ' running nominatim!');
579 info('Index ranks 5 - 25');
580 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 5, '--maxrank', 25);
581 $iStatus = $oCmd->run();
583 fail('error status ' . $iStatus . ' running nominatim!');
586 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
588 info('Index ranks 26 - 30');
589 $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 26);
590 $iStatus = $oCmd->run();
592 fail('error status ' . $iStatus . ' running nominatim!');
595 info('Index postcodes');
596 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
597 $this->db()->exec($sSQL);
600 public function createSearchIndices()
602 info('Create Search indices');
604 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
605 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
606 $aInvalidIndices = $this->db()->getCol($sSQL);
608 foreach ($aInvalidIndices as $sIndexName) {
609 info("Cleaning up invalid index $sIndexName");
610 $this->db()->exec("DROP INDEX $sIndexName;");
613 $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
615 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
617 if (!$this->dbReverseOnly()) {
618 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
620 $sTemplate = $this->replaceSqlPatterns($sTemplate);
622 $this->pgsqlRunScript($sTemplate);
625 public function createCountryNames()
627 info('Create search index for default country names');
629 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
630 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
631 $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');
632 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
633 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
634 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
635 $sLanguages = getSetting('LANGUAGES');
639 foreach (explode(',', $sLanguages) as $sLang) {
640 $sSQL .= $sDelim."'name:$sLang'";
645 // all include all simple name tags
646 $sSQL .= "like 'name:%'";
649 $this->pgsqlRunScript($sSQL);
652 public function drop()
654 info('Drop tables only required for updates');
656 // The implementation is potentially a bit dangerous because it uses
657 // a positive selection of tables to keep, and deletes everything else.
658 // Including any tables that the unsuspecting user might have manually
659 // created. USE AT YOUR OWN PERIL.
660 // tables we want to keep. everything else goes.
661 $aKeepTables = array(
667 'location_property*',
680 $aDropTables = array();
681 $aHaveTables = $this->db()->getListOfTables();
683 foreach ($aHaveTables as $sTable) {
685 foreach ($aKeepTables as $sKeep) {
686 if (fnmatch($sKeep, $sTable)) {
691 if (!$bFound) array_push($aDropTables, $sTable);
693 foreach ($aDropTables as $sDrop) {
694 $this->dropTable($sDrop);
697 $this->removeFlatnodeFile();
701 * Setup the directory for the API scripts.
705 public function setupWebsite()
707 if (!is_dir(CONST_InstallDir.'/website')) {
708 info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
709 mkdir(CONST_InstallDir.'/website');
722 foreach ($aScripts as $sScript) {
723 $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
725 fwrite($rFile, "<?php\n\n");
726 fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
728 fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
729 fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
730 fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
731 fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
732 fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
733 fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
734 fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
735 fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
736 fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
737 fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
738 fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
739 fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
740 fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
741 fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
742 fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
743 fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
744 fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
746 // XXX scripts should go into the library.
747 fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
750 chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
755 * Return the connection to the database.
757 * @return Database object.
759 * Creates a new connection if none exists yet. Otherwise reuses the
760 * already established connection.
762 private function db()
764 if (is_null($this->oDB)) {
765 $this->oDB = new \Nominatim\DB();
766 $this->oDB->connect();
772 private function removeFlatnodeFile()
774 $sFName = getSetting('FLATNODE_FILE');
775 if ($sFName && file_exists($sFName)) {
776 if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
781 private function pgsqlRunScript($sScript, $bfatal = true)
791 private function createSqlFunctions()
793 $sBasePath = CONST_DataDir.'/sql/functions/';
794 $sTemplate = file_get_contents($sBasePath.'utils.sql');
795 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
796 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
797 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
798 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
799 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
800 if ($this->db()->tableExists('place')) {
801 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
803 if ($this->db()->tableExists('placex')) {
804 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
806 if ($this->db()->tableExists('location_postcode')) {
807 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
809 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
810 if ($this->bEnableDiffUpdates) {
811 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
813 if ($this->bEnableDebugStatements) {
814 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
816 if (getSettingBool('LIMIT_REINDEXING')) {
817 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
819 if (!getSettingBool('USE_US_TIGER_DATA')) {
820 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
822 if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
823 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
826 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
827 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
829 $this->pgsqlRunScript($sTemplate);
832 private function pgsqlRunPartitionScript($sTemplate)
834 $sSQL = 'select distinct partition from country_name';
835 $aPartitions = $this->db()->getCol($sSQL);
836 if (!$this->bNoPartitions) $aPartitions[] = 0;
838 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
839 foreach ($aMatches as $aMatch) {
841 foreach ($aPartitions as $sPartitionName) {
842 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
844 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
847 $this->pgsqlRunScript($sTemplate);
850 private function pgsqlRunScriptFile($sFilename)
852 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
854 $oCmd = (new \Nominatim\Shell('psql'))
855 ->addParams('--port', $this->aDSNInfo['port'])
856 ->addParams('--dbname', $this->aDSNInfo['database']);
858 if (!$this->bVerbose) {
859 $oCmd->addParams('--quiet');
861 if (isset($this->aDSNInfo['hostspec'])) {
862 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
864 if (isset($this->aDSNInfo['username'])) {
865 $oCmd->addParams('--username', $this->aDSNInfo['username']);
867 if (isset($this->aDSNInfo['password'])) {
868 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
871 if (preg_match('/\\.gz$/', $sFilename)) {
872 $aDescriptors = array(
873 0 => array('pipe', 'r'),
874 1 => array('pipe', 'w'),
875 2 => array('file', '/dev/null', 'a')
877 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
879 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
880 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
881 $aReadPipe = $ahGzipPipes[1];
882 fclose($ahGzipPipes[0]);
884 $oCmd->addParams('--file', $sFilename);
885 $aReadPipe = array('pipe', 'r');
887 $aDescriptors = array(
889 1 => array('pipe', 'w'),
890 2 => array('file', '/dev/null', 'a')
894 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
895 if (!is_resource($hProcess)) fail('unable to start pgsql');
896 // TODO: error checking
897 while (!feof($ahPipes[1])) {
898 echo fread($ahPipes[1], 4096);
901 $iReturn = proc_close($hProcess);
903 fail("pgsql returned with error code ($iReturn)");
906 fclose($ahGzipPipes[1]);
907 proc_close($hGzipProcess);
911 private function replaceSqlPatterns($sSql)
913 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
916 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
917 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
918 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
919 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
920 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
921 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
924 foreach ($aPatterns as $sPattern => $sTablespace) {
926 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
928 $sSql = str_replace($sPattern, '', $sSql);
936 * Drop table with the given name if it exists.
938 * @param string $sName Name of table to remove.
942 private function dropTable($sName)
944 if ($this->bVerbose) echo "Dropping table $sName\n";
945 $this->db()->deleteTable($sName);
949 * Check if the database is in reverse-only mode.
951 * @return True if there is no search_name table and infrastructure.
953 private function dbReverseOnly()
955 return !($this->db()->tableExists('search_name'));
959 * Try accessing the C module, so we know early if something is wrong.
961 * Raises Nominatim\DatabaseError on failure
963 private function checkModulePresence()
965 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
966 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
967 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
969 $oDB = new \Nominatim\DB();
971 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');