3 namespace Nominatim\Setup;
5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
9 protected $iCacheMemory;
10 protected $iInstances;
11 protected $sModulePath;
14 protected $sIgnoreErrors;
15 protected $bEnableDiffUpdates;
16 protected $bEnableDebugStatements;
17 protected $bNoPartitions;
18 protected $oDB = null;
20 public function __construct(array $aCMDResult)
22 // by default, use all but one processor, but never more than 15.
23 $this->iInstances = isset($aCMDResult['threads'])
24 ? $aCMDResult['threads']
25 : (min(16, getProcessorCount()) - 1);
27 if ($this->iInstances < 1) {
28 $this->iInstances = 1;
29 warn('resetting threads to '.$this->iInstances);
32 // Assume we can steal all the cache memory in the box (unless told otherwise)
33 if (isset($aCMDResult['osm2pgsql-cache'])) {
34 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
36 $this->iCacheMemory = getCacheMemoryMB();
39 $this->sModulePath = CONST_Database_Module_Path;
40 info('module path: ' . $this->sModulePath);
42 // parse database string
43 $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
44 if (!isset($this->aDSNInfo['port'])) {
45 $this->aDSNInfo['port'] = 5432;
48 // setting member variables based on command line options stored in $aCMDResult
49 $this->bVerbose = $aCMDResult['verbose'];
51 //setting default values which are not set by the update.php array
52 if (isset($aCMDResult['ignore-errors'])) {
53 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
55 $this->sIgnoreErrors = false;
57 if (isset($aCMDResult['enable-debug-statements'])) {
58 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
60 $this->bEnableDebugStatements = false;
62 if (isset($aCMDResult['no-partitions'])) {
63 $this->bNoPartitions = $aCMDResult['no-partitions'];
65 $this->bNoPartitions = false;
67 if (isset($aCMDResult['enable-diff-updates'])) {
68 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
70 $this->bEnableDiffUpdates = false;
74 public function createDB()
79 $oDB = new \Nominatim\DB;
81 } catch (\Nominatim\DatabaseError $e) {
86 fail('database already exists ('.CONST_Database_DSN.')');
89 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
90 if (isset($this->aDSNInfo['username'])) {
91 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
94 if (isset($this->aDSNInfo['hostspec'])) {
95 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
98 $result = $this->runWithPgEnv($sCreateDBCmd);
99 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
102 public function connect()
104 $this->oDB = new \Nominatim\DB();
105 $this->oDB->connect();
108 public function setupDB()
112 $fPostgresVersion = $this->oDB->getPostgresVersion();
113 echo 'Postgres version found: '.$fPostgresVersion."\n";
115 if ($fPostgresVersion < 9.01) {
116 fail('Minimum supported version of Postgresql is 9.1.');
119 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
120 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
122 // For extratags and namedetails the hstore_to_json converter is
123 // needed which is only available from Postgresql 9.3+. For older
124 // versions add a dummy function that returns nothing.
125 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
127 if ($iNumFunc == 0) {
128 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
129 warn('Postgresql is too old. extratags and namedetails API not available.');
133 $fPostgisVersion = $this->oDB->getPostgisVersion();
134 echo 'Postgis version found: '.$fPostgisVersion."\n";
136 if ($fPostgisVersion < 2.1) {
137 // Functions were renamed in 2.1 and throw an annoying deprecation warning
138 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
139 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
141 if ($fPostgisVersion < 2.2) {
142 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
145 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
147 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
148 echo "\n createuser ".CONST_Database_Web_User."\n\n";
152 // Try accessing the C module, so we know early if something is wrong
153 if (!checkModulePresence()) {
154 fail('error loading nominatim.so module');
157 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
158 echo 'Error: you need to download the country_osm_grid first:';
159 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
162 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
163 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
164 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
166 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
167 if (file_exists($sPostcodeFilename)) {
168 $this->pgsqlRunScriptFile($sPostcodeFilename);
170 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
173 if (CONST_Use_Extra_US_Postcodes) {
174 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
177 if ($this->bNoPartitions) {
178 $this->pgsqlRunScript('update country_name set partition = 0');
181 // the following will be needed by createFunctions later but
182 // is only defined in the subsequently called createTables
183 // Create dummies here that will be overwritten by the proper
184 // versions in create-tables.
185 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
186 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
189 public function importData($sOSMFile)
193 $osm2pgsql = CONST_Osm2pgsql_Binary;
194 if (!file_exists($osm2pgsql)) {
195 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
196 echo "Normally you should not need to set this manually.\n";
197 fail("osm2pgsql not found in '$osm2pgsql'");
200 $osm2pgsql .= ' -S '.CONST_Import_Style;
202 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
203 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
206 if (CONST_Tablespace_Osm2pgsql_Data)
207 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
208 if (CONST_Tablespace_Osm2pgsql_Index)
209 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
210 if (CONST_Tablespace_Place_Data)
211 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
212 if (CONST_Tablespace_Place_Index)
213 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
214 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
215 $osm2pgsql .= ' -C '.$this->iCacheMemory;
216 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
217 if (isset($this->aDSNInfo['username'])) {
218 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
220 if (isset($this->aDSNInfo['hostspec'])) {
221 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
223 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
225 $this->runWithPgEnv($osm2pgsql);
227 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
232 public function createFunctions()
234 info('Create Functions');
236 // Try accessing the C module, so we know eif something is wrong
237 // update.php calls this function
238 if (!checkModulePresence()) {
239 fail('error loading nominatim.so module');
241 $this->createSqlFunctions();
244 public function createTables($bReverseOnly = false)
246 info('Create Tables');
248 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
249 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
250 $sTemplate = $this->replaceTablespace(
252 CONST_Tablespace_Address_Data,
255 $sTemplate = $this->replaceTablespace(
256 '{ts:address-index}',
257 CONST_Tablespace_Address_Index,
260 $sTemplate = $this->replaceTablespace(
262 CONST_Tablespace_Search_Data,
265 $sTemplate = $this->replaceTablespace(
267 CONST_Tablespace_Search_Index,
270 $sTemplate = $this->replaceTablespace(
272 CONST_Tablespace_Aux_Data,
275 $sTemplate = $this->replaceTablespace(
277 CONST_Tablespace_Aux_Index,
281 $this->pgsqlRunScript($sTemplate, false);
284 $this->pgExec('DROP TABLE search_name');
287 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
288 $oAlParser->createTable($this->oDB, 'address_levels');
291 public function createPartitionTables()
293 info('Create Partition Tables');
295 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
296 $sTemplate = $this->replaceTablespace(
298 CONST_Tablespace_Address_Data,
302 $sTemplate = $this->replaceTablespace(
303 '{ts:address-index}',
304 CONST_Tablespace_Address_Index,
308 $sTemplate = $this->replaceTablespace(
310 CONST_Tablespace_Search_Data,
314 $sTemplate = $this->replaceTablespace(
316 CONST_Tablespace_Search_Index,
320 $sTemplate = $this->replaceTablespace(
322 CONST_Tablespace_Aux_Data,
326 $sTemplate = $this->replaceTablespace(
328 CONST_Tablespace_Aux_Index,
332 $this->pgsqlRunPartitionScript($sTemplate);
335 public function createPartitionFunctions()
337 info('Create Partition Functions');
339 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
340 $this->pgsqlRunPartitionScript($sTemplate);
343 public function importWikipediaArticles()
345 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
346 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
347 if (file_exists($sWikiArticlesFile)) {
348 info('Importing wikipedia articles');
349 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
351 warn('wikipedia article dump file not found - places will have default importance');
353 if (file_exists($sWikiRedirectsFile)) {
354 info('Importing wikipedia redirects');
355 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
357 warn('wikipedia redirect dump file not found - some place importance values may be missing');
361 public function loadData($bDisableTokenPrecalc)
363 info('Drop old Data');
365 $this->pgExec('TRUNCATE word');
367 $this->pgExec('TRUNCATE placex');
369 $this->pgExec('TRUNCATE location_property_osmline');
371 $this->pgExec('TRUNCATE place_addressline');
373 $this->pgExec('TRUNCATE place_boundingbox');
375 $this->pgExec('TRUNCATE location_area');
377 if (!$this->dbReverseOnly()) {
378 $this->pgExec('TRUNCATE search_name');
381 $this->pgExec('TRUNCATE search_name_blank');
383 $this->pgExec('DROP SEQUENCE seq_place');
385 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
388 $sSQL = 'select distinct partition from country_name';
389 $aPartitions = chksql($this->oDB->getCol($sSQL));
391 if (!$this->bNoPartitions) $aPartitions[] = 0;
392 foreach ($aPartitions as $sPartition) {
393 $this->pgExec('TRUNCATE location_road_'.$sPartition);
397 // used by getorcreate_word_id to ignore frequent partial words
398 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
399 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
400 $this->pgExec($sSQL);
403 // pre-create the word list
404 if (!$bDisableTokenPrecalc) {
405 info('Loading word list');
406 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
410 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
412 $aDBInstances = array();
413 $iLoadThreads = max(1, $this->iInstances - 1);
414 for ($i = 0; $i < $iLoadThreads; $i++) {
415 // https://secure.php.net/manual/en/function.pg-connect.php
416 $DSN = CONST_Database_DSN;
417 $DSN = preg_replace('/^pgsql:/', '', $DSN);
418 $DSN = preg_replace('/;/', ' ', $DSN);
419 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
420 pg_ping($aDBInstances[$i]);
423 for ($i = 0; $i < $iLoadThreads; $i++) {
424 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
425 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
426 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
427 $sSQL .= ' and ST_IsValid(geometry)';
428 if ($this->bVerbose) echo "$sSQL\n";
429 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
430 fail(pg_last_error($aDBInstances[$i]));
434 // last thread for interpolation lines
435 // https://secure.php.net/manual/en/function.pg-connect.php
436 $DSN = CONST_Database_DSN;
437 $DSN = preg_replace('/^pgsql:/', '', $DSN);
438 $DSN = preg_replace('/;/', ' ', $DSN);
439 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
440 pg_ping($aDBInstances[$iLoadThreads]);
441 $sSQL = 'insert into location_property_osmline';
442 $sSQL .= ' (osm_id, address, linegeo)';
443 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
444 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
445 if ($this->bVerbose) echo "$sSQL\n";
446 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
447 fail(pg_last_error($aDBInstances[$iLoadThreads]));
451 for ($i = 0; $i <= $iLoadThreads; $i++) {
452 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
453 $resultStatus = pg_result_status($hPGresult);
454 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
455 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
456 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
457 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
458 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
459 $resultError = pg_result_error($hPGresult);
460 echo '-- error text ' . $i . ': ' . $resultError . "\n";
466 fail('SQL errors loading placex and/or location_property_osmline tables');
469 for ($i = 0; $i < $this->iInstances; $i++) {
470 pg_close($aDBInstances[$i]);
474 info('Reanalysing database');
475 $this->pgsqlRunScript('ANALYSE');
477 $sDatabaseDate = getDatabaseDate($this->oDB);
478 $this->oDB->exec('TRUNCATE import_status');
479 if (!$sDatabaseDate) {
480 warn('could not determine database date.');
482 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
483 $this->oDB->exec($sSQL);
484 echo "Latest data imported from $sDatabaseDate.\n";
488 public function importTigerData()
490 info('Import Tiger data');
492 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
493 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
494 $sTemplate = $this->replaceTablespace(
496 CONST_Tablespace_Aux_Data,
499 $sTemplate = $this->replaceTablespace(
501 CONST_Tablespace_Aux_Index,
504 $this->pgsqlRunScript($sTemplate, false);
506 $aDBInstances = array();
507 for ($i = 0; $i < $this->iInstances; $i++) {
508 // https://secure.php.net/manual/en/function.pg-connect.php
509 $DSN = CONST_Database_DSN;
510 $DSN = preg_replace('/^pgsql:/', '', $DSN);
511 $DSN = preg_replace('/;/', ' ', $DSN);
512 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
513 pg_ping($aDBInstances[$i]);
516 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
518 $hFile = fopen($sFile, 'r');
519 $sSQL = fgets($hFile, 100000);
522 for ($i = 0; $i < $this->iInstances; $i++) {
523 if (!pg_connection_busy($aDBInstances[$i])) {
524 while (pg_get_result($aDBInstances[$i]));
525 $sSQL = fgets($hFile, 100000);
527 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
529 if ($iLines == 1000) {
542 for ($i = 0; $i < $this->iInstances; $i++) {
543 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
550 for ($i = 0; $i < $this->iInstances; $i++) {
551 pg_close($aDBInstances[$i]);
554 info('Creating indexes on Tiger data');
555 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
556 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
557 $sTemplate = $this->replaceTablespace(
559 CONST_Tablespace_Aux_Data,
562 $sTemplate = $this->replaceTablespace(
564 CONST_Tablespace_Aux_Index,
567 $this->pgsqlRunScript($sTemplate, false);
570 public function calculatePostcodes($bCMDResultAll)
572 info('Calculate Postcodes');
573 $this->pgExec('TRUNCATE location_postcode');
575 $sSQL = 'INSERT INTO location_postcode';
576 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
577 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
578 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
579 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
580 $sSQL .= ' FROM placex';
581 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
582 $sSQL .= ' AND geometry IS NOT null';
583 $sSQL .= ' GROUP BY country_code, pc';
584 $this->pgExec($sSQL);
586 if (CONST_Use_Extra_US_Postcodes) {
587 // only add postcodes that are not yet available in OSM
588 $sSQL = 'INSERT INTO location_postcode';
589 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
590 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
591 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
592 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
593 $sSQL .= ' (SELECT postcode FROM location_postcode';
594 $sSQL .= " WHERE country_code = 'us')";
595 $this->pgExec($sSQL);
598 // add missing postcodes for GB (if available)
599 $sSQL = 'INSERT INTO location_postcode';
600 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
601 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
602 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
603 $sSQL .= ' (SELECT postcode FROM location_postcode';
604 $sSQL .= " WHERE country_code = 'gb')";
605 $this->pgExec($sSQL);
607 if (!$bCMDResultAll) {
608 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
609 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
610 $this->pgExec($sSQL);
613 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
614 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
615 $this->pgExec($sSQL);
618 public function index($bIndexNoanalyse)
621 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
622 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
623 if (isset($this->aDSNInfo['hostspec'])) {
624 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
626 if (isset($this->aDSNInfo['username'])) {
627 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
630 info('Index ranks 0 - 4');
631 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
633 fail('error status ' . $iStatus . ' running nominatim!');
635 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
637 info('Index ranks 5 - 25');
638 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
640 fail('error status ' . $iStatus . ' running nominatim!');
642 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
644 info('Index ranks 26 - 30');
645 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
647 fail('error status ' . $iStatus . ' running nominatim!');
650 info('Index postcodes');
651 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
652 $this->pgExec($sSQL);
655 public function createSearchIndices()
657 info('Create Search indices');
659 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
660 if (!$this->dbReverseOnly()) {
661 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
663 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
664 $sTemplate = $this->replaceTablespace(
665 '{ts:address-index}',
666 CONST_Tablespace_Address_Index,
669 $sTemplate = $this->replaceTablespace(
671 CONST_Tablespace_Search_Index,
674 $sTemplate = $this->replaceTablespace(
676 CONST_Tablespace_Aux_Index,
679 $this->pgsqlRunScript($sTemplate);
682 public function createCountryNames()
684 info('Create search index for default country names');
686 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
687 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
688 $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');
689 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
690 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
691 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
692 if (CONST_Languages) {
695 foreach (explode(',', CONST_Languages) as $sLang) {
696 $sSQL .= $sDelim."'name:$sLang'";
701 // all include all simple name tags
702 $sSQL .= "like 'name:%'";
705 $this->pgsqlRunScript($sSQL);
708 public function drop()
710 info('Drop tables only required for updates');
712 // The implementation is potentially a bit dangerous because it uses
713 // a positive selection of tables to keep, and deletes everything else.
714 // Including any tables that the unsuspecting user might have manually
715 // created. USE AT YOUR OWN PERIL.
716 // tables we want to keep. everything else goes.
717 $aKeepTables = array(
723 'location_property*',
736 $aDropTables = array();
737 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
739 foreach ($aHaveTables as $sTable) {
741 foreach ($aKeepTables as $sKeep) {
742 if (fnmatch($sKeep, $sTable)) {
747 if (!$bFound) array_push($aDropTables, $sTable);
749 foreach ($aDropTables as $sDrop) {
750 if ($this->bVerbose) echo "Dropping table $sDrop\n";
751 $this->oDB->exec("DROP TABLE $sDrop CASCADE");
752 // ignore warnings/errors as they might be caused by a table having
753 // been deleted already by CASCADE
756 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
757 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
758 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
759 unlink(CONST_Osm2pgsql_Flatnode_File);
764 private function pgsqlRunDropAndRestore($sDumpFile)
766 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
767 if (isset($this->aDSNInfo['hostspec'])) {
768 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
770 if (isset($this->aDSNInfo['username'])) {
771 $sCMD .= ' -U '.$this->aDSNInfo['username'];
774 $this->runWithPgEnv($sCMD);
777 private function pgsqlRunScript($sScript, $bfatal = true)
787 private function createSqlFunctions()
789 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
790 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
791 if ($this->bEnableDiffUpdates) {
792 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
794 if ($this->bEnableDebugStatements) {
795 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
797 if (CONST_Limit_Reindexing) {
798 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
800 if (!CONST_Use_US_Tiger_Data) {
801 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
803 if (!CONST_Use_Aux_Location_data) {
804 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
807 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
808 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
810 $this->pgsqlRunScript($sTemplate);
813 private function pgsqlRunPartitionScript($sTemplate)
815 $sSQL = 'select distinct partition from country_name';
816 $aPartitions = $this->oDB->getCol($sSQL);
817 if (!$this->bNoPartitions) $aPartitions[] = 0;
819 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
820 foreach ($aMatches as $aMatch) {
822 foreach ($aPartitions as $sPartitionName) {
823 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
825 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
828 $this->pgsqlRunScript($sTemplate);
831 private function pgsqlRunScriptFile($sFilename)
833 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
835 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
836 if (!$this->bVerbose) {
839 if (isset($this->aDSNInfo['hostspec'])) {
840 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
842 if (isset($this->aDSNInfo['username'])) {
843 $sCMD .= ' -U '.$this->aDSNInfo['username'];
846 if (isset($this->aDSNInfo['password'])) {
847 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
850 if (preg_match('/\\.gz$/', $sFilename)) {
851 $aDescriptors = array(
852 0 => array('pipe', 'r'),
853 1 => array('pipe', 'w'),
854 2 => array('file', '/dev/null', 'a')
856 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
857 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
858 $aReadPipe = $ahGzipPipes[1];
859 fclose($ahGzipPipes[0]);
861 $sCMD .= ' -f '.$sFilename;
862 $aReadPipe = array('pipe', 'r');
864 $aDescriptors = array(
866 1 => array('pipe', 'w'),
867 2 => array('file', '/dev/null', 'a')
870 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
871 if (!is_resource($hProcess)) fail('unable to start pgsql');
872 // TODO: error checking
873 while (!feof($ahPipes[1])) {
874 echo fread($ahPipes[1], 4096);
877 $iReturn = proc_close($hProcess);
879 fail("pgsql returned with error code ($iReturn)");
882 fclose($ahGzipPipes[1]);
883 proc_close($hGzipProcess);
887 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
890 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
892 $sSql = str_replace($sTemplate, '', $sSql);
897 private function runWithPgEnv($sCmd)
899 if ($this->bVerbose) {
900 echo "Execute: $sCmd\n";
905 if (isset($this->aDSNInfo['password'])) {
906 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
909 return runWithEnv($sCmd, $aProcEnv);
913 * Execute the SQL command on the open database.
915 * @param string $sSQL SQL command to execute.
919 * @pre connect() must have been called.
921 private function pgExec($sSQL)
923 $this->oDB->exec($sSQL);
927 * Check if the database is in reverse-only mode.
929 * @return True if there is no search_name table and infrastructure.
931 private function dbReverseOnly()
933 return !($this->oDB->tableExists('search_name'));