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;
20 protected $oDB = null;
22 public function __construct(array $aCMDResult)
24 // by default, use all but one processor, but never more than 15.
25 $this->iInstances = isset($aCMDResult['threads'])
26 ? $aCMDResult['threads']
27 : (min(16, getProcessorCount()) - 1);
29 if ($this->iInstances < 1) {
30 $this->iInstances = 1;
31 warn('resetting threads to '.$this->iInstances);
34 if (isset($aCMDResult['osm2pgsql-cache'])) {
35 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
36 } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
37 // When flatnode files are enabled then disable cache per default.
38 $this->iCacheMemory = 0;
40 // Otherwise: Assume we can steal all the cache memory in the box.
41 $this->iCacheMemory = getCacheMemoryMB();
44 $this->sModulePath = CONST_Database_Module_Path;
45 info('module path: ' . $this->sModulePath);
47 // parse database string
48 $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
49 if (!isset($this->aDSNInfo['port'])) {
50 $this->aDSNInfo['port'] = 5432;
53 // setting member variables based on command line options stored in $aCMDResult
54 $this->bQuiet = $aCMDResult['quiet'];
55 $this->bVerbose = $aCMDResult['verbose'];
57 //setting default values which are not set by the update.php array
58 if (isset($aCMDResult['ignore-errors'])) {
59 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
61 $this->sIgnoreErrors = false;
63 if (isset($aCMDResult['enable-debug-statements'])) {
64 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
66 $this->bEnableDebugStatements = false;
68 if (isset($aCMDResult['no-partitions'])) {
69 $this->bNoPartitions = $aCMDResult['no-partitions'];
71 $this->bNoPartitions = false;
73 if (isset($aCMDResult['enable-diff-updates'])) {
74 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
76 $this->bEnableDiffUpdates = false;
79 $this->bDrop = $aCMDResult['drop'];
82 public function createDB()
85 $oDB = new \Nominatim\DB;
87 if ($oDB->databaseExists()) {
88 fail('database already exists ('.CONST_Database_DSN.')');
91 $sCreateDBCmd = 'createdb -E UTF-8'
92 .' -p '.escapeshellarg($this->aDSNInfo['port'])
93 .' '.escapeshellarg($this->aDSNInfo['database']);
94 if (isset($this->aDSNInfo['username'])) {
95 $sCreateDBCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
98 if (isset($this->aDSNInfo['hostspec'])) {
99 $sCreateDBCmd .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
102 $result = $this->runWithPgEnv($sCreateDBCmd);
103 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
106 public function connect()
108 $this->oDB = new \Nominatim\DB();
109 $this->oDB->connect();
112 public function setupDB()
116 $fPostgresVersion = $this->oDB->getPostgresVersion();
117 echo 'Postgres version found: '.$fPostgresVersion."\n";
119 if ($fPostgresVersion < 9.03) {
120 fail('Minimum supported version of Postgresql is 9.3.');
123 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
124 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
126 $fPostgisVersion = $this->oDB->getPostgisVersion();
127 echo 'Postgis version found: '.$fPostgisVersion."\n";
129 if ($fPostgisVersion < 2.2) {
130 echo "Minimum required Postgis version 2.2\n";
134 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
136 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
137 echo "\n createuser ".CONST_Database_Web_User."\n\n";
141 // Try accessing the C module, so we know early if something is wrong
142 checkModulePresence(); // raises exception on failure
144 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
145 echo 'Error: you need to download the country_osm_grid first:';
146 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
149 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
150 $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
151 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
152 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
154 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
155 if (file_exists($sPostcodeFilename)) {
156 $this->pgsqlRunScriptFile($sPostcodeFilename);
158 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
161 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
162 if (file_exists($sPostcodeFilename)) {
163 $this->pgsqlRunScriptFile($sPostcodeFilename);
165 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
168 if ($this->bNoPartitions) {
169 $this->pgsqlRunScript('update country_name set partition = 0');
173 public function importData($sOSMFile)
177 $osm2pgsql = CONST_Osm2pgsql_Binary;
178 if (!file_exists($osm2pgsql)) {
179 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
180 echo "Normally you should not need to set this manually.\n";
181 fail("osm2pgsql not found in '$osm2pgsql'");
184 $osm2pgsql .= ' -S '.escapeshellarg(CONST_Import_Style);
186 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
187 $osm2pgsql .= ' --flat-nodes '.escapeshellarg(CONST_Osm2pgsql_Flatnode_File);
190 if (CONST_Tablespace_Osm2pgsql_Data)
191 $osm2pgsql .= ' --tablespace-slim-data '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Data);
192 if (CONST_Tablespace_Osm2pgsql_Index)
193 $osm2pgsql .= ' --tablespace-slim-index '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Index);
194 if (CONST_Tablespace_Place_Data)
195 $osm2pgsql .= ' --tablespace-main-data '.escapeshellarg(CONST_Tablespace_Place_Data);
196 if (CONST_Tablespace_Place_Index)
197 $osm2pgsql .= ' --tablespace-main-index '.escapeshellarg(CONST_Tablespace_Place_Index);
198 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
199 $osm2pgsql .= ' -C '.escapeshellarg($this->iCacheMemory);
200 $osm2pgsql .= ' -P '.escapeshellarg($this->aDSNInfo['port']);
201 if (isset($this->aDSNInfo['username'])) {
202 $osm2pgsql .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
204 if (isset($this->aDSNInfo['hostspec'])) {
205 $osm2pgsql .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
207 $osm2pgsql .= ' -d '.escapeshellarg($this->aDSNInfo['database']).' '.escapeshellarg($sOSMFile);
209 $this->runWithPgEnv($osm2pgsql);
211 if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
216 $this->dropTable('planet_osm_nodes');
217 $this->removeFlatnodeFile();
221 public function createFunctions()
223 info('Create Functions');
225 // Try accessing the C module, so we know early if something is wrong
226 checkModulePresence(); // raises exception on failure
228 $this->createSqlFunctions();
231 public function createTables($bReverseOnly = false)
233 info('Create Tables');
235 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
236 $sTemplate = $this->replaceSqlPatterns($sTemplate);
238 $this->pgsqlRunScript($sTemplate, false);
241 $this->dropTable('search_name');
244 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
245 $oAlParser->createTable($this->oDB, 'address_levels');
248 public function createTableTriggers()
250 info('Create Tables');
252 $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
253 $sTemplate = $this->replaceSqlPatterns($sTemplate);
255 $this->pgsqlRunScript($sTemplate, false);
258 public function createPartitionTables()
260 info('Create Partition Tables');
262 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
263 $sTemplate = $this->replaceSqlPatterns($sTemplate);
265 $this->pgsqlRunPartitionScript($sTemplate);
268 public function createPartitionFunctions()
270 info('Create Partition Functions');
272 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
273 $this->pgsqlRunPartitionScript($sTemplate);
276 public function importWikipediaArticles()
278 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
279 if (file_exists($sWikiArticlesFile)) {
280 info('Importing wikipedia articles and redirects');
281 $this->dropTable('wikipedia_article');
282 $this->dropTable('wikipedia_redirect');
283 $this->pgsqlRunScriptFile($sWikiArticlesFile);
285 warn('wikipedia importance dump file not found - places will have default importance');
289 public function loadData($bDisableTokenPrecalc)
291 info('Drop old Data');
293 $this->oDB->exec('TRUNCATE word');
295 $this->oDB->exec('TRUNCATE placex');
297 $this->oDB->exec('TRUNCATE location_property_osmline');
299 $this->oDB->exec('TRUNCATE place_addressline');
301 $this->oDB->exec('TRUNCATE location_area');
303 if (!$this->dbReverseOnly()) {
304 $this->oDB->exec('TRUNCATE search_name');
307 $this->oDB->exec('TRUNCATE search_name_blank');
309 $this->oDB->exec('DROP SEQUENCE seq_place');
311 $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
314 $sSQL = 'select distinct partition from country_name';
315 $aPartitions = $this->oDB->getCol($sSQL);
317 if (!$this->bNoPartitions) $aPartitions[] = 0;
318 foreach ($aPartitions as $sPartition) {
319 $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
323 // used by getorcreate_word_id to ignore frequent partial words
324 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
325 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
326 $this->oDB->exec($sSQL);
329 // pre-create the word list
330 if (!$bDisableTokenPrecalc) {
331 info('Loading word list');
332 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
336 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
338 $aDBInstances = array();
339 $iLoadThreads = max(1, $this->iInstances - 1);
340 for ($i = 0; $i < $iLoadThreads; $i++) {
341 // https://secure.php.net/manual/en/function.pg-connect.php
342 $DSN = CONST_Database_DSN;
343 $DSN = preg_replace('/^pgsql:/', '', $DSN);
344 $DSN = preg_replace('/;/', ' ', $DSN);
345 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
346 pg_ping($aDBInstances[$i]);
349 for ($i = 0; $i < $iLoadThreads; $i++) {
350 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
351 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
352 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
353 $sSQL .= ' and ST_IsValid(geometry)';
354 if ($this->bVerbose) echo "$sSQL\n";
355 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
356 fail(pg_last_error($aDBInstances[$i]));
360 // last thread for interpolation lines
361 // https://secure.php.net/manual/en/function.pg-connect.php
362 $DSN = CONST_Database_DSN;
363 $DSN = preg_replace('/^pgsql:/', '', $DSN);
364 $DSN = preg_replace('/;/', ' ', $DSN);
365 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
366 pg_ping($aDBInstances[$iLoadThreads]);
367 $sSQL = 'insert into location_property_osmline';
368 $sSQL .= ' (osm_id, address, linegeo)';
369 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
370 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
371 if ($this->bVerbose) echo "$sSQL\n";
372 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
373 fail(pg_last_error($aDBInstances[$iLoadThreads]));
377 for ($i = 0; $i <= $iLoadThreads; $i++) {
378 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
379 $resultStatus = pg_result_status($hPGresult);
380 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
381 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
382 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
383 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
384 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
385 $resultError = pg_result_error($hPGresult);
386 echo '-- error text ' . $i . ': ' . $resultError . "\n";
392 fail('SQL errors loading placex and/or location_property_osmline tables');
395 for ($i = 0; $i < $this->iInstances; $i++) {
396 pg_close($aDBInstances[$i]);
400 info('Reanalysing database');
401 $this->pgsqlRunScript('ANALYSE');
403 $sDatabaseDate = getDatabaseDate($this->oDB);
404 $this->oDB->exec('TRUNCATE import_status');
405 if (!$sDatabaseDate) {
406 warn('could not determine database date.');
408 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
409 $this->oDB->exec($sSQL);
410 echo "Latest data imported from $sDatabaseDate.\n";
414 public function importTigerData()
416 info('Import Tiger data');
418 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
419 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
420 if (empty($aFilenames)) return;
422 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
423 $sTemplate = $this->replaceSqlPatterns($sTemplate);
425 $this->pgsqlRunScript($sTemplate, false);
427 $aDBInstances = array();
428 for ($i = 0; $i < $this->iInstances; $i++) {
429 // https://secure.php.net/manual/en/function.pg-connect.php
430 $DSN = CONST_Database_DSN;
431 $DSN = preg_replace('/^pgsql:/', '', $DSN);
432 $DSN = preg_replace('/;/', ' ', $DSN);
433 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
434 pg_ping($aDBInstances[$i]);
437 foreach ($aFilenames as $sFile) {
439 $hFile = fopen($sFile, 'r');
440 $sSQL = fgets($hFile, 100000);
443 for ($i = 0; $i < $this->iInstances; $i++) {
444 if (!pg_connection_busy($aDBInstances[$i])) {
445 while (pg_get_result($aDBInstances[$i]));
446 $sSQL = fgets($hFile, 100000);
448 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
450 if ($iLines == 1000) {
463 for ($i = 0; $i < $this->iInstances; $i++) {
464 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
471 for ($i = 0; $i < $this->iInstances; $i++) {
472 pg_close($aDBInstances[$i]);
475 info('Creating indexes on Tiger data');
476 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
477 $sTemplate = $this->replaceSqlPatterns($sTemplate);
479 $this->pgsqlRunScript($sTemplate, false);
482 public function calculatePostcodes($bCMDResultAll)
484 info('Calculate Postcodes');
485 $this->oDB->exec('TRUNCATE location_postcode');
487 $sSQL = 'INSERT INTO location_postcode';
488 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
489 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
490 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
491 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
492 $sSQL .= ' FROM placex';
493 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
494 $sSQL .= ' AND geometry IS NOT null';
495 $sSQL .= ' GROUP BY country_code, pc';
496 $this->oDB->exec($sSQL);
498 // only add postcodes that are not yet available in OSM
499 $sSQL = 'INSERT INTO location_postcode';
500 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
501 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
502 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
503 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
504 $sSQL .= ' (SELECT postcode FROM location_postcode';
505 $sSQL .= " WHERE country_code = 'us')";
506 $this->oDB->exec($sSQL);
508 // add missing postcodes for GB (if available)
509 $sSQL = 'INSERT INTO location_postcode';
510 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
511 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
512 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
513 $sSQL .= ' (SELECT postcode FROM location_postcode';
514 $sSQL .= " WHERE country_code = 'gb')";
515 $this->oDB->exec($sSQL);
517 if (!$bCMDResultAll) {
518 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
519 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
520 $this->oDB->exec($sSQL);
523 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
524 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
525 $this->oDB->exec($sSQL);
528 public function index($bIndexNoanalyse)
531 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim.py'
532 .' -d '.escapeshellarg($this->aDSNInfo['database'])
533 .' -P '.escapeshellarg($this->aDSNInfo['port'])
534 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
535 if (!$this->bQuiet) {
538 if ($this->bVerbose) {
541 if (isset($this->aDSNInfo['hostspec'])) {
542 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
544 if (isset($this->aDSNInfo['username'])) {
545 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
548 info('Index ranks 0 - 4');
549 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
551 fail('error status ' . $iStatus . ' running nominatim!');
553 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
555 info('Index ranks 5 - 25');
556 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
558 fail('error status ' . $iStatus . ' running nominatim!');
560 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
562 info('Index ranks 26 - 30');
563 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
565 fail('error status ' . $iStatus . ' running nominatim!');
568 info('Index postcodes');
569 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
570 $this->oDB->exec($sSQL);
573 public function createSearchIndices()
575 info('Create Search indices');
577 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
578 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
579 $aInvalidIndices = $this->oDB->getCol($sSQL);
581 foreach ($aInvalidIndices as $sIndexName) {
582 info("Cleaning up invalid index $sIndexName");
583 $this->oDB->exec("DROP INDEX $sIndexName;");
586 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
588 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
590 if (!$this->dbReverseOnly()) {
591 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
593 $sTemplate = $this->replaceSqlPatterns($sTemplate);
595 $this->pgsqlRunScript($sTemplate);
598 public function createCountryNames()
600 info('Create search index for default country names');
602 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
603 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
604 $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');
605 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
606 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
607 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
608 if (CONST_Languages) {
611 foreach (explode(',', CONST_Languages) as $sLang) {
612 $sSQL .= $sDelim."'name:$sLang'";
617 // all include all simple name tags
618 $sSQL .= "like 'name:%'";
621 $this->pgsqlRunScript($sSQL);
624 public function drop()
626 info('Drop tables only required for updates');
628 // The implementation is potentially a bit dangerous because it uses
629 // a positive selection of tables to keep, and deletes everything else.
630 // Including any tables that the unsuspecting user might have manually
631 // created. USE AT YOUR OWN PERIL.
632 // tables we want to keep. everything else goes.
633 $aKeepTables = array(
639 'location_property*',
652 $aDropTables = array();
653 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
655 foreach ($aHaveTables as $sTable) {
657 foreach ($aKeepTables as $sKeep) {
658 if (fnmatch($sKeep, $sTable)) {
663 if (!$bFound) array_push($aDropTables, $sTable);
665 foreach ($aDropTables as $sDrop) {
666 $this->dropTable($sDrop);
669 $this->removeFlatnodeFile();
672 private function removeFlatnodeFile()
674 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
675 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
676 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
677 unlink(CONST_Osm2pgsql_Flatnode_File);
682 private function pgsqlRunScript($sScript, $bfatal = true)
692 private function createSqlFunctions()
694 $sBasePath = CONST_BasePath.'/sql/functions/';
695 $sTemplate = file_get_contents($sBasePath.'utils.sql');
696 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
697 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
698 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
699 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
700 if ($this->oDB->tableExists('place')) {
701 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
703 if ($this->oDB->tableExists('placex')) {
704 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
706 if ($this->oDB->tableExists('location_postcode')) {
707 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
709 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
710 if ($this->bEnableDiffUpdates) {
711 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
713 if ($this->bEnableDebugStatements) {
714 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
716 if (CONST_Limit_Reindexing) {
717 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
719 if (!CONST_Use_US_Tiger_Data) {
720 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
722 if (!CONST_Use_Aux_Location_data) {
723 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
726 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
727 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
729 $this->pgsqlRunScript($sTemplate);
732 private function pgsqlRunPartitionScript($sTemplate)
734 $sSQL = 'select distinct partition from country_name';
735 $aPartitions = $this->oDB->getCol($sSQL);
736 if (!$this->bNoPartitions) $aPartitions[] = 0;
738 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
739 foreach ($aMatches as $aMatch) {
741 foreach ($aPartitions as $sPartitionName) {
742 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
744 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
747 $this->pgsqlRunScript($sTemplate);
750 private function pgsqlRunScriptFile($sFilename)
752 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
755 .' -p '.escapeshellarg($this->aDSNInfo['port'])
756 .' -d '.escapeshellarg($this->aDSNInfo['database']);
757 if (!$this->bVerbose) {
760 if (isset($this->aDSNInfo['hostspec'])) {
761 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
763 if (isset($this->aDSNInfo['username'])) {
764 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
767 if (isset($this->aDSNInfo['password'])) {
768 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
771 if (preg_match('/\\.gz$/', $sFilename)) {
772 $aDescriptors = array(
773 0 => array('pipe', 'r'),
774 1 => array('pipe', 'w'),
775 2 => array('file', '/dev/null', 'a')
777 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
778 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
779 $aReadPipe = $ahGzipPipes[1];
780 fclose($ahGzipPipes[0]);
782 $sCMD .= ' -f '.escapeshellarg($sFilename);
783 $aReadPipe = array('pipe', 'r');
785 $aDescriptors = array(
787 1 => array('pipe', 'w'),
788 2 => array('file', '/dev/null', 'a')
791 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
792 if (!is_resource($hProcess)) fail('unable to start pgsql');
793 // TODO: error checking
794 while (!feof($ahPipes[1])) {
795 echo fread($ahPipes[1], 4096);
798 $iReturn = proc_close($hProcess);
800 fail("pgsql returned with error code ($iReturn)");
803 fclose($ahGzipPipes[1]);
804 proc_close($hGzipProcess);
808 private function replaceSqlPatterns($sSql)
810 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
813 '{ts:address-data}' => CONST_Tablespace_Address_Data,
814 '{ts:address-index}' => CONST_Tablespace_Address_Index,
815 '{ts:search-data}' => CONST_Tablespace_Search_Data,
816 '{ts:search-index}' => CONST_Tablespace_Search_Index,
817 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
818 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
821 foreach ($aPatterns as $sPattern => $sTablespace) {
823 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
825 $sSql = str_replace($sPattern, '', $sSql);
832 private function runWithPgEnv($sCmd)
834 if ($this->bVerbose) {
835 echo "Execute: $sCmd\n";
840 if (isset($this->aDSNInfo['password'])) {
841 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
844 return runWithEnv($sCmd, $aProcEnv);
848 * Drop table with the given name if it exists.
850 * @param string $sName Name of table to remove.
854 * @pre connect() must have been called.
856 private function dropTable($sName)
858 if ($this->bVerbose) echo "Dropping table $sName\n";
859 $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
863 * Check if the database is in reverse-only mode.
865 * @return True if there is no search_name table and infrastructure.
867 private function dbReverseOnly()
869 return !($this->oDB->tableExists('search_name'));