3 namespace Nominatim\Setup;
5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
9 protected $iCacheMemory;
10 protected $iInstances;
11 protected $sModulePath;
14 protected $sIgnoreErrors;
15 protected $bEnableDiffUpdates;
16 protected $bEnableDebugStatements;
17 protected $bNoPartitions;
18 protected $oDB = null;
20 public function __construct(array $aCMDResult)
22 // by default, use all but one processor, but never more than 15.
23 $this->iInstances = isset($aCMDResult['threads'])
24 ? $aCMDResult['threads']
25 : (min(16, getProcessorCount()) - 1);
27 if ($this->iInstances < 1) {
28 $this->iInstances = 1;
29 warn('resetting threads to '.$this->iInstances);
32 // Assume we can steal all the cache memory in the box (unless told otherwise)
33 if (isset($aCMDResult['osm2pgsql-cache'])) {
34 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
36 $this->iCacheMemory = getCacheMemoryMB();
39 $this->sModulePath = CONST_Database_Module_Path;
40 info('module path: ' . $this->sModulePath);
42 // parse database string
43 $this->aDSNInfo = array_filter(\DB::parseDSN(CONST_Database_DSN));
44 if (!isset($this->aDSNInfo['port'])) {
45 $this->aDSNInfo['port'] = 5432;
48 // setting member variables based on command line options stored in $aCMDResult
49 $this->sVerbose = $aCMDResult['verbose'];
51 //setting default values which are not set by the update.php array
52 if (isset($aCMDResult['ignore-errors'])) {
53 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
55 $this->sIgnoreErrors = false;
57 if (isset($aCMDResult['enable-debug-statements'])) {
58 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
60 $this->bEnableDebugStatements = false;
62 if (isset($aCMDResult['no-partitions'])) {
63 $this->bNoPartitions = $aCMDResult['no-partitions'];
65 $this->bNoPartitions = false;
67 if (isset($aCMDResult['enable-diff-updates'])) {
68 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
70 $this->bEnableDiffUpdates = false;
74 public function createDB()
77 $sDB = \DB::connect(CONST_Database_DSN, false);
78 if (!\PEAR::isError($sDB)) {
79 fail('database already exists ('.CONST_Database_DSN.')');
82 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
83 if (isset($this->aDSNInfo['username'])) {
84 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
87 if (isset($this->aDSNInfo['hostspec'])) {
88 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
91 $result = $this->runWithPgEnv($sCreateDBCmd);
92 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
95 public function connect()
97 $this->oDB =& getDB();
100 public function setupDB()
104 $fPostgresVersion = getPostgresVersion($this->oDB);
105 echo 'Postgres version found: '.$fPostgresVersion."\n";
107 if ($fPostgresVersion < 9.01) {
108 fail('Minimum supported version of Postgresql is 9.1.');
111 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
112 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
114 // For extratags and namedetails the hstore_to_json converter is
115 // needed which is only available from Postgresql 9.3+. For older
116 // versions add a dummy function that returns nothing.
117 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
119 if ($iNumFunc == 0) {
120 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
121 warn('Postgresql is too old. extratags and namedetails API not available.');
125 $fPostgisVersion = getPostgisVersion($this->oDB);
126 echo 'Postgis version found: '.$fPostgisVersion."\n";
128 if ($fPostgisVersion < 2.1) {
129 // Functions were renamed in 2.1 and throw an annoying deprecation warning
130 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
131 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
133 if ($fPostgisVersion < 2.2) {
134 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
137 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
139 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
140 echo "\n createuser ".CONST_Database_Web_User."\n\n";
144 // Try accessing the C module, so we know early if something is wrong
145 if (!checkModulePresence()) {
146 fail('error loading nominatim.so module');
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_BasePath.'/data/country_osm_grid.sql.gz');
156 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
158 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
159 if (file_exists($sPostcodeFilename)) {
160 $this->pgsqlRunScriptFile($sPostcodeFilename);
162 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
165 if (CONST_Use_Extra_US_Postcodes) {
166 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
169 if ($this->bNoPartitions) {
170 $this->pgsqlRunScript('update country_name set partition = 0');
173 // the following will be needed by createFunctions later but
174 // is only defined in the subsequently called createTables
175 // Create dummies here that will be overwritten by the proper
176 // versions in create-tables.
177 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
178 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
181 public function importData($sOSMFile)
185 $osm2pgsql = CONST_Osm2pgsql_Binary;
186 if (!file_exists($osm2pgsql)) {
187 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
188 echo "Normally you should not need to set this manually.\n";
189 fail("osm2pgsql not found in '$osm2pgsql'");
192 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
193 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
196 if (CONST_Tablespace_Osm2pgsql_Data)
197 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
198 if (CONST_Tablespace_Osm2pgsql_Index)
199 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
200 if (CONST_Tablespace_Place_Data)
201 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
202 if (CONST_Tablespace_Place_Index)
203 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
204 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
205 $osm2pgsql .= ' -C '.$this->iCacheMemory;
206 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
207 if (isset($this->aDSNInfo['username'])) {
208 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
210 if (isset($this->aDSNInfo['hostspec'])) {
211 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
213 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
215 $this->runWithPgEnv($osm2pgsql);
217 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
222 public function createFunctions()
224 info('Create Functions');
226 // Try accessing the C module, so we know eif something is wrong
227 // update.php calls this function
228 if (!checkModulePresence()) {
229 fail('error loading nominatim.so module');
231 $this->createSqlFunctions();
234 public function createTables($bReverseOnly = false)
236 info('Create Tables');
238 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
239 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
240 $sTemplate = $this->replaceTablespace(
242 CONST_Tablespace_Address_Data,
245 $sTemplate = $this->replaceTablespace(
246 '{ts:address-index}',
247 CONST_Tablespace_Address_Index,
250 $sTemplate = $this->replaceTablespace(
252 CONST_Tablespace_Search_Data,
255 $sTemplate = $this->replaceTablespace(
257 CONST_Tablespace_Search_Index,
260 $sTemplate = $this->replaceTablespace(
262 CONST_Tablespace_Aux_Data,
265 $sTemplate = $this->replaceTablespace(
267 CONST_Tablespace_Aux_Index,
271 $this->pgsqlRunScript($sTemplate, false);
274 $this->pgExec('DROP TABLE search_name');
277 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
278 $oAlParser->createTable($this->oDB, 'address_levels');
281 public function createPartitionTables()
283 info('Create Partition Tables');
285 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
286 $sTemplate = $this->replaceTablespace(
288 CONST_Tablespace_Address_Data,
292 $sTemplate = $this->replaceTablespace(
293 '{ts:address-index}',
294 CONST_Tablespace_Address_Index,
298 $sTemplate = $this->replaceTablespace(
300 CONST_Tablespace_Search_Data,
304 $sTemplate = $this->replaceTablespace(
306 CONST_Tablespace_Search_Index,
310 $sTemplate = $this->replaceTablespace(
312 CONST_Tablespace_Aux_Data,
316 $sTemplate = $this->replaceTablespace(
318 CONST_Tablespace_Aux_Index,
322 $this->pgsqlRunPartitionScript($sTemplate);
325 public function createPartitionFunctions()
327 info('Create Partition Functions');
329 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
330 $this->pgsqlRunPartitionScript($sTemplate);
333 public function importWikipediaArticles()
335 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
336 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
337 if (file_exists($sWikiArticlesFile)) {
338 info('Importing wikipedia articles');
339 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
341 warn('wikipedia article dump file not found - places will have default importance');
343 if (file_exists($sWikiRedirectsFile)) {
344 info('Importing wikipedia redirects');
345 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
347 warn('wikipedia redirect dump file not found - some place importance values may be missing');
351 public function loadData($bDisableTokenPrecalc)
353 info('Drop old Data');
355 $this->pgExec('TRUNCATE word');
357 $this->pgExec('TRUNCATE placex');
359 $this->pgExec('TRUNCATE location_property_osmline');
361 $this->pgExec('TRUNCATE place_addressline');
363 $this->pgExec('TRUNCATE place_boundingbox');
365 $this->pgExec('TRUNCATE location_area');
367 if (!$this->dbReverseOnly()) {
368 $this->pgExec('TRUNCATE search_name');
371 $this->pgExec('TRUNCATE search_name_blank');
373 $this->pgExec('DROP SEQUENCE seq_place');
375 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
378 $sSQL = 'select distinct partition from country_name';
379 $aPartitions = chksql($this->oDB->getCol($sSQL));
380 if (!$this->bNoPartitions) $aPartitions[] = 0;
381 foreach ($aPartitions as $sPartition) {
382 $this->pgExec('TRUNCATE location_road_'.$sPartition);
386 // used by getorcreate_word_id to ignore frequent partial words
387 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
388 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
389 $this->pgExec($sSQL);
392 // pre-create the word list
393 if (!$bDisableTokenPrecalc) {
394 info('Loading word list');
395 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
399 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
400 $aDBInstances = array();
401 $iLoadThreads = max(1, $this->iInstances - 1);
402 for ($i = 0; $i < $iLoadThreads; $i++) {
403 $aDBInstances[$i] =& getDB(true);
404 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
405 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
406 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
407 $sSQL .= ' and ST_IsValid(geometry)';
408 if ($this->sVerbose) echo "$sSQL\n";
409 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
410 fail(pg_last_error($aDBInstances[$i]->connection));
414 // last thread for interpolation lines
415 $aDBInstances[$iLoadThreads] =& getDB(true);
416 $sSQL = 'insert into location_property_osmline';
417 $sSQL .= ' (osm_id, address, linegeo)';
418 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
419 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
420 if ($this->sVerbose) echo "$sSQL\n";
421 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
422 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
426 for ($i = 0; $i <= $iLoadThreads; $i++) {
427 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
428 $resultStatus = pg_result_status($hPGresult);
429 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
430 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
431 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
432 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
433 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
434 $resultError = pg_result_error($hPGresult);
435 echo '-- error text ' . $i . ': ' . $resultError . "\n";
441 fail('SQL errors loading placex and/or location_property_osmline tables');
444 info('Reanalysing database');
445 $this->pgsqlRunScript('ANALYSE');
447 $sDatabaseDate = getDatabaseDate($this->oDB);
448 pg_query($this->oDB->connection, 'TRUNCATE import_status');
449 if ($sDatabaseDate === false) {
450 warn('could not determine database date.');
452 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
453 pg_query($this->oDB->connection, $sSQL);
454 echo "Latest data imported from $sDatabaseDate.\n";
458 public function importTigerData()
460 info('Import Tiger data');
462 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
463 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
464 $sTemplate = $this->replaceTablespace(
466 CONST_Tablespace_Aux_Data,
469 $sTemplate = $this->replaceTablespace(
471 CONST_Tablespace_Aux_Index,
474 $this->pgsqlRunScript($sTemplate, false);
476 $aDBInstances = array();
477 for ($i = 0; $i < $this->iInstances; $i++) {
478 $aDBInstances[$i] =& getDB(true);
481 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
483 $hFile = fopen($sFile, 'r');
484 $sSQL = fgets($hFile, 100000);
487 for ($i = 0; $i < $this->iInstances; $i++) {
488 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
489 while (pg_get_result($aDBInstances[$i]->connection));
490 $sSQL = fgets($hFile, 100000);
492 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
494 if ($iLines == 1000) {
507 for ($i = 0; $i < $this->iInstances; $i++) {
508 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
515 info('Creating indexes on Tiger data');
516 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
517 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
518 $sTemplate = $this->replaceTablespace(
520 CONST_Tablespace_Aux_Data,
523 $sTemplate = $this->replaceTablespace(
525 CONST_Tablespace_Aux_Index,
528 $this->pgsqlRunScript($sTemplate, false);
531 public function calculatePostcodes($bCMDResultAll)
533 info('Calculate Postcodes');
534 $this->pgExec('TRUNCATE location_postcode');
536 $sSQL = 'INSERT INTO location_postcode';
537 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
538 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
539 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
540 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
541 $sSQL .= ' FROM placex';
542 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
543 $sSQL .= ' AND geometry IS NOT null';
544 $sSQL .= ' GROUP BY country_code, pc';
545 $this->pgExec($sSQL);
547 if (CONST_Use_Extra_US_Postcodes) {
548 // only add postcodes that are not yet available in OSM
549 $sSQL = 'INSERT INTO location_postcode';
550 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
551 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
552 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
553 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
554 $sSQL .= ' (SELECT postcode FROM location_postcode';
555 $sSQL .= " WHERE country_code = 'us')";
556 $this->pgExec($sSQL);
559 // add missing postcodes for GB (if available)
560 $sSQL = 'INSERT INTO location_postcode';
561 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
562 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
563 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
564 $sSQL .= ' (SELECT postcode FROM location_postcode';
565 $sSQL .= " WHERE country_code = 'gb')";
566 $this->pgExec($sSQL);
568 if (!$bCMDResultAll) {
569 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
570 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
571 $this->pgExec($sSQL);
574 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
575 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
576 $this->pgExec($sSQL);
579 public function index($bIndexNoanalyse)
582 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
583 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
584 if (isset($this->aDSNInfo['hostspec'])) {
585 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
587 if (isset($this->aDSNInfo['username'])) {
588 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
591 info('Index ranks 0 - 4');
592 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
594 fail('error status ' . $iStatus . ' running nominatim!');
596 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
598 info('Index ranks 5 - 25');
599 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
601 fail('error status ' . $iStatus . ' running nominatim!');
603 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
605 info('Index ranks 26 - 30');
606 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
608 fail('error status ' . $iStatus . ' running nominatim!');
611 info('Index postcodes');
612 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
613 $this->pgExec($sSQL);
616 public function createSearchIndices()
618 info('Create Search indices');
620 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
621 if (!$this->dbReverseOnly()) {
622 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
624 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
625 $sTemplate = $this->replaceTablespace(
626 '{ts:address-index}',
627 CONST_Tablespace_Address_Index,
630 $sTemplate = $this->replaceTablespace(
632 CONST_Tablespace_Search_Index,
635 $sTemplate = $this->replaceTablespace(
637 CONST_Tablespace_Aux_Index,
640 $this->pgsqlRunScript($sTemplate);
643 public function createCountryNames()
645 info('Create search index for default country names');
647 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
648 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
649 $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');
650 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
651 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
652 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
653 if (CONST_Languages) {
656 foreach (explode(',', CONST_Languages) as $sLang) {
657 $sSQL .= $sDelim."'name:$sLang'";
662 // all include all simple name tags
663 $sSQL .= "like 'name:%'";
666 $this->pgsqlRunScript($sSQL);
669 public function drop()
671 info('Drop tables only required for updates');
673 // The implementation is potentially a bit dangerous because it uses
674 // a positive selection of tables to keep, and deletes everything else.
675 // Including any tables that the unsuspecting user might have manually
676 // created. USE AT YOUR OWN PERIL.
677 // tables we want to keep. everything else goes.
678 $aKeepTables = array(
684 'location_property*',
696 $aDropTables = array();
697 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
699 foreach ($aHaveTables as $sTable) {
701 foreach ($aKeepTables as $sKeep) {
702 if (fnmatch($sKeep, $sTable)) {
707 if (!$bFound) array_push($aDropTables, $sTable);
709 foreach ($aDropTables as $sDrop) {
710 if ($this->sVerbose) echo "Dropping table $sDrop\n";
711 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
712 // ignore warnings/errors as they might be caused by a table having
713 // been deleted already by CASCADE
716 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
717 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
718 if ($this->sVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
719 unlink(CONST_Osm2pgsql_Flatnode_File);
724 private function pgsqlRunDropAndRestore($sDumpFile)
726 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
727 if (isset($this->aDSNInfo['hostspec'])) {
728 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
730 if (isset($this->aDSNInfo['username'])) {
731 $sCMD .= ' -U '.$this->aDSNInfo['username'];
734 $this->runWithPgEnv($sCMD);
737 private function pgsqlRunScript($sScript, $bfatal = true)
747 private function createSqlFunctions()
749 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
750 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
751 if ($this->bEnableDiffUpdates) {
752 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
754 if ($this->bEnableDebugStatements) {
755 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
757 if (CONST_Limit_Reindexing) {
758 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
760 if (!CONST_Use_US_Tiger_Data) {
761 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
763 if (!CONST_Use_Aux_Location_data) {
764 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
767 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
768 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
770 $this->pgsqlRunScript($sTemplate);
773 private function pgsqlRunPartitionScript($sTemplate)
775 $sSQL = 'select distinct partition from country_name';
776 $aPartitions = chksql($this->oDB->getCol($sSQL));
777 if (!$this->bNoPartitions) $aPartitions[] = 0;
779 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
780 foreach ($aMatches as $aMatch) {
782 foreach ($aPartitions as $sPartitionName) {
783 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
785 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
788 $this->pgsqlRunScript($sTemplate);
791 private function pgsqlRunScriptFile($sFilename)
793 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
795 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
796 if (!$this->sVerbose) {
799 if (isset($this->aDSNInfo['hostspec'])) {
800 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
802 if (isset($this->aDSNInfo['username'])) {
803 $sCMD .= ' -U '.$this->aDSNInfo['username'];
806 if (isset($this->aDSNInfo['password'])) {
807 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
810 if (preg_match('/\\.gz$/', $sFilename)) {
811 $aDescriptors = array(
812 0 => array('pipe', 'r'),
813 1 => array('pipe', 'w'),
814 2 => array('file', '/dev/null', 'a')
816 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
817 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
818 $aReadPipe = $ahGzipPipes[1];
819 fclose($ahGzipPipes[0]);
821 $sCMD .= ' -f '.$sFilename;
822 $aReadPipe = array('pipe', 'r');
824 $aDescriptors = array(
826 1 => array('pipe', 'w'),
827 2 => array('file', '/dev/null', 'a')
830 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
831 if (!is_resource($hProcess)) fail('unable to start pgsql');
832 // TODO: error checking
833 while (!feof($ahPipes[1])) {
834 echo fread($ahPipes[1], 4096);
837 $iReturn = proc_close($hProcess);
839 fail("pgsql returned with error code ($iReturn)");
842 fclose($ahGzipPipes[1]);
843 proc_close($hGzipProcess);
847 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
850 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
852 $sSql = str_replace($sTemplate, '', $sSql);
857 private function runWithPgEnv($sCmd)
861 if (isset($this->aDSNInfo['password'])) {
862 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
865 return runWithEnv($sCmd, $aProcEnv);
869 * Execute the SQL command on the open database.
871 * @param string $sSQL SQL command to execute.
875 * @pre connect() must have been called.
877 private function pgExec($sSQL)
879 if (!pg_query($this->oDB->connection, $sSQL)) {
880 fail(pg_last_error($this->oDB->connection));
885 * Check if the database is in reverse-only mode.
887 * @return True if there is no search_name table and infrastructure.
889 private function dbReverseOnly()
891 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = 'search_name'";
892 return !(chksql($this->oDB->getOne($sSQL)));