3 namespace Nominatim\Setup;
7 protected $iCacheMemory;
9 protected $sModulePath;
12 protected $sIgnoreErrors;
13 protected $bEnableDiffUpdates;
14 protected $bEnableDebugStatements;
15 protected $bNoPartitions;
16 protected $oDB = null;
18 public function __construct(array $aCMDResult)
20 // by default, use all but one processor, but never more than 15.
21 $this->iInstances = isset($aCMDResult['threads'])
22 ? $aCMDResult['threads']
23 : (min(16, getProcessorCount()) - 1);
25 if ($this->iInstances < 1) {
26 $this->iInstances = 1;
27 warn('resetting threads to '.$this->iInstances);
30 // Assume we can steal all the cache memory in the box (unless told otherwise)
31 if (isset($aCMDResult['osm2pgsql-cache'])) {
32 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
34 $this->iCacheMemory = getCacheMemoryMB();
37 $this->sModulePath = CONST_Database_Module_Path;
38 info('module path: ' . $this->sModulePath);
40 // parse database string
41 $this->aDSNInfo = array_filter(\DB::parseDSN(CONST_Database_DSN));
42 if (!isset($this->aDSNInfo['port'])) {
43 $this->aDSNInfo['port'] = 5432;
46 // setting member variables based on command line options stored in $aCMDResult
47 $this->sVerbose = $aCMDResult['verbose'];
49 //setting default values which are not set by the update.php array
50 if (isset($aCMDResult['ignore-errors'])) {
51 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
53 $this->sIgnoreErrors = false;
55 if (isset($aCMDResult['enable-debug-statements'])) {
56 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
58 $this->bEnableDebugStatements = false;
60 if (isset($aCMDResult['no-partitions'])) {
61 $this->bNoPartitions = $aCMDResult['no-partitions'];
63 $this->bNoPartitions = false;
65 if (isset($aCMDResult['enable-diff-updates'])) {
66 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
68 $this->bEnableDiffUpdates = false;
72 public function createDB()
75 $sDB = \DB::connect(CONST_Database_DSN, false);
76 if (!\PEAR::isError($sDB)) {
77 fail('database already exists ('.CONST_Database_DSN.')');
80 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
81 if (isset($this->aDSNInfo['username'])) {
82 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
85 if (isset($this->aDSNInfo['hostspec'])) {
86 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
89 $result = $this->runWithPgEnv($sCreateDBCmd);
90 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
93 public function connect()
95 $this->oDB =& getDB();
98 public function setupDB()
102 $fPostgresVersion = getPostgresVersion($this->oDB);
103 echo 'Postgres version found: '.$fPostgresVersion."\n";
105 if ($fPostgresVersion < 9.01) {
106 fail('Minimum supported version of Postgresql is 9.1.');
109 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
110 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
112 // For extratags and namedetails the hstore_to_json converter is
113 // needed which is only available from Postgresql 9.3+. For older
114 // versions add a dummy function that returns nothing.
115 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
117 if ($iNumFunc == 0) {
118 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
119 warn('Postgresql is too old. extratags and namedetails API not available.');
123 $fPostgisVersion = getPostgisVersion($this->oDB);
124 echo 'Postgis version found: '.$fPostgisVersion."\n";
126 if ($fPostgisVersion < 2.1) {
127 // Functions were renamed in 2.1 and throw an annoying deprecation warning
128 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
129 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
131 if ($fPostgisVersion < 2.2) {
132 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
135 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
137 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
138 echo "\n createuser ".CONST_Database_Web_User."\n\n";
142 // Try accessing the C module, so we know early if something is wrong
143 if (!checkModulePresence()) {
144 fail('error loading nominatim.so module');
147 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
148 echo 'Error: you need to download the country_osm_grid first:';
149 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
152 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
153 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
154 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
155 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
157 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
158 if (file_exists($sPostcodeFilename)) {
159 $this->pgsqlRunScriptFile($sPostcodeFilename);
161 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
164 if (CONST_Use_Extra_US_Postcodes) {
165 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
168 if ($this->bNoPartitions) {
169 $this->pgsqlRunScript('update country_name set partition = 0');
172 // the following will be needed by createFunctions later but
173 // is only defined in the subsequently called createTables
174 // Create dummies here that will be overwritten by the proper
175 // versions in create-tables.
176 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
177 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
180 public function importData($sOSMFile)
184 $osm2pgsql = CONST_Osm2pgsql_Binary;
185 if (!file_exists($osm2pgsql)) {
186 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
187 echo "Normally you should not need to set this manually.\n";
188 fail("osm2pgsql not found in '$osm2pgsql'");
191 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
195 if (CONST_Tablespace_Osm2pgsql_Data)
196 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
197 if (CONST_Tablespace_Osm2pgsql_Index)
198 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
199 if (CONST_Tablespace_Place_Data)
200 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
201 if (CONST_Tablespace_Place_Index)
202 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
203 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
204 $osm2pgsql .= ' -C '.$this->iCacheMemory;
205 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
206 if (isset($this->aDSNInfo['username'])) {
207 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
209 if (isset($this->aDSNInfo['hostspec'])) {
210 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
212 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
214 $this->runWithPgEnv($osm2pgsql);
216 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
221 public function createFunctions()
223 info('Create Functions');
225 // Try accessing the C module, so we know eif something is wrong
226 // update.php calls this function
227 if (!checkModulePresence()) {
228 fail('error loading nominatim.so module');
230 $this->createSqlFunctions();
233 public function createTables($bReverseOnly = false)
235 info('Create Tables');
237 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
238 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
239 $sTemplate = $this->replaceTablespace(
241 CONST_Tablespace_Address_Data,
244 $sTemplate = $this->replaceTablespace(
245 '{ts:address-index}',
246 CONST_Tablespace_Address_Index,
249 $sTemplate = $this->replaceTablespace(
251 CONST_Tablespace_Search_Data,
254 $sTemplate = $this->replaceTablespace(
256 CONST_Tablespace_Search_Index,
259 $sTemplate = $this->replaceTablespace(
261 CONST_Tablespace_Aux_Data,
264 $sTemplate = $this->replaceTablespace(
266 CONST_Tablespace_Aux_Index,
270 $this->pgsqlRunScript($sTemplate, false);
273 $this->pgExec('DROP TABLE search_name');
277 public function createPartitionTables()
279 info('Create Partition Tables');
281 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
282 $sTemplate = $this->replaceTablespace(
284 CONST_Tablespace_Address_Data,
288 $sTemplate = $this->replaceTablespace(
289 '{ts:address-index}',
290 CONST_Tablespace_Address_Index,
294 $sTemplate = $this->replaceTablespace(
296 CONST_Tablespace_Search_Data,
300 $sTemplate = $this->replaceTablespace(
302 CONST_Tablespace_Search_Index,
306 $sTemplate = $this->replaceTablespace(
308 CONST_Tablespace_Aux_Data,
312 $sTemplate = $this->replaceTablespace(
314 CONST_Tablespace_Aux_Index,
318 $this->pgsqlRunPartitionScript($sTemplate);
321 public function createPartitionFunctions()
323 info('Create Partition Functions');
325 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
326 $this->pgsqlRunPartitionScript($sTemplate);
329 public function importWikipediaArticles()
331 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
332 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
333 if (file_exists($sWikiArticlesFile)) {
334 info('Importing wikipedia articles');
335 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
337 warn('wikipedia article dump file not found - places will have default importance');
339 if (file_exists($sWikiRedirectsFile)) {
340 info('Importing wikipedia redirects');
341 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
343 warn('wikipedia redirect dump file not found - some place importance values may be missing');
347 public function loadData($bDisableTokenPrecalc)
349 info('Drop old Data');
351 $this->pgExec('TRUNCATE word');
353 $this->pgExec('TRUNCATE placex');
355 $this->pgExec('TRUNCATE location_property_osmline');
357 $this->pgExec('TRUNCATE place_addressline');
359 $this->pgExec('TRUNCATE place_boundingbox');
361 $this->pgExec('TRUNCATE location_area');
363 if (!$this->dbReverseOnly()) {
364 $this->pgExec('TRUNCATE search_name');
367 $this->pgExec('TRUNCATE search_name_blank');
369 $this->pgExec('DROP SEQUENCE seq_place');
371 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
374 $sSQL = 'select distinct partition from country_name';
375 $aPartitions = chksql($this->oDB->getCol($sSQL));
376 if (!$this->bNoPartitions) $aPartitions[] = 0;
377 foreach ($aPartitions as $sPartition) {
378 $this->pgExec('TRUNCATE location_road_'.$sPartition);
382 // used by getorcreate_word_id to ignore frequent partial words
383 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
384 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
385 $this->pgExec($sSQL);
388 // pre-create the word list
389 if (!$bDisableTokenPrecalc) {
390 info('Loading word list');
391 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
395 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
396 $aDBInstances = array();
397 $iLoadThreads = max(1, $this->iInstances - 1);
398 for ($i = 0; $i < $iLoadThreads; $i++) {
399 $aDBInstances[$i] =& getDB(true);
400 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
401 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
402 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
403 $sSQL .= ' and ST_IsValid(geometry)';
404 if ($this->sVerbose) echo "$sSQL\n";
405 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
406 fail(pg_last_error($aDBInstances[$i]->connection));
410 // last thread for interpolation lines
411 $aDBInstances[$iLoadThreads] =& getDB(true);
412 $sSQL = 'insert into location_property_osmline';
413 $sSQL .= ' (osm_id, address, linegeo)';
414 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
415 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
416 if ($this->sVerbose) echo "$sSQL\n";
417 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
418 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
422 for ($i = 0; $i <= $iLoadThreads; $i++) {
423 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
424 $resultStatus = pg_result_status($hPGresult);
425 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
426 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
427 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
428 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
429 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
430 $resultError = pg_result_error($hPGresult);
431 echo '-- error text ' . $i . ': ' . $resultError . "\n";
437 fail('SQL errors loading placex and/or location_property_osmline tables');
440 info('Reanalysing database');
441 $this->pgsqlRunScript('ANALYSE');
443 $sDatabaseDate = getDatabaseDate($this->oDB);
444 pg_query($this->oDB->connection, 'TRUNCATE import_status');
445 if ($sDatabaseDate === false) {
446 warn('could not determine database date.');
448 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
449 pg_query($this->oDB->connection, $sSQL);
450 echo "Latest data imported from $sDatabaseDate.\n";
454 public function importTigerData()
456 info('Import Tiger data');
458 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
459 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
460 $sTemplate = $this->replaceTablespace(
462 CONST_Tablespace_Aux_Data,
465 $sTemplate = $this->replaceTablespace(
467 CONST_Tablespace_Aux_Index,
470 $this->pgsqlRunScript($sTemplate, false);
472 $aDBInstances = array();
473 for ($i = 0; $i < $this->iInstances; $i++) {
474 $aDBInstances[$i] =& getDB(true);
477 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
479 $hFile = fopen($sFile, 'r');
480 $sSQL = fgets($hFile, 100000);
483 for ($i = 0; $i < $this->iInstances; $i++) {
484 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
485 while (pg_get_result($aDBInstances[$i]->connection));
486 $sSQL = fgets($hFile, 100000);
488 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
490 if ($iLines == 1000) {
503 for ($i = 0; $i < $this->iInstances; $i++) {
504 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
511 info('Creating indexes on Tiger data');
512 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
513 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
514 $sTemplate = $this->replaceTablespace(
516 CONST_Tablespace_Aux_Data,
519 $sTemplate = $this->replaceTablespace(
521 CONST_Tablespace_Aux_Index,
524 $this->pgsqlRunScript($sTemplate, false);
527 public function calculatePostcodes($bCMDResultAll)
529 info('Calculate Postcodes');
530 $this->pgExec('TRUNCATE location_postcode');
532 $sSQL = 'INSERT INTO location_postcode';
533 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
534 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
535 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
536 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
537 $sSQL .= ' FROM placex';
538 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
539 $sSQL .= ' AND geometry IS NOT null';
540 $sSQL .= ' GROUP BY country_code, pc';
541 $this->pgExec($sSQL);
543 if (CONST_Use_Extra_US_Postcodes) {
544 // only add postcodes that are not yet available in OSM
545 $sSQL = 'INSERT INTO location_postcode';
546 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
547 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
548 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
549 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
550 $sSQL .= ' (SELECT postcode FROM location_postcode';
551 $sSQL .= " WHERE country_code = 'us')";
552 $this->pgExec($sSQL);
555 // add missing postcodes for GB (if available)
556 $sSQL = 'INSERT INTO location_postcode';
557 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
558 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
559 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
560 $sSQL .= ' (SELECT postcode FROM location_postcode';
561 $sSQL .= " WHERE country_code = 'gb')";
562 $this->pgExec($sSQL);
564 if (!$bCMDResultAll) {
565 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
566 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
567 $this->pgExec($sSQL);
570 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
571 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
572 $this->pgExec($sSQL);
575 public function index($bIndexNoanalyse)
578 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
579 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
580 if (isset($this->aDSNInfo['hostspec'])) {
581 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
583 if (isset($this->aDSNInfo['username'])) {
584 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
587 info('Index ranks 0 - 4');
588 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
590 fail('error status ' . $iStatus . ' running nominatim!');
592 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
594 info('Index ranks 5 - 25');
595 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
597 fail('error status ' . $iStatus . ' running nominatim!');
599 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
601 info('Index ranks 26 - 30');
602 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
604 fail('error status ' . $iStatus . ' running nominatim!');
607 info('Index postcodes');
608 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
609 $this->pgExec($sSQL);
612 public function createSearchIndices()
614 info('Create Search indices');
616 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
617 if (!$this->dbReverseOnly()) {
618 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
620 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
621 $sTemplate = $this->replaceTablespace(
622 '{ts:address-index}',
623 CONST_Tablespace_Address_Index,
626 $sTemplate = $this->replaceTablespace(
628 CONST_Tablespace_Search_Index,
631 $sTemplate = $this->replaceTablespace(
633 CONST_Tablespace_Aux_Index,
636 $this->pgsqlRunScript($sTemplate);
639 public function createCountryNames()
641 info('Create search index for default country names');
643 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
644 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
645 $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');
646 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
647 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
648 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
649 if (CONST_Languages) {
652 foreach (explode(',', CONST_Languages) as $sLang) {
653 $sSQL .= $sDelim."'name:$sLang'";
658 // all include all simple name tags
659 $sSQL .= "like 'name:%'";
662 $this->pgsqlRunScript($sSQL);
665 public function drop()
667 info('Drop tables only required for updates');
669 // The implementation is potentially a bit dangerous because it uses
670 // a positive selection of tables to keep, and deletes everything else.
671 // Including any tables that the unsuspecting user might have manually
672 // created. USE AT YOUR OWN PERIL.
673 // tables we want to keep. everything else goes.
674 $aKeepTables = array(
680 'location_property*',
692 $aDropTables = array();
693 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
695 foreach ($aHaveTables as $sTable) {
697 foreach ($aKeepTables as $sKeep) {
698 if (fnmatch($sKeep, $sTable)) {
703 if (!$bFound) array_push($aDropTables, $sTable);
705 foreach ($aDropTables as $sDrop) {
706 if ($this->sVerbose) echo "Dropping table $sDrop\n";
707 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
708 // ignore warnings/errors as they might be caused by a table having
709 // been deleted already by CASCADE
712 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
713 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
714 if ($this->sVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
715 unlink(CONST_Osm2pgsql_Flatnode_File);
720 private function pgsqlRunDropAndRestore($sDumpFile)
722 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
723 if (isset($this->aDSNInfo['hostspec'])) {
724 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
726 if (isset($this->aDSNInfo['username'])) {
727 $sCMD .= ' -U '.$this->aDSNInfo['username'];
730 $this->runWithPgEnv($sCMD);
733 private function pgsqlRunScript($sScript, $bfatal = true)
743 private function createSqlFunctions()
745 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
746 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
747 if ($this->bEnableDiffUpdates) {
748 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
750 if ($this->bEnableDebugStatements) {
751 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
753 if (CONST_Limit_Reindexing) {
754 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
756 if (!CONST_Use_US_Tiger_Data) {
757 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
759 if (!CONST_Use_Aux_Location_data) {
760 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
763 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
764 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
766 $this->pgsqlRunScript($sTemplate);
769 private function pgsqlRunPartitionScript($sTemplate)
771 $sSQL = 'select distinct partition from country_name';
772 $aPartitions = chksql($this->oDB->getCol($sSQL));
773 if (!$this->bNoPartitions) $aPartitions[] = 0;
775 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
776 foreach ($aMatches as $aMatch) {
778 foreach ($aPartitions as $sPartitionName) {
779 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
781 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
784 $this->pgsqlRunScript($sTemplate);
787 private function pgsqlRunScriptFile($sFilename)
789 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
791 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
792 if (!$this->sVerbose) {
795 if (isset($this->aDSNInfo['hostspec'])) {
796 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
798 if (isset($this->aDSNInfo['username'])) {
799 $sCMD .= ' -U '.$this->aDSNInfo['username'];
802 if (isset($this->aDSNInfo['password'])) {
803 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
806 if (preg_match('/\\.gz$/', $sFilename)) {
807 $aDescriptors = array(
808 0 => array('pipe', 'r'),
809 1 => array('pipe', 'w'),
810 2 => array('file', '/dev/null', 'a')
812 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
813 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
814 $aReadPipe = $ahGzipPipes[1];
815 fclose($ahGzipPipes[0]);
817 $sCMD .= ' -f '.$sFilename;
818 $aReadPipe = array('pipe', 'r');
820 $aDescriptors = array(
822 1 => array('pipe', 'w'),
823 2 => array('file', '/dev/null', 'a')
826 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
827 if (!is_resource($hProcess)) fail('unable to start pgsql');
828 // TODO: error checking
829 while (!feof($ahPipes[1])) {
830 echo fread($ahPipes[1], 4096);
833 $iReturn = proc_close($hProcess);
835 fail("pgsql returned with error code ($iReturn)");
838 fclose($ahGzipPipes[1]);
839 proc_close($hGzipProcess);
843 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
846 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
848 $sSql = str_replace($sTemplate, '', $sSql);
853 private function runWithPgEnv($sCmd)
857 if (isset($this->aDSNInfo['password'])) {
858 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
861 return runWithEnv($sCmd, $aProcEnv);
865 * Execute the SQL command on the open database.
867 * @param string $sSQL SQL command to execute.
871 * @pre connect() must have been called.
873 private function pgExec($sSQL)
875 if (!pg_query($this->oDB->connection, $sSQL)) {
876 fail(pg_last_error($this->oDB->connection));
881 * Check if the database is in reverse-only mode.
883 * @return True if there is no search_name table and infrastructure.
885 private function dbReverseOnly()
887 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = 'search_name'";
888 return !(chksql($this->oDB->getOne($sSQL)));