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 connect()
113 $this->oDB = new \Nominatim\DB();
114 $this->oDB->connect();
117 public function setupDB()
121 $fPostgresVersion = $this->oDB->getPostgresVersion();
122 echo 'Postgres version found: '.$fPostgresVersion."\n";
124 if ($fPostgresVersion < 9.03) {
125 fail('Minimum supported version of Postgresql is 9.3.');
128 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
129 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
131 $fPostgisVersion = $this->oDB->getPostgisVersion();
132 echo 'Postgis version found: '.$fPostgisVersion."\n";
134 if ($fPostgisVersion < 2.2) {
135 echo "Minimum required Postgis version 2.2\n";
139 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
141 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
142 echo "\n createuser ".CONST_Database_Web_User."\n\n";
146 // Try accessing the C module, so we know early if something is wrong
147 checkModulePresence(); // raises exception on failure
149 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
150 echo 'Error: you need to download the country_osm_grid first:';
151 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
154 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
155 $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
156 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
157 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
159 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
160 if (file_exists($sPostcodeFilename)) {
161 $this->pgsqlRunScriptFile($sPostcodeFilename);
163 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
166 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
167 if (file_exists($sPostcodeFilename)) {
168 $this->pgsqlRunScriptFile($sPostcodeFilename);
170 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
173 if ($this->bNoPartitions) {
174 $this->pgsqlRunScript('update country_name set partition = 0');
178 public function importData($sOSMFile)
182 if (!file_exists(CONST_Osm2pgsql_Binary)) {
183 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
184 echo "Normally you should not need to set this manually.\n";
185 fail("osm2pgsql not found in '".CONST_Osm2pgsql_Binary."'");
188 $oCmd = new \Nominatim\Shell(CONST_Osm2pgsql_Binary);
189 $oCmd->addParams('--style', CONST_Import_Style);
191 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192 $oCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
194 if (CONST_Tablespace_Osm2pgsql_Data) {
195 $oCmd->addParams('--tablespace-slim-data', CONST_Tablespace_Osm2pgsql_Data);
197 if (CONST_Tablespace_Osm2pgsql_Index) {
198 $oCmd->addParams('--tablespace-slim-index', CONST_Tablespace_Osm2pgsql_Index);
200 if (CONST_Tablespace_Place_Data) {
201 $oCmd->addParams('--tablespace-main-data', CONST_Tablespace_Place_Data);
203 if (CONST_Tablespace_Place_Index) {
204 $oCmd->addParams('--tablespace-main-index', CONST_Tablespace_Place_Index);
206 $oCmd->addParams('--latlong', '--slim', '--create');
207 $oCmd->addParams('--output', 'gazetteer');
208 $oCmd->addParams('--hstore');
209 $oCmd->addParams('--number-processes', 1);
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->oDB->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 checkModulePresence(); // raises exception on failure
243 $this->createSqlFunctions();
246 public function createTables($bReverseOnly = false)
248 info('Create Tables');
250 $sTemplate = file_get_contents(CONST_BasePath.'/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->oDB, 'address_levels');
263 public function createTableTriggers()
265 info('Create Tables');
267 $sTemplate = file_get_contents(CONST_BasePath.'/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_BasePath.'/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_BasePath.'/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');
308 $this->oDB->exec('TRUNCATE word');
310 $this->oDB->exec('TRUNCATE placex');
312 $this->oDB->exec('TRUNCATE location_property_osmline');
314 $this->oDB->exec('TRUNCATE place_addressline');
316 $this->oDB->exec('TRUNCATE location_area');
318 if (!$this->dbReverseOnly()) {
319 $this->oDB->exec('TRUNCATE search_name');
322 $this->oDB->exec('TRUNCATE search_name_blank');
324 $this->oDB->exec('DROP SEQUENCE seq_place');
326 $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
329 $sSQL = 'select distinct partition from country_name';
330 $aPartitions = $this->oDB->getCol($sSQL);
332 if (!$this->bNoPartitions) $aPartitions[] = 0;
333 foreach ($aPartitions as $sPartition) {
334 $this->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 '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
341 $this->oDB->exec($sSQL);
344 // pre-create the word list
345 if (!$bDisableTokenPrecalc) {
346 info('Loading word list');
347 $this->pgsqlRunScriptFile(CONST_BasePath.'/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 = CONST_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 = CONST_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($this->oDB);
419 $this->oDB->exec('TRUNCATE import_status');
420 if (!$sDatabaseDate) {
421 warn('could not determine database date.');
423 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
424 $this->oDB->exec($sSQL);
425 echo "Latest data imported from $sDatabaseDate.\n";
429 public function importTigerData()
431 info('Import Tiger data');
433 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
434 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
435 if (empty($aFilenames)) {
436 warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
439 $sTemplate = file_get_contents(CONST_BasePath.'/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 = CONST_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_BasePath.'/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->oDB->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->oDB->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->oDB->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->oDB->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->oDB->exec($sSQL);
540 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
541 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
542 $this->oDB->exec($sSQL);
545 public function index($bIndexNoanalyse)
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 ranks 5 - 25');
579 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
580 $iStatus = $oCmd->run();
582 fail('error status ' . $iStatus . ' running nominatim!');
584 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
586 info('Index ranks 26 - 30');
587 $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
588 $iStatus = $oCmd->run();
590 fail('error status ' . $iStatus . ' running nominatim!');
593 info('Index postcodes');
594 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
595 $this->oDB->exec($sSQL);
598 public function createSearchIndices()
600 info('Create Search indices');
602 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
603 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
604 $aInvalidIndices = $this->oDB->getCol($sSQL);
606 foreach ($aInvalidIndices as $sIndexName) {
607 info("Cleaning up invalid index $sIndexName");
608 $this->oDB->exec("DROP INDEX $sIndexName;");
611 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
613 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
615 if (!$this->dbReverseOnly()) {
616 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
618 $sTemplate = $this->replaceSqlPatterns($sTemplate);
620 $this->pgsqlRunScript($sTemplate);
623 public function createCountryNames()
625 info('Create search index for default country names');
627 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
628 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
629 $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');
630 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
631 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
632 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
633 if (CONST_Languages) {
636 foreach (explode(',', CONST_Languages) as $sLang) {
637 $sSQL .= $sDelim."'name:$sLang'";
642 // all include all simple name tags
643 $sSQL .= "like 'name:%'";
646 $this->pgsqlRunScript($sSQL);
649 public function drop()
651 info('Drop tables only required for updates');
653 // The implementation is potentially a bit dangerous because it uses
654 // a positive selection of tables to keep, and deletes everything else.
655 // Including any tables that the unsuspecting user might have manually
656 // created. USE AT YOUR OWN PERIL.
657 // tables we want to keep. everything else goes.
658 $aKeepTables = array(
664 'location_property*',
677 $aDropTables = array();
678 $aHaveTables = $this->oDB->getListOfTables();
680 foreach ($aHaveTables as $sTable) {
682 foreach ($aKeepTables as $sKeep) {
683 if (fnmatch($sKeep, $sTable)) {
688 if (!$bFound) array_push($aDropTables, $sTable);
690 foreach ($aDropTables as $sDrop) {
691 $this->dropTable($sDrop);
694 $this->removeFlatnodeFile();
698 * Setup settings-frontend.php in the build/website directory
702 public function setupWebsite()
704 $rOutputFile = fopen(CONST_InstallPath.'/settings/settings-frontend.php', 'w');
706 fwrite($rOutputFile, "<?php
707 @define('CONST_BasePath', '".CONST_BasePath."');
708 if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
710 @define('CONST_Database_DSN', '".CONST_Database_DSN."'); // or add ;host=...;port=...;user=...;password=...
711 @define('CONST_Default_Language', ".(CONST_Default_Language ? ("'".CONST_Default_Language."'") : 'false').");
712 @define('CONST_Default_Lat', ".CONST_Default_Lat.");
713 @define('CONST_Default_Lon', ".CONST_Default_Lon.");
714 @define('CONST_Default_Zoom', ".CONST_Default_Zoom.");
715 @define('CONST_Map_Tile_URL', '".CONST_Map_Tile_URL."');
716 @define('CONST_Map_Tile_Attribution', '".CONST_Map_Tile_Attribution."'); // Set if tile source isn't osm.org
717 @define('CONST_Log_DB', ".(CONST_Log_DB ? 'true' : 'false').");
718 @define('CONST_Log_File', ".(CONST_Log_File ? ("'".CONST_Log_File."'") : 'false').");
719 @define('CONST_Max_Word_Frequency', '".CONST_Max_Word_Frequency."');
720 @define('CONST_NoAccessControl', ".CONST_NoAccessControl.");
721 @define('CONST_Places_Max_ID_count', ".CONST_Places_Max_ID_count.");
722 @define('CONST_PolygonOutput_MaximumTypes', ".CONST_PolygonOutput_MaximumTypes.");
723 @define('CONST_Search_AreaPolygons', ".CONST_Search_AreaPolygons.");
724 @define('CONST_Search_BatchMode', ".(CONST_Search_BatchMode ? 'true' : 'false').");
725 @define('CONST_Search_NameOnlySearchFrequencyThreshold', ".CONST_Search_NameOnlySearchFrequencyThreshold.");
726 @define('CONST_Search_ReversePlanForAll', ".CONST_Search_ReversePlanForAll.");
727 @define('CONST_Term_Normalization_Rules', \"".CONST_Term_Normalization_Rules."\");
728 @define('CONST_Use_Aux_Location_data', ".(CONST_Use_Aux_Location_data ? 'true' : 'false').");
729 @define('CONST_Use_US_Tiger_Data', ".(CONST_Use_US_Tiger_Data ? 'true' : 'false').");
730 @define('CONST_Website_BaseURL', '".CONST_Website_BaseURL."');
732 info(CONST_InstallPath.'/website/settings-frontend.php has been set up successfully');
735 private function removeFlatnodeFile()
737 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
738 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
739 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
740 unlink(CONST_Osm2pgsql_Flatnode_File);
745 private function pgsqlRunScript($sScript, $bfatal = true)
755 private function createSqlFunctions()
757 $sBasePath = CONST_BasePath.'/sql/functions/';
758 $sTemplate = file_get_contents($sBasePath.'utils.sql');
759 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
760 $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
761 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
762 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
763 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
764 if ($this->oDB->tableExists('place')) {
765 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
767 if ($this->oDB->tableExists('placex')) {
768 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
770 if ($this->oDB->tableExists('location_postcode')) {
771 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
773 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
774 if ($this->bEnableDiffUpdates) {
775 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
777 if ($this->bEnableDebugStatements) {
778 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
780 if (CONST_Limit_Reindexing) {
781 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
783 if (!CONST_Use_US_Tiger_Data) {
784 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
786 if (!CONST_Use_Aux_Location_data) {
787 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
790 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
791 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
793 $this->pgsqlRunScript($sTemplate);
796 private function pgsqlRunPartitionScript($sTemplate)
798 $sSQL = 'select distinct partition from country_name';
799 $aPartitions = $this->oDB->getCol($sSQL);
800 if (!$this->bNoPartitions) $aPartitions[] = 0;
802 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
803 foreach ($aMatches as $aMatch) {
805 foreach ($aPartitions as $sPartitionName) {
806 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
808 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
811 $this->pgsqlRunScript($sTemplate);
814 private function pgsqlRunScriptFile($sFilename)
816 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
818 $oCmd = (new \Nominatim\Shell('psql'))
819 ->addParams('--port', $this->aDSNInfo['port'])
820 ->addParams('--dbname', $this->aDSNInfo['database']);
822 if (!$this->bVerbose) {
823 $oCmd->addParams('--quiet');
825 if (isset($this->aDSNInfo['hostspec'])) {
826 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
828 if (isset($this->aDSNInfo['username'])) {
829 $oCmd->addParams('--username', $this->aDSNInfo['username']);
831 if (isset($this->aDSNInfo['password'])) {
832 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
835 if (preg_match('/\\.gz$/', $sFilename)) {
836 $aDescriptors = array(
837 0 => array('pipe', 'r'),
838 1 => array('pipe', 'w'),
839 2 => array('file', '/dev/null', 'a')
841 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
843 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
844 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
845 $aReadPipe = $ahGzipPipes[1];
846 fclose($ahGzipPipes[0]);
848 $oCmd->addParams('--file', $sFilename);
849 $aReadPipe = array('pipe', 'r');
851 $aDescriptors = array(
853 1 => array('pipe', 'w'),
854 2 => array('file', '/dev/null', 'a')
858 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
859 if (!is_resource($hProcess)) fail('unable to start pgsql');
860 // TODO: error checking
861 while (!feof($ahPipes[1])) {
862 echo fread($ahPipes[1], 4096);
865 $iReturn = proc_close($hProcess);
867 fail("pgsql returned with error code ($iReturn)");
870 fclose($ahGzipPipes[1]);
871 proc_close($hGzipProcess);
875 private function replaceSqlPatterns($sSql)
877 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
880 '{ts:address-data}' => CONST_Tablespace_Address_Data,
881 '{ts:address-index}' => CONST_Tablespace_Address_Index,
882 '{ts:search-data}' => CONST_Tablespace_Search_Data,
883 '{ts:search-index}' => CONST_Tablespace_Search_Index,
884 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
885 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
888 foreach ($aPatterns as $sPattern => $sTablespace) {
890 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
892 $sSql = str_replace($sPattern, '', $sSql);
900 * Drop table with the given name if it exists.
902 * @param string $sName Name of table to remove.
906 * @pre connect() must have been called.
908 private function dropTable($sName)
910 if ($this->bVerbose) echo "Dropping table $sName\n";
911 $this->oDB->deleteTable($sName);
915 * Check if the database is in reverse-only mode.
917 * @return True if there is no search_name table and infrastructure.
919 private function dbReverseOnly()
921 return !($this->oDB->tableExists('search_name'));