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 (!is_null(CONST_Osm2pgsql_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 (strlen($this->sModulePath) == 0 || $this->sModulePath[0] != '/') {
47 $this->sModulePath = CONST_InstallDir.'/'.$this->sModulePath;
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(CONST_Osm2pgsql_Binary)) {
181 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
182 echo "Normally you should not need to set this manually.\n";
183 fail("osm2pgsql not found in '".CONST_Osm2pgsql_Binary."'");
186 $oCmd = new \Nominatim\Shell(CONST_Osm2pgsql_Binary);
187 $oCmd->addParams('--style', CONST_Import_Style);
189 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
190 $oCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
192 if (CONST_Tablespace_Osm2pgsql_Data) {
193 $oCmd->addParams('--tablespace-slim-data', CONST_Tablespace_Osm2pgsql_Data);
195 if (CONST_Tablespace_Osm2pgsql_Index) {
196 $oCmd->addParams('--tablespace-slim-index', CONST_Tablespace_Osm2pgsql_Index);
198 if (CONST_Tablespace_Place_Data) {
199 $oCmd->addParams('--tablespace-main-data', CONST_Tablespace_Place_Data);
201 if (CONST_Tablespace_Place_Index) {
202 $oCmd->addParams('--tablespace-main-index', CONST_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(CONST_Address_Level_Config);
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 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
294 if (file_exists($sWikiArticlesFile)) {
295 info('Importing wikipedia articles and redirects');
296 $this->dropTable('wikipedia_article');
297 $this->dropTable('wikipedia_redirect');
298 $this->pgsqlRunScriptFile($sWikiArticlesFile);
300 warn('wikipedia importance dump file not found - places will have default importance');
304 public function loadData($bDisableTokenPrecalc)
306 info('Drop old Data');
310 $oDB->exec('TRUNCATE word');
312 $oDB->exec('TRUNCATE placex');
314 $oDB->exec('TRUNCATE location_property_osmline');
316 $oDB->exec('TRUNCATE place_addressline');
318 $oDB->exec('TRUNCATE location_area');
320 if (!$this->dbReverseOnly()) {
321 $oDB->exec('TRUNCATE search_name');
324 $oDB->exec('TRUNCATE search_name_blank');
326 $oDB->exec('DROP SEQUENCE seq_place');
328 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
331 $sSQL = 'select distinct partition from country_name';
332 $aPartitions = $oDB->getCol($sSQL);
334 if (!$this->bNoPartitions) $aPartitions[] = 0;
335 foreach ($aPartitions as $sPartition) {
336 $oDB->exec('TRUNCATE location_road_'.$sPartition);
340 // used by getorcreate_word_id to ignore frequent partial words
341 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
342 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
346 // pre-create the word list
347 if (!$bDisableTokenPrecalc) {
348 info('Loading word list');
349 $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
353 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
355 $aDBInstances = array();
356 $iLoadThreads = max(1, $this->iInstances - 1);
357 for ($i = 0; $i < $iLoadThreads; $i++) {
358 // https://secure.php.net/manual/en/function.pg-connect.php
359 $DSN = getSetting('DATABASE_DSN');
360 $DSN = preg_replace('/^pgsql:/', '', $DSN);
361 $DSN = preg_replace('/;/', ' ', $DSN);
362 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
363 pg_ping($aDBInstances[$i]);
366 for ($i = 0; $i < $iLoadThreads; $i++) {
367 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
368 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
369 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
370 $sSQL .= ' and ST_IsValid(geometry)';
371 if ($this->bVerbose) echo "$sSQL\n";
372 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
373 fail(pg_last_error($aDBInstances[$i]));
377 // last thread for interpolation lines
378 // https://secure.php.net/manual/en/function.pg-connect.php
379 $DSN = getSetting('DATABASE_DSN');
380 $DSN = preg_replace('/^pgsql:/', '', $DSN);
381 $DSN = preg_replace('/;/', ' ', $DSN);
382 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
383 pg_ping($aDBInstances[$iLoadThreads]);
384 $sSQL = 'insert into location_property_osmline';
385 $sSQL .= ' (osm_id, address, linegeo)';
386 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
387 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
388 if ($this->bVerbose) echo "$sSQL\n";
389 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
390 fail(pg_last_error($aDBInstances[$iLoadThreads]));
394 for ($i = 0; $i <= $iLoadThreads; $i++) {
395 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
396 $resultStatus = pg_result_status($hPGresult);
397 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
398 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
399 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
400 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
401 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
402 $resultError = pg_result_error($hPGresult);
403 echo '-- error text ' . $i . ': ' . $resultError . "\n";
409 fail('SQL errors loading placex and/or location_property_osmline tables');
412 for ($i = 0; $i < $this->iInstances; $i++) {
413 pg_close($aDBInstances[$i]);
417 info('Reanalysing database');
418 $this->pgsqlRunScript('ANALYSE');
420 $sDatabaseDate = getDatabaseDate($oDB);
421 $oDB->exec('TRUNCATE import_status');
422 if (!$sDatabaseDate) {
423 warn('could not determine database date.');
425 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
427 echo "Latest data imported from $sDatabaseDate.\n";
431 public function importTigerData()
433 info('Import Tiger data');
435 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
436 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
437 if (empty($aFilenames)) {
438 warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
441 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
442 $sTemplate = $this->replaceSqlPatterns($sTemplate);
444 $this->pgsqlRunScript($sTemplate, false);
446 $aDBInstances = array();
447 for ($i = 0; $i < $this->iInstances; $i++) {
448 // https://secure.php.net/manual/en/function.pg-connect.php
449 $DSN = getSetting('DATABASE_DSN');
450 $DSN = preg_replace('/^pgsql:/', '', $DSN);
451 $DSN = preg_replace('/;/', ' ', $DSN);
452 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
453 pg_ping($aDBInstances[$i]);
456 foreach ($aFilenames as $sFile) {
458 $hFile = fopen($sFile, 'r');
459 $sSQL = fgets($hFile, 100000);
462 for ($i = 0; $i < $this->iInstances; $i++) {
463 if (!pg_connection_busy($aDBInstances[$i])) {
464 while (pg_get_result($aDBInstances[$i]));
465 $sSQL = fgets($hFile, 100000);
467 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
469 if ($iLines == 1000) {
482 for ($i = 0; $i < $this->iInstances; $i++) {
483 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
490 for ($i = 0; $i < $this->iInstances; $i++) {
491 pg_close($aDBInstances[$i]);
494 info('Creating indexes on Tiger data');
495 $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
496 $sTemplate = $this->replaceSqlPatterns($sTemplate);
498 $this->pgsqlRunScript($sTemplate, false);
501 public function calculatePostcodes($bCMDResultAll)
503 info('Calculate Postcodes');
504 $this->db()->exec('TRUNCATE location_postcode');
506 $sSQL = 'INSERT INTO location_postcode';
507 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
508 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
509 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
510 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
511 $sSQL .= ' FROM placex';
512 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
513 $sSQL .= ' AND geometry IS NOT null';
514 $sSQL .= ' GROUP BY country_code, pc';
515 $this->db()->exec($sSQL);
517 // only add postcodes that are not yet available in OSM
518 $sSQL = 'INSERT INTO location_postcode';
519 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
520 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
521 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
522 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
523 $sSQL .= ' (SELECT postcode FROM location_postcode';
524 $sSQL .= " WHERE country_code = 'us')";
525 $this->db()->exec($sSQL);
527 // add missing postcodes for GB (if available)
528 $sSQL = 'INSERT INTO location_postcode';
529 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
530 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
531 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
532 $sSQL .= ' (SELECT postcode FROM location_postcode';
533 $sSQL .= " WHERE country_code = 'gb')";
534 $this->db()->exec($sSQL);
536 if (!$bCMDResultAll) {
537 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
538 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
539 $this->db()->exec($sSQL);
542 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
543 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
544 $this->db()->exec($sSQL);
547 public function index($bIndexNoanalyse)
549 $this->checkModulePresence(); // raises exception on failure
551 $oBaseCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
552 ->addParams('--database', $this->aDSNInfo['database'])
553 ->addParams('--port', $this->aDSNInfo['port'])
554 ->addParams('--threads', $this->iInstances);
556 if (!$this->bQuiet) {
557 $oBaseCmd->addParams('-v');
559 if ($this->bVerbose) {
560 $oBaseCmd->addParams('-v');
562 if (isset($this->aDSNInfo['hostspec'])) {
563 $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
565 if (isset($this->aDSNInfo['username'])) {
566 $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
568 if (isset($this->aDSNInfo['password'])) {
569 $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
572 info('Index ranks 0 - 4');
573 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
574 echo $oCmd->escapedCmd();
576 $iStatus = $oCmd->run();
578 fail('error status ' . $iStatus . ' running nominatim!');
580 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
582 info('Index administrative boundaries');
583 $oCmd = (clone $oBaseCmd)->addParams('-b');
584 $iStatus = $oCmd->run();
586 fail('error status ' . $iStatus . ' running nominatim!');
589 info('Index ranks 5 - 25');
590 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
591 $iStatus = $oCmd->run();
593 fail('error status ' . $iStatus . ' running nominatim!');
596 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
598 info('Index ranks 26 - 30');
599 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
600 $iStatus = $oCmd->run();
602 fail('error status ' . $iStatus . ' running nominatim!');
605 info('Index postcodes');
606 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
607 $this->db()->exec($sSQL);
610 public function createSearchIndices()
612 info('Create Search indices');
614 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
615 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
616 $aInvalidIndices = $this->db()->getCol($sSQL);
618 foreach ($aInvalidIndices as $sIndexName) {
619 info("Cleaning up invalid index $sIndexName");
620 $this->db()->exec("DROP INDEX $sIndexName;");
623 $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
625 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
627 if (!$this->dbReverseOnly()) {
628 $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
630 $sTemplate = $this->replaceSqlPatterns($sTemplate);
632 $this->pgsqlRunScript($sTemplate);
635 public function createCountryNames()
637 info('Create search index for default country names');
639 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
640 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
641 $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');
642 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
643 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
644 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
645 if (CONST_Languages) {
648 foreach (explode(',', CONST_Languages) as $sLang) {
649 $sSQL .= $sDelim."'name:$sLang'";
654 // all include all simple name tags
655 $sSQL .= "like 'name:%'";
658 $this->pgsqlRunScript($sSQL);
661 public function drop()
663 info('Drop tables only required for updates');
665 // The implementation is potentially a bit dangerous because it uses
666 // a positive selection of tables to keep, and deletes everything else.
667 // Including any tables that the unsuspecting user might have manually
668 // created. USE AT YOUR OWN PERIL.
669 // tables we want to keep. everything else goes.
670 $aKeepTables = array(
676 'location_property*',
689 $aDropTables = array();
690 $aHaveTables = $this->db()->getListOfTables();
692 foreach ($aHaveTables as $sTable) {
694 foreach ($aKeepTables as $sKeep) {
695 if (fnmatch($sKeep, $sTable)) {
700 if (!$bFound) array_push($aDropTables, $sTable);
702 foreach ($aDropTables as $sDrop) {
703 $this->dropTable($sDrop);
706 $this->removeFlatnodeFile();
710 * Setup settings-frontend.php in the build/website directory
714 public function setupWebsite()
716 $rOutputFile = fopen(CONST_InstallDir.'/settings/settings-frontend.php', 'w');
718 fwrite($rOutputFile, "<?php
719 if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
721 @define('CONST_Database_DSN', '".getSetting('DATABASE_DSN')."');
722 @define('CONST_Default_Language', ".(CONST_Default_Language ? ("'".CONST_Default_Language."'") : 'false').");
723 @define('CONST_Log_DB', ".(CONST_Log_DB ? 'true' : 'false').");
724 @define('CONST_Log_File', ".(CONST_Log_File ? ("'".CONST_Log_File."'") : 'false').");
725 @define('CONST_Max_Word_Frequency', '".CONST_Max_Word_Frequency."');
726 @define('CONST_NoAccessControl', ".CONST_NoAccessControl.");
727 @define('CONST_Places_Max_ID_count', ".CONST_Places_Max_ID_count.");
728 @define('CONST_PolygonOutput_MaximumTypes', ".CONST_PolygonOutput_MaximumTypes.");
729 @define('CONST_Search_AreaPolygons', ".CONST_Search_AreaPolygons.");
730 @define('CONST_Search_BatchMode', ".(CONST_Search_BatchMode ? 'true' : 'false').");
731 @define('CONST_Search_NameOnlySearchFrequencyThreshold', ".CONST_Search_NameOnlySearchFrequencyThreshold.");
732 @define('CONST_Search_ReversePlanForAll', ".CONST_Search_ReversePlanForAll.");
733 @define('CONST_Term_Normalization_Rules', \"".CONST_Term_Normalization_Rules."\");
734 @define('CONST_Use_Aux_Location_data', ".(CONST_Use_Aux_Location_data ? 'true' : 'false').");
735 @define('CONST_Use_US_Tiger_Data', ".(CONST_Use_US_Tiger_Data ? 'true' : 'false').");
736 @define('CONST_MapIcon_URL', ".(CONST_MapIcon_URL ? ("'".CONST_MapIcon_URL."'") : 'false').');
738 info(CONST_InstallDir.'/settings/settings-frontend.php has been set up successfully');
742 * Return the connection to the database.
744 * @return Database object.
746 * Creates a new connection if none exists yet. Otherwise reuses the
747 * already established connection.
749 private function db()
751 if (is_null($this->oDB)) {
752 $this->oDB = new \Nominatim\DB();
753 $this->oDB->connect();
759 private function removeFlatnodeFile()
761 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
762 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
763 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
764 unlink(CONST_Osm2pgsql_Flatnode_File);
769 private function pgsqlRunScript($sScript, $bfatal = true)
779 private function createSqlFunctions()
781 $sBasePath = CONST_DataDir.'/sql/functions/';
782 $sTemplate = file_get_contents($sBasePath.'utils.sql');
783 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
784 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
785 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
786 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
787 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
788 if ($this->db()->tableExists('place')) {
789 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
791 if ($this->db()->tableExists('placex')) {
792 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
794 if ($this->db()->tableExists('location_postcode')) {
795 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
797 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
798 if ($this->bEnableDiffUpdates) {
799 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
801 if ($this->bEnableDebugStatements) {
802 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
804 if (CONST_Limit_Reindexing) {
805 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
807 if (!CONST_Use_US_Tiger_Data) {
808 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
810 if (!CONST_Use_Aux_Location_data) {
811 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
814 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
815 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
817 $this->pgsqlRunScript($sTemplate);
820 private function pgsqlRunPartitionScript($sTemplate)
822 $sSQL = 'select distinct partition from country_name';
823 $aPartitions = $this->db()->getCol($sSQL);
824 if (!$this->bNoPartitions) $aPartitions[] = 0;
826 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
827 foreach ($aMatches as $aMatch) {
829 foreach ($aPartitions as $sPartitionName) {
830 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
832 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
835 $this->pgsqlRunScript($sTemplate);
838 private function pgsqlRunScriptFile($sFilename)
840 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
842 $oCmd = (new \Nominatim\Shell('psql'))
843 ->addParams('--port', $this->aDSNInfo['port'])
844 ->addParams('--dbname', $this->aDSNInfo['database']);
846 if (!$this->bVerbose) {
847 $oCmd->addParams('--quiet');
849 if (isset($this->aDSNInfo['hostspec'])) {
850 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
852 if (isset($this->aDSNInfo['username'])) {
853 $oCmd->addParams('--username', $this->aDSNInfo['username']);
855 if (isset($this->aDSNInfo['password'])) {
856 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
859 if (preg_match('/\\.gz$/', $sFilename)) {
860 $aDescriptors = array(
861 0 => array('pipe', 'r'),
862 1 => array('pipe', 'w'),
863 2 => array('file', '/dev/null', 'a')
865 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
867 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
868 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
869 $aReadPipe = $ahGzipPipes[1];
870 fclose($ahGzipPipes[0]);
872 $oCmd->addParams('--file', $sFilename);
873 $aReadPipe = array('pipe', 'r');
875 $aDescriptors = array(
877 1 => array('pipe', 'w'),
878 2 => array('file', '/dev/null', 'a')
882 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
883 if (!is_resource($hProcess)) fail('unable to start pgsql');
884 // TODO: error checking
885 while (!feof($ahPipes[1])) {
886 echo fread($ahPipes[1], 4096);
889 $iReturn = proc_close($hProcess);
891 fail("pgsql returned with error code ($iReturn)");
894 fclose($ahGzipPipes[1]);
895 proc_close($hGzipProcess);
899 private function replaceSqlPatterns($sSql)
901 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
904 '{ts:address-data}' => CONST_Tablespace_Address_Data,
905 '{ts:address-index}' => CONST_Tablespace_Address_Index,
906 '{ts:search-data}' => CONST_Tablespace_Search_Data,
907 '{ts:search-index}' => CONST_Tablespace_Search_Index,
908 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
909 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
912 foreach ($aPatterns as $sPattern => $sTablespace) {
914 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
916 $sSql = str_replace($sPattern, '', $sSql);
924 * Drop table with the given name if it exists.
926 * @param string $sName Name of table to remove.
930 private function dropTable($sName)
932 if ($this->bVerbose) echo "Dropping table $sName\n";
933 $this->db()->deleteTable($sName);
937 * Check if the database is in reverse-only mode.
939 * @return True if there is no search_name table and infrastructure.
941 private function dbReverseOnly()
943 return !($this->db()->tableExists('search_name'));
947 * Try accessing the C module, so we know early if something is wrong.
949 * Raises Nominatim\DatabaseError on failure
951 private function checkModulePresence()
953 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
954 $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
955 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
957 $oDB = new \Nominatim\DB();
959 $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');