3 namespace Nominatim\Setup;
5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
9 protected $iCacheMemory;
10 protected $iInstances;
11 protected $sModulePath;
15 protected $sIgnoreErrors;
16 protected $bEnableDiffUpdates;
17 protected $bEnableDebugStatements;
18 protected $bNoPartitions;
19 protected $oDB = null;
21 public function __construct(array $aCMDResult)
23 // by default, use all but one processor, but never more than 15.
24 $this->iInstances = isset($aCMDResult['threads'])
25 ? $aCMDResult['threads']
26 : (min(16, getProcessorCount()) - 1);
28 if ($this->iInstances < 1) {
29 $this->iInstances = 1;
30 warn('resetting threads to '.$this->iInstances);
33 if (isset($aCMDResult['osm2pgsql-cache'])) {
34 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
35 } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
36 // When flatnode files are enabled then disable cache per default.
37 $this->iCacheMemory = 0;
39 // Otherwise: Assume we can steal all the cache memory in the box.
40 $this->iCacheMemory = getCacheMemoryMB();
43 $this->sModulePath = CONST_Database_Module_Path;
44 info('module path: ' . $this->sModulePath);
46 // parse database string
47 $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
48 if (!isset($this->aDSNInfo['port'])) {
49 $this->aDSNInfo['port'] = 5432;
52 // setting member variables based on command line options stored in $aCMDResult
53 $this->bQuiet = $aCMDResult['quiet'];
54 $this->bVerbose = $aCMDResult['verbose'];
56 //setting default values which are not set by the update.php array
57 if (isset($aCMDResult['ignore-errors'])) {
58 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
60 $this->sIgnoreErrors = false;
62 if (isset($aCMDResult['enable-debug-statements'])) {
63 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
65 $this->bEnableDebugStatements = false;
67 if (isset($aCMDResult['no-partitions'])) {
68 $this->bNoPartitions = $aCMDResult['no-partitions'];
70 $this->bNoPartitions = false;
72 if (isset($aCMDResult['enable-diff-updates'])) {
73 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
75 $this->bEnableDiffUpdates = false;
79 public function createDB()
82 $oDB = new \Nominatim\DB;
84 if ($oDB->databaseExists()) {
85 fail('database already exists ('.CONST_Database_DSN.')');
88 $sCreateDBCmd = 'createdb -E UTF-8'
89 .' -p '.escapeshellarg($this->aDSNInfo['port'])
90 .' '.escapeshellarg($this->aDSNInfo['database']);
91 if (isset($this->aDSNInfo['username'])) {
92 $sCreateDBCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
95 if (isset($this->aDSNInfo['hostspec'])) {
96 $sCreateDBCmd .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
99 $result = $this->runWithPgEnv($sCreateDBCmd);
100 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
103 public function connect()
105 $this->oDB = new \Nominatim\DB();
106 $this->oDB->connect();
109 public function setupDB()
113 $fPostgresVersion = $this->oDB->getPostgresVersion();
114 echo 'Postgres version found: '.$fPostgresVersion."\n";
116 if ($fPostgresVersion < 9.03) {
117 fail('Minimum supported version of Postgresql is 9.3.');
120 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
121 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
123 $fPostgisVersion = $this->oDB->getPostgisVersion();
124 echo 'Postgis version found: '.$fPostgisVersion."\n";
126 if ($fPostgisVersion < 2.2) {
127 echo "Minimum required Postgis version 2.2\n";
131 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
133 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
134 echo "\n createuser ".CONST_Database_Web_User."\n\n";
138 // Try accessing the C module, so we know early if something is wrong
139 checkModulePresence(); // raises exception on failure
141 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
142 echo 'Error: you need to download the country_osm_grid first:';
143 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
146 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
147 $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
148 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
149 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
151 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
152 if (file_exists($sPostcodeFilename)) {
153 $this->pgsqlRunScriptFile($sPostcodeFilename);
155 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
158 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
159 if (file_exists($sPostcodeFilename)) {
160 $this->pgsqlRunScriptFile($sPostcodeFilename);
162 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
165 if ($this->bNoPartitions) {
166 $this->pgsqlRunScript('update country_name set partition = 0');
170 public function importData($sOSMFile)
174 $osm2pgsql = CONST_Osm2pgsql_Binary;
175 if (!file_exists($osm2pgsql)) {
176 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
177 echo "Normally you should not need to set this manually.\n";
178 fail("osm2pgsql not found in '$osm2pgsql'");
181 $osm2pgsql .= ' -S '.escapeshellarg(CONST_Import_Style);
183 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
184 $osm2pgsql .= ' --flat-nodes '.escapeshellarg(CONST_Osm2pgsql_Flatnode_File);
187 if (CONST_Tablespace_Osm2pgsql_Data)
188 $osm2pgsql .= ' --tablespace-slim-data '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Data);
189 if (CONST_Tablespace_Osm2pgsql_Index)
190 $osm2pgsql .= ' --tablespace-slim-index '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Index);
191 if (CONST_Tablespace_Place_Data)
192 $osm2pgsql .= ' --tablespace-main-data '.escapeshellarg(CONST_Tablespace_Place_Data);
193 if (CONST_Tablespace_Place_Index)
194 $osm2pgsql .= ' --tablespace-main-index '.escapeshellarg(CONST_Tablespace_Place_Index);
195 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
196 $osm2pgsql .= ' -C '.escapeshellarg($this->iCacheMemory);
197 $osm2pgsql .= ' -P '.escapeshellarg($this->aDSNInfo['port']);
198 if (isset($this->aDSNInfo['username'])) {
199 $osm2pgsql .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
201 if (isset($this->aDSNInfo['hostspec'])) {
202 $osm2pgsql .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
204 $osm2pgsql .= ' -d '.escapeshellarg($this->aDSNInfo['database']).' '.escapeshellarg($sOSMFile);
206 $this->runWithPgEnv($osm2pgsql);
208 if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
213 public function createFunctions()
215 info('Create Functions');
217 // Try accessing the C module, so we know early if something is wrong
218 checkModulePresence(); // raises exception on failure
220 $this->createSqlFunctions();
223 public function createTables($bReverseOnly = false)
225 info('Create Tables');
227 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
228 $sTemplate = $this->replaceSqlPatterns($sTemplate);
230 $this->pgsqlRunScript($sTemplate, false);
233 $this->dropTable('search_name');
236 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
237 $oAlParser->createTable($this->oDB, 'address_levels');
240 public function createTableTriggers()
242 info('Create Tables');
244 $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
245 $sTemplate = $this->replaceSqlPatterns($sTemplate);
247 $this->pgsqlRunScript($sTemplate, false);
250 public function createPartitionTables()
252 info('Create Partition Tables');
254 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
255 $sTemplate = $this->replaceSqlPatterns($sTemplate);
257 $this->pgsqlRunPartitionScript($sTemplate);
260 public function createPartitionFunctions()
262 info('Create Partition Functions');
264 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
265 $this->pgsqlRunPartitionScript($sTemplate);
268 public function importWikipediaArticles()
270 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
271 if (file_exists($sWikiArticlesFile)) {
272 info('Importing wikipedia articles and redirects');
273 $this->dropTable('wikipedia_article');
274 $this->dropTable('wikipedia_redirect');
275 $this->pgsqlRunScriptFile($sWikiArticlesFile);
277 warn('wikipedia importance dump file not found - places will have default importance');
281 public function loadData($bDisableTokenPrecalc)
283 info('Drop old Data');
285 $this->oDB->exec('TRUNCATE word');
287 $this->oDB->exec('TRUNCATE placex');
289 $this->oDB->exec('TRUNCATE location_property_osmline');
291 $this->oDB->exec('TRUNCATE place_addressline');
293 $this->oDB->exec('TRUNCATE location_area');
295 if (!$this->dbReverseOnly()) {
296 $this->oDB->exec('TRUNCATE search_name');
299 $this->oDB->exec('TRUNCATE search_name_blank');
301 $this->oDB->exec('DROP SEQUENCE seq_place');
303 $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
306 $sSQL = 'select distinct partition from country_name';
307 $aPartitions = $this->oDB->getCol($sSQL);
309 if (!$this->bNoPartitions) $aPartitions[] = 0;
310 foreach ($aPartitions as $sPartition) {
311 $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
315 // used by getorcreate_word_id to ignore frequent partial words
316 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
317 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
318 $this->oDB->exec($sSQL);
321 // pre-create the word list
322 if (!$bDisableTokenPrecalc) {
323 info('Loading word list');
324 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
328 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
330 $aDBInstances = array();
331 $iLoadThreads = max(1, $this->iInstances - 1);
332 for ($i = 0; $i < $iLoadThreads; $i++) {
333 // https://secure.php.net/manual/en/function.pg-connect.php
334 $DSN = CONST_Database_DSN;
335 $DSN = preg_replace('/^pgsql:/', '', $DSN);
336 $DSN = preg_replace('/;/', ' ', $DSN);
337 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
338 pg_ping($aDBInstances[$i]);
341 for ($i = 0; $i < $iLoadThreads; $i++) {
342 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
343 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
344 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
345 $sSQL .= ' and ST_IsValid(geometry)';
346 if ($this->bVerbose) echo "$sSQL\n";
347 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
348 fail(pg_last_error($aDBInstances[$i]));
352 // last thread for interpolation lines
353 // https://secure.php.net/manual/en/function.pg-connect.php
354 $DSN = CONST_Database_DSN;
355 $DSN = preg_replace('/^pgsql:/', '', $DSN);
356 $DSN = preg_replace('/;/', ' ', $DSN);
357 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
358 pg_ping($aDBInstances[$iLoadThreads]);
359 $sSQL = 'insert into location_property_osmline';
360 $sSQL .= ' (osm_id, address, linegeo)';
361 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
362 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
363 if ($this->bVerbose) echo "$sSQL\n";
364 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
365 fail(pg_last_error($aDBInstances[$iLoadThreads]));
369 for ($i = 0; $i <= $iLoadThreads; $i++) {
370 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
371 $resultStatus = pg_result_status($hPGresult);
372 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
373 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
374 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
375 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
376 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
377 $resultError = pg_result_error($hPGresult);
378 echo '-- error text ' . $i . ': ' . $resultError . "\n";
384 fail('SQL errors loading placex and/or location_property_osmline tables');
387 for ($i = 0; $i < $this->iInstances; $i++) {
388 pg_close($aDBInstances[$i]);
392 info('Reanalysing database');
393 $this->pgsqlRunScript('ANALYSE');
395 $sDatabaseDate = getDatabaseDate($this->oDB);
396 $this->oDB->exec('TRUNCATE import_status');
397 if (!$sDatabaseDate) {
398 warn('could not determine database date.');
400 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
401 $this->oDB->exec($sSQL);
402 echo "Latest data imported from $sDatabaseDate.\n";
406 public function importTigerData()
408 info('Import Tiger data');
410 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
411 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
412 if (empty($aFilenames)) return;
414 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
415 $sTemplate = $this->replaceSqlPatterns($sTemplate);
417 $this->pgsqlRunScript($sTemplate, false);
419 $aDBInstances = array();
420 for ($i = 0; $i < $this->iInstances; $i++) {
421 // https://secure.php.net/manual/en/function.pg-connect.php
422 $DSN = CONST_Database_DSN;
423 $DSN = preg_replace('/^pgsql:/', '', $DSN);
424 $DSN = preg_replace('/;/', ' ', $DSN);
425 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
426 pg_ping($aDBInstances[$i]);
429 foreach ($aFilenames as $sFile) {
431 $hFile = fopen($sFile, 'r');
432 $sSQL = fgets($hFile, 100000);
435 for ($i = 0; $i < $this->iInstances; $i++) {
436 if (!pg_connection_busy($aDBInstances[$i])) {
437 while (pg_get_result($aDBInstances[$i]));
438 $sSQL = fgets($hFile, 100000);
440 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
442 if ($iLines == 1000) {
455 for ($i = 0; $i < $this->iInstances; $i++) {
456 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
463 for ($i = 0; $i < $this->iInstances; $i++) {
464 pg_close($aDBInstances[$i]);
467 info('Creating indexes on Tiger data');
468 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
469 $sTemplate = $this->replaceSqlPatterns($sTemplate);
471 $this->pgsqlRunScript($sTemplate, false);
474 public function calculatePostcodes($bCMDResultAll)
476 info('Calculate Postcodes');
477 $this->oDB->exec('TRUNCATE location_postcode');
479 $sSQL = 'INSERT INTO location_postcode';
480 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
481 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
482 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
483 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
484 $sSQL .= ' FROM placex';
485 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
486 $sSQL .= ' AND geometry IS NOT null';
487 $sSQL .= ' GROUP BY country_code, pc';
488 $this->oDB->exec($sSQL);
490 // only add postcodes that are not yet available in OSM
491 $sSQL = 'INSERT INTO location_postcode';
492 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
493 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
494 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
495 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
496 $sSQL .= ' (SELECT postcode FROM location_postcode';
497 $sSQL .= " WHERE country_code = 'us')";
498 $this->oDB->exec($sSQL);
500 // add missing postcodes for GB (if available)
501 $sSQL = 'INSERT INTO location_postcode';
502 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
503 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
504 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
505 $sSQL .= ' (SELECT postcode FROM location_postcode';
506 $sSQL .= " WHERE country_code = 'gb')";
507 $this->oDB->exec($sSQL);
509 if (!$bCMDResultAll) {
510 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
511 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
512 $this->oDB->exec($sSQL);
515 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
516 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
517 $this->oDB->exec($sSQL);
520 public function index($bIndexNoanalyse)
523 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim.py'
524 .' -d '.escapeshellarg($this->aDSNInfo['database'])
525 .' -P '.escapeshellarg($this->aDSNInfo['port'])
526 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
527 if (!$this->bQuiet) {
530 if ($this->bVerbose) {
533 if (isset($this->aDSNInfo['hostspec'])) {
534 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
536 if (isset($this->aDSNInfo['username'])) {
537 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
540 info('Index ranks 0 - 4');
541 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
543 fail('error status ' . $iStatus . ' running nominatim!');
545 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
547 info('Index ranks 5 - 25');
548 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
550 fail('error status ' . $iStatus . ' running nominatim!');
552 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
554 info('Index ranks 26 - 30');
555 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
557 fail('error status ' . $iStatus . ' running nominatim!');
560 info('Index postcodes');
561 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
562 $this->oDB->exec($sSQL);
565 public function createSearchIndices()
567 info('Create Search indices');
569 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
570 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
571 $aInvalidIndices = $this->oDB->getCol($sSQL);
573 foreach ($aInvalidIndices as $sIndexName) {
574 info("Cleaning up invalid index $sIndexName");
575 $this->oDB->exec("DROP INDEX $sIndexName;");
578 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
579 if (!$this->dbReverseOnly()) {
580 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
582 $sTemplate = $this->replaceSqlPatterns($sTemplate);
584 $this->pgsqlRunScript($sTemplate);
587 public function createCountryNames()
589 info('Create search index for default country names');
591 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
592 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
593 $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');
594 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
595 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
596 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
597 if (CONST_Languages) {
600 foreach (explode(',', CONST_Languages) as $sLang) {
601 $sSQL .= $sDelim."'name:$sLang'";
606 // all include all simple name tags
607 $sSQL .= "like 'name:%'";
610 $this->pgsqlRunScript($sSQL);
613 public function drop()
615 info('Drop tables only required for updates');
617 // The implementation is potentially a bit dangerous because it uses
618 // a positive selection of tables to keep, and deletes everything else.
619 // Including any tables that the unsuspecting user might have manually
620 // created. USE AT YOUR OWN PERIL.
621 // tables we want to keep. everything else goes.
622 $aKeepTables = array(
628 'location_property*',
641 $aDropTables = array();
642 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
644 foreach ($aHaveTables as $sTable) {
646 foreach ($aKeepTables as $sKeep) {
647 if (fnmatch($sKeep, $sTable)) {
652 if (!$bFound) array_push($aDropTables, $sTable);
654 foreach ($aDropTables as $sDrop) {
655 $this->dropTable($sDrop);
658 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
659 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
660 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
661 unlink(CONST_Osm2pgsql_Flatnode_File);
666 private function pgsqlRunScript($sScript, $bfatal = true)
676 private function createSqlFunctions()
678 $sBasePath = CONST_BasePath.'/sql/functions/';
679 $sTemplate = file_get_contents($sBasePath.'utils.sql');
680 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
681 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
682 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
683 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
684 if ($this->oDB->tableExists('place')) {
685 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
687 if ($this->oDB->tableExists('placex')) {
688 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
690 if ($this->oDB->tableExists('location_postcode')) {
691 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
693 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
694 if ($this->bEnableDiffUpdates) {
695 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
697 if ($this->bEnableDebugStatements) {
698 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
700 if (CONST_Limit_Reindexing) {
701 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
703 if (!CONST_Use_US_Tiger_Data) {
704 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
706 if (!CONST_Use_Aux_Location_data) {
707 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
710 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
711 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
713 $this->pgsqlRunScript($sTemplate);
716 private function pgsqlRunPartitionScript($sTemplate)
718 $sSQL = 'select distinct partition from country_name';
719 $aPartitions = $this->oDB->getCol($sSQL);
720 if (!$this->bNoPartitions) $aPartitions[] = 0;
722 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
723 foreach ($aMatches as $aMatch) {
725 foreach ($aPartitions as $sPartitionName) {
726 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
728 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
731 $this->pgsqlRunScript($sTemplate);
734 private function pgsqlRunScriptFile($sFilename)
736 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
739 .' -p '.escapeshellarg($this->aDSNInfo['port'])
740 .' -d '.escapeshellarg($this->aDSNInfo['database']);
741 if (!$this->bVerbose) {
744 if (isset($this->aDSNInfo['hostspec'])) {
745 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
747 if (isset($this->aDSNInfo['username'])) {
748 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
751 if (isset($this->aDSNInfo['password'])) {
752 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
755 if (preg_match('/\\.gz$/', $sFilename)) {
756 $aDescriptors = array(
757 0 => array('pipe', 'r'),
758 1 => array('pipe', 'w'),
759 2 => array('file', '/dev/null', 'a')
761 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
762 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
763 $aReadPipe = $ahGzipPipes[1];
764 fclose($ahGzipPipes[0]);
766 $sCMD .= ' -f '.escapeshellarg($sFilename);
767 $aReadPipe = array('pipe', 'r');
769 $aDescriptors = array(
771 1 => array('pipe', 'w'),
772 2 => array('file', '/dev/null', 'a')
775 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
776 if (!is_resource($hProcess)) fail('unable to start pgsql');
777 // TODO: error checking
778 while (!feof($ahPipes[1])) {
779 echo fread($ahPipes[1], 4096);
782 $iReturn = proc_close($hProcess);
784 fail("pgsql returned with error code ($iReturn)");
787 fclose($ahGzipPipes[1]);
788 proc_close($hGzipProcess);
792 private function replaceSqlPatterns($sSql)
794 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
797 '{ts:address-data}' => CONST_Tablespace_Address_Data,
798 '{ts:address-index}' => CONST_Tablespace_Address_Index,
799 '{ts:search-data}' => CONST_Tablespace_Search_Data,
800 '{ts:search-index}' => CONST_Tablespace_Search_Index,
801 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
802 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
805 foreach ($aPatterns as $sPattern => $sTablespace) {
807 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
809 $sSql = str_replace($sPattern, '', $sSql);
816 private function runWithPgEnv($sCmd)
818 if ($this->bVerbose) {
819 echo "Execute: $sCmd\n";
824 if (isset($this->aDSNInfo['password'])) {
825 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
828 return runWithEnv($sCmd, $aProcEnv);
832 * Drop table with the given name if it exists.
834 * @param string $sName Name of table to remove.
838 * @pre connect() must have been called.
840 private function dropTable($sName)
842 if ($this->bVerbose) echo "Dropping table $sName\n";
843 $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
847 * Check if the database is in reverse-only mode.
849 * @return True if there is no search_name table and infrastructure.
851 private function dbReverseOnly()
853 return !($this->oDB->tableExists('search_name'));