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()
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 public function createPartitionTables()
275 info('Create Partition Tables');
277 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
278 $sTemplate = $this->replaceTablespace(
280 CONST_Tablespace_Address_Data,
284 $sTemplate = $this->replaceTablespace(
285 '{ts:address-index}',
286 CONST_Tablespace_Address_Index,
290 $sTemplate = $this->replaceTablespace(
292 CONST_Tablespace_Search_Data,
296 $sTemplate = $this->replaceTablespace(
298 CONST_Tablespace_Search_Index,
302 $sTemplate = $this->replaceTablespace(
304 CONST_Tablespace_Aux_Data,
308 $sTemplate = $this->replaceTablespace(
310 CONST_Tablespace_Aux_Index,
314 $this->pgsqlRunPartitionScript($sTemplate);
317 public function createPartitionFunctions()
319 info('Create Partition Functions');
321 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
322 $this->pgsqlRunPartitionScript($sTemplate);
325 public function importWikipediaArticles()
327 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
328 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
329 if (file_exists($sWikiArticlesFile)) {
330 info('Importing wikipedia articles');
331 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
333 warn('wikipedia article dump file not found - places will have default importance');
335 if (file_exists($sWikiRedirectsFile)) {
336 info('Importing wikipedia redirects');
337 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
339 warn('wikipedia redirect dump file not found - some place importance values may be missing');
343 public function loadData($bDisableTokenPrecalc)
345 info('Drop old Data');
347 $this->pgExec('TRUNCATE word');
349 $this->pgExec('TRUNCATE placex');
351 $this->pgExec('TRUNCATE location_property_osmline');
353 $this->pgExec('TRUNCATE place_addressline');
355 $this->pgExec('TRUNCATE place_boundingbox');
357 $this->pgExec('TRUNCATE location_area');
359 $this->pgExec('TRUNCATE search_name');
361 $this->pgExec('TRUNCATE search_name_blank');
363 $this->pgExec('DROP SEQUENCE seq_place');
365 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
368 $sSQL = 'select distinct partition from country_name';
369 $aPartitions = chksql($this->oDB->getCol($sSQL));
370 if (!$this->bNoPartitions) $aPartitions[] = 0;
371 foreach ($aPartitions as $sPartition) {
372 $this->pgExec('TRUNCATE location_road_'.$sPartition);
376 // used by getorcreate_word_id to ignore frequent partial words
377 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
378 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
379 $this->pgExec($sSQL);
382 // pre-create the word list
383 if (!$bDisableTokenPrecalc) {
384 info('Loading word list');
385 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
389 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
390 $aDBInstances = array();
391 $iLoadThreads = max(1, $this->iInstances - 1);
392 for ($i = 0; $i < $iLoadThreads; $i++) {
393 $aDBInstances[$i] =& getDB(true);
394 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
395 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
396 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
397 $sSQL .= ' and ST_IsValid(geometry)';
398 if ($this->sVerbose) echo "$sSQL\n";
399 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
400 fail(pg_last_error($aDBInstances[$i]->connection));
404 // last thread for interpolation lines
405 $aDBInstances[$iLoadThreads] =& getDB(true);
406 $sSQL = 'insert into location_property_osmline';
407 $sSQL .= ' (osm_id, address, linegeo)';
408 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
409 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
410 if ($this->sVerbose) echo "$sSQL\n";
411 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
412 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
416 for ($i = 0; $i <= $iLoadThreads; $i++) {
417 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
418 $resultStatus = pg_result_status($hPGresult);
419 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
420 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
421 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
422 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
423 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
424 $resultError = pg_result_error($hPGresult);
425 echo '-- error text ' . $i . ': ' . $resultError . "\n";
431 fail('SQL errors loading placex and/or location_property_osmline tables');
434 info('Reanalysing database');
435 $this->pgsqlRunScript('ANALYSE');
437 $sDatabaseDate = getDatabaseDate($this->oDB);
438 pg_query($this->oDB->connection, 'TRUNCATE import_status');
439 if ($sDatabaseDate === false) {
440 warn('could not determine database date.');
442 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
443 pg_query($this->oDB->connection, $sSQL);
444 echo "Latest data imported from $sDatabaseDate.\n";
448 public function importTigerData()
450 info('Import Tiger data');
452 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
453 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
454 $sTemplate = $this->replaceTablespace(
456 CONST_Tablespace_Aux_Data,
459 $sTemplate = $this->replaceTablespace(
461 CONST_Tablespace_Aux_Index,
464 $this->pgsqlRunScript($sTemplate, false);
466 $aDBInstances = array();
467 for ($i = 0; $i < $this->iInstances; $i++) {
468 $aDBInstances[$i] =& getDB(true);
471 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
473 $hFile = fopen($sFile, 'r');
474 $sSQL = fgets($hFile, 100000);
477 for ($i = 0; $i < $this->iInstances; $i++) {
478 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
479 while (pg_get_result($aDBInstances[$i]->connection));
480 $sSQL = fgets($hFile, 100000);
482 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
484 if ($iLines == 1000) {
497 for ($i = 0; $i < $this->iInstances; $i++) {
498 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
505 info('Creating indexes on Tiger data');
506 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
507 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
508 $sTemplate = $this->replaceTablespace(
510 CONST_Tablespace_Aux_Data,
513 $sTemplate = $this->replaceTablespace(
515 CONST_Tablespace_Aux_Index,
518 $this->pgsqlRunScript($sTemplate, false);
521 public function calculatePostcodes($bCMDResultAll)
523 info('Calculate Postcodes');
524 $this->pgExec('TRUNCATE location_postcode');
526 $sSQL = 'INSERT INTO location_postcode';
527 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
528 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
529 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
530 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
531 $sSQL .= ' FROM placex';
532 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
533 $sSQL .= ' AND geometry IS NOT null';
534 $sSQL .= ' GROUP BY country_code, pc';
535 $this->pgExec($sSQL);
537 if (CONST_Use_Extra_US_Postcodes) {
538 // only add postcodes that are not yet available in OSM
539 $sSQL = 'INSERT INTO location_postcode';
540 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
541 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
542 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
543 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
544 $sSQL .= ' (SELECT postcode FROM location_postcode';
545 $sSQL .= " WHERE country_code = 'us')";
546 $this->pgExec($sSQL);
549 // add missing postcodes for GB (if available)
550 $sSQL = 'INSERT INTO location_postcode';
551 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
552 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
553 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
554 $sSQL .= ' (SELECT postcode FROM location_postcode';
555 $sSQL .= " WHERE country_code = 'gb')";
556 $this->pgExec($sSQL);
558 if (!$bCMDResultAll) {
559 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
560 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
561 $this->pgExec($sSQL);
564 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
565 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
566 $this->pgExec($sSQL);
569 public function index($bIndexNoanalyse)
572 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
573 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
574 if (isset($this->aDSNInfo['hostspec'])) {
575 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
577 if (isset($this->aDSNInfo['username'])) {
578 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
581 info('Index ranks 0 - 4');
582 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
584 fail('error status ' . $iStatus . ' running nominatim!');
586 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
588 info('Index ranks 5 - 25');
589 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
591 fail('error status ' . $iStatus . ' running nominatim!');
593 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
595 info('Index ranks 26 - 30');
596 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
598 fail('error status ' . $iStatus . ' running nominatim!');
601 info('Index postcodes');
602 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
603 $this->pgExec($sSQL);
606 public function createSearchIndices()
608 info('Create Search indices');
610 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
611 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
612 $sTemplate = $this->replaceTablespace(
613 '{ts:address-index}',
614 CONST_Tablespace_Address_Index,
617 $sTemplate = $this->replaceTablespace(
619 CONST_Tablespace_Search_Index,
622 $sTemplate = $this->replaceTablespace(
624 CONST_Tablespace_Aux_Index,
627 $this->pgsqlRunScript($sTemplate);
630 public function createCountryNames()
632 info('Create search index for default country names');
634 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
635 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
636 $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');
637 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
638 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
639 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
640 if (CONST_Languages) {
643 foreach (explode(',', CONST_Languages) as $sLang) {
644 $sSQL .= $sDelim."'name:$sLang'";
649 // all include all simple name tags
650 $sSQL .= "like 'name:%'";
653 $this->pgsqlRunScript($sSQL);
656 public function drop()
658 info('Drop tables only required for updates');
660 // The implementation is potentially a bit dangerous because it uses
661 // a positive selection of tables to keep, and deletes everything else.
662 // Including any tables that the unsuspecting user might have manually
663 // created. USE AT YOUR OWN PERIL.
664 // tables we want to keep. everything else goes.
665 $aKeepTables = array(
671 'location_property*',
683 $aDropTables = array();
684 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
686 foreach ($aHaveTables as $sTable) {
688 foreach ($aKeepTables as $sKeep) {
689 if (fnmatch($sKeep, $sTable)) {
694 if (!$bFound) array_push($aDropTables, $sTable);
696 foreach ($aDropTables as $sDrop) {
697 if ($this->sVerbose) echo "dropping table $sDrop\n";
698 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
699 // ignore warnings/errors as they might be caused by a table having
700 // been deleted already by CASCADE
703 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
704 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
705 unlink(CONST_Osm2pgsql_Flatnode_File);
709 private function pgsqlRunDropAndRestore($sDumpFile)
711 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
712 if (isset($this->aDSNInfo['hostspec'])) {
713 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
715 if (isset($this->aDSNInfo['username'])) {
716 $sCMD .= ' -U '.$this->aDSNInfo['username'];
719 $this->runWithPgEnv($sCMD);
722 private function pgsqlRunScript($sScript, $bfatal = true)
732 private function createSqlFunctions()
734 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
735 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
736 if ($this->bEnableDiffUpdates) {
737 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
739 if ($this->bEnableDebugStatements) {
740 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
742 if (CONST_Limit_Reindexing) {
743 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
745 if (!CONST_Use_US_Tiger_Data) {
746 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
748 if (!CONST_Use_Aux_Location_data) {
749 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
751 $this->pgsqlRunScript($sTemplate);
754 private function pgsqlRunPartitionScript($sTemplate)
756 $sSQL = 'select distinct partition from country_name';
757 $aPartitions = chksql($this->oDB->getCol($sSQL));
758 if (!$this->bNoPartitions) $aPartitions[] = 0;
760 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
761 foreach ($aMatches as $aMatch) {
763 foreach ($aPartitions as $sPartitionName) {
764 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
766 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
769 $this->pgsqlRunScript($sTemplate);
772 private function pgsqlRunScriptFile($sFilename)
774 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
776 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
777 if (!$this->sVerbose) {
780 if (isset($this->aDSNInfo['hostspec'])) {
781 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
783 if (isset($this->aDSNInfo['username'])) {
784 $sCMD .= ' -U '.$this->aDSNInfo['username'];
787 if (isset($this->aDSNInfo['password'])) {
788 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
791 if (preg_match('/\\.gz$/', $sFilename)) {
792 $aDescriptors = array(
793 0 => array('pipe', 'r'),
794 1 => array('pipe', 'w'),
795 2 => array('file', '/dev/null', 'a')
797 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
798 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
799 $aReadPipe = $ahGzipPipes[1];
800 fclose($ahGzipPipes[0]);
802 $sCMD .= ' -f '.$sFilename;
803 $aReadPipe = array('pipe', 'r');
805 $aDescriptors = array(
807 1 => array('pipe', 'w'),
808 2 => array('file', '/dev/null', 'a')
811 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
812 if (!is_resource($hProcess)) fail('unable to start pgsql');
813 // TODO: error checking
814 while (!feof($ahPipes[1])) {
815 echo fread($ahPipes[1], 4096);
818 $iReturn = proc_close($hProcess);
820 fail("pgsql returned with error code ($iReturn)");
823 fclose($ahGzipPipes[1]);
824 proc_close($hGzipProcess);
828 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
831 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
833 $sSql = str_replace($sTemplate, '', $sSql);
838 private function runWithPgEnv($sCmd)
842 if (isset($this->aDSNInfo['password'])) {
843 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
846 return runWithEnv($sCmd, $aProcEnv);
850 * Execute the SQL command on the open database.
852 * @param string $sSQL SQL command to execute.
856 * @pre connect() must have been called.
858 private function pgExec($sSQL)
860 if (!pg_query($this->oDB->connection, $sSQL)) {
861 fail(pg_last_error($this->oDB->connection));