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)) {
421 warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
424 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
425 $sTemplate = $this->replaceSqlPatterns($sTemplate);
427 $this->pgsqlRunScript($sTemplate, false);
429 $aDBInstances = array();
430 for ($i = 0; $i < $this->iInstances; $i++) {
431 // https://secure.php.net/manual/en/function.pg-connect.php
432 $DSN = CONST_Database_DSN;
433 $DSN = preg_replace('/^pgsql:/', '', $DSN);
434 $DSN = preg_replace('/;/', ' ', $DSN);
435 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
436 pg_ping($aDBInstances[$i]);
439 foreach ($aFilenames as $sFile) {
441 $hFile = fopen($sFile, 'r');
442 $sSQL = fgets($hFile, 100000);
445 for ($i = 0; $i < $this->iInstances; $i++) {
446 if (!pg_connection_busy($aDBInstances[$i])) {
447 while (pg_get_result($aDBInstances[$i]));
448 $sSQL = fgets($hFile, 100000);
450 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
452 if ($iLines == 1000) {
465 for ($i = 0; $i < $this->iInstances; $i++) {
466 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
473 for ($i = 0; $i < $this->iInstances; $i++) {
474 pg_close($aDBInstances[$i]);
477 info('Creating indexes on Tiger data');
478 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
479 $sTemplate = $this->replaceSqlPatterns($sTemplate);
481 $this->pgsqlRunScript($sTemplate, false);
484 public function calculatePostcodes($bCMDResultAll)
486 info('Calculate Postcodes');
487 $this->oDB->exec('TRUNCATE location_postcode');
489 $sSQL = 'INSERT INTO location_postcode';
490 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
491 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
492 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
493 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
494 $sSQL .= ' FROM placex';
495 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
496 $sSQL .= ' AND geometry IS NOT null';
497 $sSQL .= ' GROUP BY country_code, pc';
498 $this->oDB->exec($sSQL);
500 // only add postcodes that are not yet available in OSM
501 $sSQL = 'INSERT INTO location_postcode';
502 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
503 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
504 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
505 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
506 $sSQL .= ' (SELECT postcode FROM location_postcode';
507 $sSQL .= " WHERE country_code = 'us')";
508 $this->oDB->exec($sSQL);
510 // add missing postcodes for GB (if available)
511 $sSQL = 'INSERT INTO location_postcode';
512 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
513 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
514 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
515 $sSQL .= ' (SELECT postcode FROM location_postcode';
516 $sSQL .= " WHERE country_code = 'gb')";
517 $this->oDB->exec($sSQL);
519 if (!$bCMDResultAll) {
520 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
521 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
522 $this->oDB->exec($sSQL);
525 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
526 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
527 $this->oDB->exec($sSQL);
530 public function index($bIndexNoanalyse)
533 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim.py'
534 .' -d '.escapeshellarg($this->aDSNInfo['database'])
535 .' -P '.escapeshellarg($this->aDSNInfo['port'])
536 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
537 if (!$this->bQuiet) {
540 if ($this->bVerbose) {
543 if (isset($this->aDSNInfo['hostspec'])) {
544 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
546 if (isset($this->aDSNInfo['username'])) {
547 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
550 info('Index ranks 0 - 4');
551 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
553 fail('error status ' . $iStatus . ' running nominatim!');
555 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
557 info('Index ranks 5 - 25');
558 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
560 fail('error status ' . $iStatus . ' running nominatim!');
562 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
564 info('Index ranks 26 - 30');
565 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
567 fail('error status ' . $iStatus . ' running nominatim!');
570 info('Index postcodes');
571 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
572 $this->oDB->exec($sSQL);
575 public function createSearchIndices()
577 info('Create Search indices');
579 $sSQL = 'SELECT relname FROM pg_class, pg_index ';
580 $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
581 $aInvalidIndices = $this->oDB->getCol($sSQL);
583 foreach ($aInvalidIndices as $sIndexName) {
584 info("Cleaning up invalid index $sIndexName");
585 $this->oDB->exec("DROP INDEX $sIndexName;");
588 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
590 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
592 if (!$this->dbReverseOnly()) {
593 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
595 $sTemplate = $this->replaceSqlPatterns($sTemplate);
597 $this->pgsqlRunScript($sTemplate);
600 public function createCountryNames()
602 info('Create search index for default country names');
604 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
605 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
606 $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');
607 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
608 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
609 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
610 if (CONST_Languages) {
613 foreach (explode(',', CONST_Languages) as $sLang) {
614 $sSQL .= $sDelim."'name:$sLang'";
619 // all include all simple name tags
620 $sSQL .= "like 'name:%'";
623 $this->pgsqlRunScript($sSQL);
626 public function drop()
628 info('Drop tables only required for updates');
630 // The implementation is potentially a bit dangerous because it uses
631 // a positive selection of tables to keep, and deletes everything else.
632 // Including any tables that the unsuspecting user might have manually
633 // created. USE AT YOUR OWN PERIL.
634 // tables we want to keep. everything else goes.
635 $aKeepTables = array(
641 'location_property*',
654 $aDropTables = array();
655 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
657 foreach ($aHaveTables as $sTable) {
659 foreach ($aKeepTables as $sKeep) {
660 if (fnmatch($sKeep, $sTable)) {
665 if (!$bFound) array_push($aDropTables, $sTable);
667 foreach ($aDropTables as $sDrop) {
668 $this->dropTable($sDrop);
671 $this->removeFlatnodeFile();
674 private function removeFlatnodeFile()
676 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
677 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
678 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
679 unlink(CONST_Osm2pgsql_Flatnode_File);
684 private function pgsqlRunScript($sScript, $bfatal = true)
694 private function createSqlFunctions()
696 $sBasePath = CONST_BasePath.'/sql/functions/';
697 $sTemplate = file_get_contents($sBasePath.'utils.sql');
698 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
699 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
700 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
701 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
702 if ($this->oDB->tableExists('place')) {
703 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
705 if ($this->oDB->tableExists('placex')) {
706 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
708 if ($this->oDB->tableExists('location_postcode')) {
709 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
711 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
712 if ($this->bEnableDiffUpdates) {
713 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
715 if ($this->bEnableDebugStatements) {
716 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
718 if (CONST_Limit_Reindexing) {
719 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
721 if (!CONST_Use_US_Tiger_Data) {
722 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
724 if (!CONST_Use_Aux_Location_data) {
725 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
728 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
729 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
731 $this->pgsqlRunScript($sTemplate);
734 private function pgsqlRunPartitionScript($sTemplate)
736 $sSQL = 'select distinct partition from country_name';
737 $aPartitions = $this->oDB->getCol($sSQL);
738 if (!$this->bNoPartitions) $aPartitions[] = 0;
740 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
741 foreach ($aMatches as $aMatch) {
743 foreach ($aPartitions as $sPartitionName) {
744 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
746 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
749 $this->pgsqlRunScript($sTemplate);
752 private function pgsqlRunScriptFile($sFilename)
754 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
757 .' -p '.escapeshellarg($this->aDSNInfo['port'])
758 .' -d '.escapeshellarg($this->aDSNInfo['database']);
759 if (!$this->bVerbose) {
762 if (isset($this->aDSNInfo['hostspec'])) {
763 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
765 if (isset($this->aDSNInfo['username'])) {
766 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
769 if (isset($this->aDSNInfo['password'])) {
770 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
773 if (preg_match('/\\.gz$/', $sFilename)) {
774 $aDescriptors = array(
775 0 => array('pipe', 'r'),
776 1 => array('pipe', 'w'),
777 2 => array('file', '/dev/null', 'a')
779 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
780 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
781 $aReadPipe = $ahGzipPipes[1];
782 fclose($ahGzipPipes[0]);
784 $sCMD .= ' -f '.escapeshellarg($sFilename);
785 $aReadPipe = array('pipe', 'r');
787 $aDescriptors = array(
789 1 => array('pipe', 'w'),
790 2 => array('file', '/dev/null', 'a')
793 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
794 if (!is_resource($hProcess)) fail('unable to start pgsql');
795 // TODO: error checking
796 while (!feof($ahPipes[1])) {
797 echo fread($ahPipes[1], 4096);
800 $iReturn = proc_close($hProcess);
802 fail("pgsql returned with error code ($iReturn)");
805 fclose($ahGzipPipes[1]);
806 proc_close($hGzipProcess);
810 private function replaceSqlPatterns($sSql)
812 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
815 '{ts:address-data}' => CONST_Tablespace_Address_Data,
816 '{ts:address-index}' => CONST_Tablespace_Address_Index,
817 '{ts:search-data}' => CONST_Tablespace_Search_Data,
818 '{ts:search-index}' => CONST_Tablespace_Search_Index,
819 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
820 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
823 foreach ($aPatterns as $sPattern => $sTablespace) {
825 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
827 $sSql = str_replace($sPattern, '', $sSql);
834 private function runWithPgEnv($sCmd)
836 if ($this->bVerbose) {
837 echo "Execute: $sCmd\n";
842 if (isset($this->aDSNInfo['password'])) {
843 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
846 return runWithEnv($sCmd, $aProcEnv);
850 * Drop table with the given name if it exists.
852 * @param string $sName Name of table to remove.
856 * @pre connect() must have been called.
858 private function dropTable($sName)
860 if ($this->bVerbose) echo "Dropping table $sName\n";
861 $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
865 * Check if the database is in reverse-only mode.
867 * @return True if there is no search_name table and infrastructure.
869 private function dbReverseOnly()
871 return !($this->oDB->tableExists('search_name'));