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 = getSettings('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 settings-frontend.php in the build/website directory
713 public function setupWebsite()
715 $rOutputFile = fopen(CONST_InstallDir.'/settings/settings-frontend.php', 'w');
717 fwrite($rOutputFile, "<?php
718 @define('CONST_Database_DSN', '".getSetting('DATABASE_DSN')."');
719 @define('CONST_Default_Language', ".getSetting('DEFAULT_LANGUAGE', 'false').");
720 @define('CONST_Log_DB', ".(getSettingBool('LOG_DB') ? 'true' : 'false').");
721 @define('CONST_Log_File', ".getSetting('LOG_FILE', 'false').");
722 @define('CONST_Max_Word_Frequency', '".getSetting('MAX_WORD_FREQUENCY')."');
723 @define('CONST_NoAccessControl', ".(getSettingBool('CORS_NOACCESSCONTROL') ? 'true' : 'false').");
724 @define('CONST_Places_Max_ID_count', ".getSetting('LOOKUP_MAX_COUNT').");
725 @define('CONST_PolygonOutput_MaximumTypes', ".getSetting('POLYGON_OUTPUT_MAX_TYPES').");
726 @define('CONST_Search_BatchMode', ".(getSettingBool('SEARCH_BATCH_MODE' ? 'true' : 'false').");
727 @define('CONST_Search_NameOnlySearchFrequencyThreshold', ".getSetting('SEARCH_NAME_ONLY_THRESHOLD').");
728 @define('CONST_Term_Normalization_Rules', \"".getSetting('TERM_NORMALIZATION')."\");
729 @define('CONST_Use_Aux_Location_data', ".(getSettingBool('USE_AUX_LOCATION_DATA') ? 'true' : 'false').");
730 @define('CONST_Use_US_Tiger_Data', ".(getSettingBool('USE_US_TIGER_DATA') ? 'true' : 'false').");
731 @define('CONST_MapIcon_URL', ".(getSetting('MAPICON_URL', 'false').');
733 info(CONST_InstallDir.'/settings/settings-frontend.php has been set up successfully');
737 * Return the connection to the database.
739 * @return Database object.
741 * Creates a new connection if none exists yet. Otherwise reuses the
742 * already established connection.
744 private function db()
746 if (is_null($this->oDB)) {
747 $this->oDB = new \Nominatim\DB();
748 $this->oDB->connect();
754 private function removeFlatnodeFile()
756 $sFName = getSetting('FLATNODE_FILE');
757 if ($sFName && file_exists($sFName)) {
758 if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
764 private function pgsqlRunScript($sScript, $bfatal = true)
774 private function createSqlFunctions()
776 $sBasePath = CONST_DataDir.'/sql/functions/';
777 $sTemplate = file_get_contents($sBasePath.'utils.sql');
778 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
779 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
780 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
781 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
782 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
783 if ($this->db()->tableExists('place')) {
784 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
786 if ($this->db()->tableExists('placex')) {
787 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
789 if ($this->db()->tableExists('location_postcode')) {
790 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
792 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
793 if ($this->bEnableDiffUpdates) {
794 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
796 if ($this->bEnableDebugStatements) {
797 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
799 if (getSettingBool('LIMIT_REINDEXING')) {
800 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
802 if (!getSettingBool('USE_US_TIGER_DATA')) {
803 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
805 if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
806 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
809 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
810 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
812 $this->pgsqlRunScript($sTemplate);
815 private function pgsqlRunPartitionScript($sTemplate)
817 $sSQL = 'select distinct partition from country_name';
818 $aPartitions = $this->db()->getCol($sSQL);
819 if (!$this->bNoPartitions) $aPartitions[] = 0;
821 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
822 foreach ($aMatches as $aMatch) {
824 foreach ($aPartitions as $sPartitionName) {
825 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
827 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
830 $this->pgsqlRunScript($sTemplate);
833 private function pgsqlRunScriptFile($sFilename)
835 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
837 $oCmd = (new \Nominatim\Shell('psql'))
838 ->addParams('--port', $this->aDSNInfo['port'])
839 ->addParams('--dbname', $this->aDSNInfo['database']);
841 if (!$this->bVerbose) {
842 $oCmd->addParams('--quiet');
844 if (isset($this->aDSNInfo['hostspec'])) {
845 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
847 if (isset($this->aDSNInfo['username'])) {
848 $oCmd->addParams('--username', $this->aDSNInfo['username']);
850 if (isset($this->aDSNInfo['password'])) {
851 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
854 if (preg_match('/\\.gz$/', $sFilename)) {
855 $aDescriptors = array(
856 0 => array('pipe', 'r'),
857 1 => array('pipe', 'w'),
858 2 => array('file', '/dev/null', 'a')
860 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
862 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
863 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
864 $aReadPipe = $ahGzipPipes[1];
865 fclose($ahGzipPipes[0]);
867 $oCmd->addParams('--file', $sFilename);
868 $aReadPipe = array('pipe', 'r');
870 $aDescriptors = array(
872 1 => array('pipe', 'w'),
873 2 => array('file', '/dev/null', 'a')
877 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
878 if (!is_resource($hProcess)) fail('unable to start pgsql');
879 // TODO: error checking
880 while (!feof($ahPipes[1])) {
881 echo fread($ahPipes[1], 4096);
884 $iReturn = proc_close($hProcess);
886 fail("pgsql returned with error code ($iReturn)");
889 fclose($ahGzipPipes[1]);
890 proc_close($hGzipProcess);
894 private function replaceSqlPatterns($sSql)
896 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
899 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
900 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
901 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
902 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
903 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
904 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
907 foreach ($aPatterns as $sPattern => $sTablespace) {
909 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
911 $sSql = str_replace($sPattern, '', $sSql);
919 * Drop table with the given name if it exists.
921 * @param string $sName Name of table to remove.
925 private function dropTable($sName)
927 if ($this->bVerbose) echo "Dropping table $sName\n";
928 $this->db()->deleteTable($sName);
932 * Check if the database is in reverse-only mode.
934 * @return True if there is no search_name table and infrastructure.
936 private function dbReverseOnly()
938 return !($this->db()->tableExists('search_name'));
942 * Try accessing the C module, so we know early if something is wrong.
944 * Raises Nominatim\DatabaseError on failure
946 private function checkModulePresence()
948 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
949 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
950 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
952 $oDB = new \Nominatim\DB();
954 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');