3 namespace Nominatim\Setup;
5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
6 require_once(CONST_BasePath.'/lib/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 = CONST_Database_Module_Path;
46 info('module path: ' . $this->sModulePath);
48 // parse database string
49 $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_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 ('.CONST_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 $i = $this->db()->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
135 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
136 echo "\n createuser ".CONST_Database_Web_User."\n\n";
140 // Try accessing the C module, so we know early if something is wrong
141 checkModulePresence(); // raises exception on failure
143 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
144 echo 'Error: you need to download the country_osm_grid first:';
145 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
148 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
149 $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
150 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
151 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
153 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
154 if (file_exists($sPostcodeFilename)) {
155 $this->pgsqlRunScriptFile($sPostcodeFilename);
157 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
160 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
161 if (file_exists($sPostcodeFilename)) {
162 $this->pgsqlRunScriptFile($sPostcodeFilename);
164 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
167 if ($this->bNoPartitions) {
168 $this->pgsqlRunScript('update country_name set partition = 0');
172 public function importData($sOSMFile)
176 if (!file_exists(CONST_Osm2pgsql_Binary)) {
177 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
178 echo "Normally you should not need to set this manually.\n";
179 fail("osm2pgsql not found in '".CONST_Osm2pgsql_Binary."'");
182 $oCmd = new \Nominatim\Shell(CONST_Osm2pgsql_Binary);
183 $oCmd->addParams('--style', CONST_Import_Style);
185 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
186 $oCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
188 if (CONST_Tablespace_Osm2pgsql_Data) {
189 $oCmd->addParams('--tablespace-slim-data', CONST_Tablespace_Osm2pgsql_Data);
191 if (CONST_Tablespace_Osm2pgsql_Index) {
192 $oCmd->addParams('--tablespace-slim-index', CONST_Tablespace_Osm2pgsql_Index);
194 if (CONST_Tablespace_Place_Data) {
195 $oCmd->addParams('--tablespace-main-data', CONST_Tablespace_Place_Data);
197 if (CONST_Tablespace_Place_Index) {
198 $oCmd->addParams('--tablespace-main-index', CONST_Tablespace_Place_Index);
200 $oCmd->addParams('--latlong', '--slim', '--create');
201 $oCmd->addParams('--output', 'gazetteer');
202 $oCmd->addParams('--hstore');
203 $oCmd->addParams('--number-processes', 1);
204 $oCmd->addParams('--with-forward-dependencies', 'false');
205 $oCmd->addParams('--log-progress', 'true');
206 $oCmd->addParams('--cache', $this->iCacheMemory);
207 $oCmd->addParams('--port', $this->aDSNInfo['port']);
209 if (isset($this->aDSNInfo['username'])) {
210 $oCmd->addParams('--username', $this->aDSNInfo['username']);
212 if (isset($this->aDSNInfo['password'])) {
213 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
215 if (isset($this->aDSNInfo['hostspec'])) {
216 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
218 $oCmd->addParams('--database', $this->aDSNInfo['database']);
219 $oCmd->addParams($sOSMFile);
222 if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
227 $this->dropTable('planet_osm_nodes');
228 $this->removeFlatnodeFile();
232 public function createFunctions()
234 info('Create Functions');
236 // Try accessing the C module, so we know early if something is wrong
237 checkModulePresence(); // raises exception on failure
239 $this->createSqlFunctions();
242 public function createTables($bReverseOnly = false)
244 info('Create Tables');
246 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
247 $sTemplate = $this->replaceSqlPatterns($sTemplate);
249 $this->pgsqlRunScript($sTemplate, false);
252 $this->dropTable('search_name');
255 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
256 $oAlParser->createTable($this->db(), 'address_levels');
259 public function createTableTriggers()
261 info('Create Tables');
263 $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
264 $sTemplate = $this->replaceSqlPatterns($sTemplate);
266 $this->pgsqlRunScript($sTemplate, false);
269 public function createPartitionTables()
271 info('Create Partition Tables');
273 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
274 $sTemplate = $this->replaceSqlPatterns($sTemplate);
276 $this->pgsqlRunPartitionScript($sTemplate);
279 public function createPartitionFunctions()
281 info('Create Partition Functions');
283 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
284 $this->pgsqlRunPartitionScript($sTemplate);
287 public function importWikipediaArticles()
289 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
290 if (file_exists($sWikiArticlesFile)) {
291 info('Importing wikipedia articles and redirects');
292 $this->dropTable('wikipedia_article');
293 $this->dropTable('wikipedia_redirect');
294 $this->pgsqlRunScriptFile($sWikiArticlesFile);
296 warn('wikipedia importance dump file not found - places will have default importance');
300 public function loadData($bDisableTokenPrecalc)
302 info('Drop old Data');
306 $oDB->exec('TRUNCATE word');
308 $oDB->exec('TRUNCATE placex');
310 $oDB->exec('TRUNCATE location_property_osmline');
312 $oDB->exec('TRUNCATE place_addressline');
314 $oDB->exec('TRUNCATE location_area');
316 if (!$this->dbReverseOnly()) {
317 $oDB->exec('TRUNCATE search_name');
320 $oDB->exec('TRUNCATE search_name_blank');
322 $oDB->exec('DROP SEQUENCE seq_place');
324 $oDB->exec('CREATE SEQUENCE seq_place start 100000');
327 $sSQL = 'select distinct partition from country_name';
328 $aPartitions = $oDB->getCol($sSQL);
330 if (!$this->bNoPartitions) $aPartitions[] = 0;
331 foreach ($aPartitions as $sPartition) {
332 $oDB->exec('TRUNCATE location_road_'.$sPartition);
336 // used by getorcreate_word_id to ignore frequent partial words
337 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
338 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
342 // pre-create the word list
343 if (!$bDisableTokenPrecalc) {
344 info('Loading word list');
345 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
349 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
351 $aDBInstances = array();
352 $iLoadThreads = max(1, $this->iInstances - 1);
353 for ($i = 0; $i < $iLoadThreads; $i++) {
354 // https://secure.php.net/manual/en/function.pg-connect.php
355 $DSN = CONST_Database_DSN;
356 $DSN = preg_replace('/^pgsql:/', '', $DSN);
357 $DSN = preg_replace('/;/', ' ', $DSN);
358 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
359 pg_ping($aDBInstances[$i]);
362 for ($i = 0; $i < $iLoadThreads; $i++) {
363 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
364 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
365 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
366 $sSQL .= ' and ST_IsValid(geometry)';
367 if ($this->bVerbose) echo "$sSQL\n";
368 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
369 fail(pg_last_error($aDBInstances[$i]));
373 // last thread for interpolation lines
374 // https://secure.php.net/manual/en/function.pg-connect.php
375 $DSN = CONST_Database_DSN;
376 $DSN = preg_replace('/^pgsql:/', '', $DSN);
377 $DSN = preg_replace('/;/', ' ', $DSN);
378 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
379 pg_ping($aDBInstances[$iLoadThreads]);
380 $sSQL = 'insert into location_property_osmline';
381 $sSQL .= ' (osm_id, address, linegeo)';
382 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
383 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
384 if ($this->bVerbose) echo "$sSQL\n";
385 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
386 fail(pg_last_error($aDBInstances[$iLoadThreads]));
390 for ($i = 0; $i <= $iLoadThreads; $i++) {
391 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
392 $resultStatus = pg_result_status($hPGresult);
393 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
394 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
395 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
396 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
397 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
398 $resultError = pg_result_error($hPGresult);
399 echo '-- error text ' . $i . ': ' . $resultError . "\n";
405 fail('SQL errors loading placex and/or location_property_osmline tables');
408 for ($i = 0; $i < $this->iInstances; $i++) {
409 pg_close($aDBInstances[$i]);
413 info('Reanalysing database');
414 $this->pgsqlRunScript('ANALYSE');
416 $sDatabaseDate = getDatabaseDate($oDB);
417 $oDB->exec('TRUNCATE import_status');
418 if (!$sDatabaseDate) {
419 warn('could not determine database date.');
421 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
423 echo "Latest data imported from $sDatabaseDate.\n";
427 public function importTigerData()
429 info('Import Tiger data');
431 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
432 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
433 if (empty($aFilenames)) {
434 warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
437 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
438 $sTemplate = $this->replaceSqlPatterns($sTemplate);
440 $this->pgsqlRunScript($sTemplate, false);
442 $aDBInstances = array();
443 for ($i = 0; $i < $this->iInstances; $i++) {
444 // https://secure.php.net/manual/en/function.pg-connect.php
445 $DSN = CONST_Database_DSN;
446 $DSN = preg_replace('/^pgsql:/', '', $DSN);
447 $DSN = preg_replace('/;/', ' ', $DSN);
448 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
449 pg_ping($aDBInstances[$i]);
452 foreach ($aFilenames as $sFile) {
454 $hFile = fopen($sFile, 'r');
455 $sSQL = fgets($hFile, 100000);
458 for ($i = 0; $i < $this->iInstances; $i++) {
459 if (!pg_connection_busy($aDBInstances[$i])) {
460 while (pg_get_result($aDBInstances[$i]));
461 $sSQL = fgets($hFile, 100000);
463 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
465 if ($iLines == 1000) {
478 for ($i = 0; $i < $this->iInstances; $i++) {
479 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
486 for ($i = 0; $i < $this->iInstances; $i++) {
487 pg_close($aDBInstances[$i]);
490 info('Creating indexes on Tiger data');
491 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
492 $sTemplate = $this->replaceSqlPatterns($sTemplate);
494 $this->pgsqlRunScript($sTemplate, false);
497 public function calculatePostcodes($bCMDResultAll)
499 info('Calculate Postcodes');
500 $this->db()->exec('TRUNCATE location_postcode');
502 $sSQL = 'INSERT INTO location_postcode';
503 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
504 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
505 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
506 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
507 $sSQL .= ' FROM placex';
508 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
509 $sSQL .= ' AND geometry IS NOT null';
510 $sSQL .= ' GROUP BY country_code, pc';
511 $this->db()->exec($sSQL);
513 // only add postcodes that are not yet available in OSM
514 $sSQL = 'INSERT INTO location_postcode';
515 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
516 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
517 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
518 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
519 $sSQL .= ' (SELECT postcode FROM location_postcode';
520 $sSQL .= " WHERE country_code = 'us')";
521 $this->db()->exec($sSQL);
523 // add missing postcodes for GB (if available)
524 $sSQL = 'INSERT INTO location_postcode';
525 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
526 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
527 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
528 $sSQL .= ' (SELECT postcode FROM location_postcode';
529 $sSQL .= " WHERE country_code = 'gb')";
530 $this->db()->exec($sSQL);
532 if (!$bCMDResultAll) {
533 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
534 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
535 $this->db()->exec($sSQL);
538 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
539 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
540 $this->db()->exec($sSQL);
543 public function index($bIndexNoanalyse)
545 checkModulePresence(); // raises exception on failure
547 $oBaseCmd = (new \Nominatim\Shell(CONST_BasePath.'/nominatim/nominatim.py'))
548 ->addParams('--database', $this->aDSNInfo['database'])
549 ->addParams('--port', $this->aDSNInfo['port'])
550 ->addParams('--threads', $this->iInstances);
552 if (!$this->bQuiet) {
553 $oBaseCmd->addParams('-v');
555 if ($this->bVerbose) {
556 $oBaseCmd->addParams('-v');
558 if (isset($this->aDSNInfo['hostspec'])) {
559 $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
561 if (isset($this->aDSNInfo['username'])) {
562 $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
564 if (isset($this->aDSNInfo['password'])) {
565 $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
568 info('Index ranks 0 - 4');
569 $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
570 echo $oCmd->escapedCmd();
572 $iStatus = $oCmd->run();
574 fail('error status ' . $iStatus . ' running nominatim!');
576 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
578 info('Index administrative boundaries');
579 $oCmd = (clone $oBaseCmd)->addParams('-b');
580 $iStatus = $oCmd->run();
582 fail('error status ' . $iStatus . ' running nominatim!');
585 info('Index ranks 5 - 25');
586 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
587 $iStatus = $oCmd->run();
589 fail('error status ' . $iStatus . ' running nominatim!');
592 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
594 info('Index ranks 26 - 30');
595 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
596 $iStatus = $oCmd->run();
598 fail('error status ' . $iStatus . ' running nominatim!');
601 info('Index postcodes');
602 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
603 $this->db()->exec($sSQL);
606 public function createSearchIndices()
608 info('Create Search indices');
610 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
611 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
612 $aInvalidIndices = $this->db()->getCol($sSQL);
614 foreach ($aInvalidIndices as $sIndexName) {
615 info("Cleaning up invalid index $sIndexName");
616 $this->db()->exec("DROP INDEX $sIndexName;");
619 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
621 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
623 if (!$this->dbReverseOnly()) {
624 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
626 $sTemplate = $this->replaceSqlPatterns($sTemplate);
628 $this->pgsqlRunScript($sTemplate);
631 public function createCountryNames()
633 info('Create search index for default country names');
635 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
636 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
637 $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');
638 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
639 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
640 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
641 if (CONST_Languages) {
644 foreach (explode(',', CONST_Languages) as $sLang) {
645 $sSQL .= $sDelim."'name:$sLang'";
650 // all include all simple name tags
651 $sSQL .= "like 'name:%'";
654 $this->pgsqlRunScript($sSQL);
657 public function drop()
659 info('Drop tables only required for updates');
661 // The implementation is potentially a bit dangerous because it uses
662 // a positive selection of tables to keep, and deletes everything else.
663 // Including any tables that the unsuspecting user might have manually
664 // created. USE AT YOUR OWN PERIL.
665 // tables we want to keep. everything else goes.
666 $aKeepTables = array(
672 'location_property*',
685 $aDropTables = array();
686 $aHaveTables = $this->db()->getListOfTables();
688 foreach ($aHaveTables as $sTable) {
690 foreach ($aKeepTables as $sKeep) {
691 if (fnmatch($sKeep, $sTable)) {
696 if (!$bFound) array_push($aDropTables, $sTable);
698 foreach ($aDropTables as $sDrop) {
699 $this->dropTable($sDrop);
702 $this->removeFlatnodeFile();
706 * Setup settings-frontend.php in the build/website directory
710 public function setupWebsite()
712 $rOutputFile = fopen(CONST_InstallPath.'/settings/settings-frontend.php', 'w');
714 fwrite($rOutputFile, "<?php
715 @define('CONST_BasePath', '".CONST_BasePath."');
716 if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
718 @define('CONST_Database_DSN', '".CONST_Database_DSN."');
719 @define('CONST_Default_Language', ".(CONST_Default_Language ? ("'".CONST_Default_Language."'") : 'false').");
720 @define('CONST_Log_DB', ".(CONST_Log_DB ? 'true' : 'false').");
721 @define('CONST_Log_File', ".(CONST_Log_File ? ("'".CONST_Log_File."'") : 'false').");
722 @define('CONST_Max_Word_Frequency', '".CONST_Max_Word_Frequency."');
723 @define('CONST_NoAccessControl', ".CONST_NoAccessControl.");
724 @define('CONST_Places_Max_ID_count', ".CONST_Places_Max_ID_count.");
725 @define('CONST_PolygonOutput_MaximumTypes', ".CONST_PolygonOutput_MaximumTypes.");
726 @define('CONST_Search_AreaPolygons', ".CONST_Search_AreaPolygons.");
727 @define('CONST_Search_BatchMode', ".(CONST_Search_BatchMode ? 'true' : 'false').");
728 @define('CONST_Search_NameOnlySearchFrequencyThreshold', ".CONST_Search_NameOnlySearchFrequencyThreshold.");
729 @define('CONST_Search_ReversePlanForAll', ".CONST_Search_ReversePlanForAll.");
730 @define('CONST_Term_Normalization_Rules', \"".CONST_Term_Normalization_Rules."\");
731 @define('CONST_Use_Aux_Location_data', ".(CONST_Use_Aux_Location_data ? 'true' : 'false').");
732 @define('CONST_Use_US_Tiger_Data', ".(CONST_Use_US_Tiger_Data ? 'true' : 'false').");
733 @define('CONST_MapIcon_URL', ".(CONST_MapIcon_URL ? ("'".CONST_MapIcon_URL."'") : 'false').');
735 info(CONST_InstallPath.'/settings/settings-frontend.php has been set up successfully');
739 * Return the connection to the database.
741 * @return Database object.
743 * Creates a new connection if none exists yet. Otherwise reuses the
744 * already established connection.
746 private function db()
748 if (is_null($this->oDB)) {
749 $this->oDB = new \Nominatim\DB();
750 $this->oDB->connect();
756 private function removeFlatnodeFile()
758 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
759 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
760 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
761 unlink(CONST_Osm2pgsql_Flatnode_File);
766 private function pgsqlRunScript($sScript, $bfatal = true)
776 private function createSqlFunctions()
778 $sBasePath = CONST_BasePath.'/sql/functions/';
779 $sTemplate = file_get_contents($sBasePath.'utils.sql');
780 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
781 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
782 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
783 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
784 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
785 if ($this->db()->tableExists('place')) {
786 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
788 if ($this->db()->tableExists('placex')) {
789 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
791 if ($this->db()->tableExists('location_postcode')) {
792 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
794 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
795 if ($this->bEnableDiffUpdates) {
796 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
798 if ($this->bEnableDebugStatements) {
799 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
801 if (CONST_Limit_Reindexing) {
802 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
804 if (!CONST_Use_US_Tiger_Data) {
805 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
807 if (!CONST_Use_Aux_Location_data) {
808 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
811 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
812 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
814 $this->pgsqlRunScript($sTemplate);
817 private function pgsqlRunPartitionScript($sTemplate)
819 $sSQL = 'select distinct partition from country_name';
820 $aPartitions = $this->db()->getCol($sSQL);
821 if (!$this->bNoPartitions) $aPartitions[] = 0;
823 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
824 foreach ($aMatches as $aMatch) {
826 foreach ($aPartitions as $sPartitionName) {
827 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
829 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
832 $this->pgsqlRunScript($sTemplate);
835 private function pgsqlRunScriptFile($sFilename)
837 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
839 $oCmd = (new \Nominatim\Shell('psql'))
840 ->addParams('--port', $this->aDSNInfo['port'])
841 ->addParams('--dbname', $this->aDSNInfo['database']);
843 if (!$this->bVerbose) {
844 $oCmd->addParams('--quiet');
846 if (isset($this->aDSNInfo['hostspec'])) {
847 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
849 if (isset($this->aDSNInfo['username'])) {
850 $oCmd->addParams('--username', $this->aDSNInfo['username']);
852 if (isset($this->aDSNInfo['password'])) {
853 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
856 if (preg_match('/\\.gz$/', $sFilename)) {
857 $aDescriptors = array(
858 0 => array('pipe', 'r'),
859 1 => array('pipe', 'w'),
860 2 => array('file', '/dev/null', 'a')
862 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
864 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
865 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
866 $aReadPipe = $ahGzipPipes[1];
867 fclose($ahGzipPipes[0]);
869 $oCmd->addParams('--file', $sFilename);
870 $aReadPipe = array('pipe', 'r');
872 $aDescriptors = array(
874 1 => array('pipe', 'w'),
875 2 => array('file', '/dev/null', 'a')
879 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
880 if (!is_resource($hProcess)) fail('unable to start pgsql');
881 // TODO: error checking
882 while (!feof($ahPipes[1])) {
883 echo fread($ahPipes[1], 4096);
886 $iReturn = proc_close($hProcess);
888 fail("pgsql returned with error code ($iReturn)");
891 fclose($ahGzipPipes[1]);
892 proc_close($hGzipProcess);
896 private function replaceSqlPatterns($sSql)
898 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
901 '{ts:address-data}' => CONST_Tablespace_Address_Data,
902 '{ts:address-index}' => CONST_Tablespace_Address_Index,
903 '{ts:search-data}' => CONST_Tablespace_Search_Data,
904 '{ts:search-index}' => CONST_Tablespace_Search_Index,
905 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
906 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
909 foreach ($aPatterns as $sPattern => $sTablespace) {
911 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
913 $sSql = str_replace($sPattern, '', $sSql);
921 * Drop table with the given name if it exists.
923 * @param string $sName Name of table to remove.
927 private function dropTable($sName)
929 if ($this->bVerbose) echo "Dropping table $sName\n";
930 $this->db()->deleteTable($sName);
934 * Check if the database is in reverse-only mode.
936 * @return True if there is no search_name table and infrastructure.
938 private function dbReverseOnly()
940 return !($this->db()->tableExists('search_name'));