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()
77 $oDB = new \Nominatim\DB;
79 if ($oDB->databaseExists()) {
80 fail('database already exists ('.CONST_Database_DSN.')');
83 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
84 if (isset($this->aDSNInfo['username'])) {
85 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
88 if (isset($this->aDSNInfo['hostspec'])) {
89 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
92 $result = $this->runWithPgEnv($sCreateDBCmd);
93 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
96 public function connect()
98 $this->oDB = new \Nominatim\DB();
99 $this->oDB->connect();
102 public function setupDB()
106 $fPostgresVersion = $this->oDB->getPostgresVersion();
107 echo 'Postgres version found: '.$fPostgresVersion."\n";
109 if ($fPostgresVersion < 9.03) {
110 fail('Minimum supported version of Postgresql is 9.3.');
113 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
114 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
116 $fPostgisVersion = $this->oDB->getPostgisVersion();
117 echo 'Postgis version found: '.$fPostgisVersion."\n";
119 if ($fPostgisVersion < 2.2) {
120 echo "Minimum required Postgis version 2.2\n";
124 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
126 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
127 echo "\n createuser ".CONST_Database_Web_User."\n\n";
131 // Try accessing the C module, so we know early if something is wrong
132 checkModulePresence(); // raises exception on failure
134 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
135 echo 'Error: you need to download the country_osm_grid first:';
136 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
139 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
140 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
141 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
142 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
144 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
145 if (file_exists($sPostcodeFilename)) {
146 $this->pgsqlRunScriptFile($sPostcodeFilename);
148 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
151 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
152 if (file_exists($sPostcodeFilename)) {
153 $this->pgsqlRunScriptFile($sPostcodeFilename);
155 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
158 if ($this->bNoPartitions) {
159 $this->pgsqlRunScript('update country_name set partition = 0');
162 // the following will be needed by createFunctions later but
163 // is only defined in the subsequently called createTables
164 // Create dummies here that will be overwritten by the proper
165 // versions in create-tables.
166 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
167 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
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 '.CONST_Import_Style;
183 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
184 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
187 if (CONST_Tablespace_Osm2pgsql_Data)
188 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
189 if (CONST_Tablespace_Osm2pgsql_Index)
190 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
191 if (CONST_Tablespace_Place_Data)
192 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
193 if (CONST_Tablespace_Place_Index)
194 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
195 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
196 $osm2pgsql .= ' -C '.$this->iCacheMemory;
197 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
198 if (isset($this->aDSNInfo['username'])) {
199 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
201 if (isset($this->aDSNInfo['hostspec'])) {
202 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
204 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$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 = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
229 $sTemplate = $this->replaceTablespace(
231 CONST_Tablespace_Address_Data,
234 $sTemplate = $this->replaceTablespace(
235 '{ts:address-index}',
236 CONST_Tablespace_Address_Index,
239 $sTemplate = $this->replaceTablespace(
241 CONST_Tablespace_Search_Data,
244 $sTemplate = $this->replaceTablespace(
246 CONST_Tablespace_Search_Index,
249 $sTemplate = $this->replaceTablespace(
251 CONST_Tablespace_Aux_Data,
254 $sTemplate = $this->replaceTablespace(
256 CONST_Tablespace_Aux_Index,
260 $this->pgsqlRunScript($sTemplate, false);
263 $this->pgExec('DROP TABLE search_name');
266 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
267 $oAlParser->createTable($this->oDB, 'address_levels');
270 public function createPartitionTables()
272 info('Create Partition Tables');
274 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
275 $sTemplate = $this->replaceTablespace(
277 CONST_Tablespace_Address_Data,
281 $sTemplate = $this->replaceTablespace(
282 '{ts:address-index}',
283 CONST_Tablespace_Address_Index,
287 $sTemplate = $this->replaceTablespace(
289 CONST_Tablespace_Search_Data,
293 $sTemplate = $this->replaceTablespace(
295 CONST_Tablespace_Search_Index,
299 $sTemplate = $this->replaceTablespace(
301 CONST_Tablespace_Aux_Data,
305 $sTemplate = $this->replaceTablespace(
307 CONST_Tablespace_Aux_Index,
311 $this->pgsqlRunPartitionScript($sTemplate);
314 public function createPartitionFunctions()
316 info('Create Partition Functions');
318 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
319 $this->pgsqlRunPartitionScript($sTemplate);
322 public function importWikipediaArticles()
324 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
325 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
326 if (file_exists($sWikiArticlesFile)) {
327 info('Importing wikipedia articles');
328 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
330 warn('wikipedia article dump file not found - places will have default importance');
332 if (file_exists($sWikiRedirectsFile)) {
333 info('Importing wikipedia redirects');
334 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
336 warn('wikipedia redirect dump file not found - some place importance values may be missing');
340 public function loadData($bDisableTokenPrecalc)
342 info('Drop old Data');
344 $this->pgExec('TRUNCATE word');
346 $this->pgExec('TRUNCATE placex');
348 $this->pgExec('TRUNCATE location_property_osmline');
350 $this->pgExec('TRUNCATE place_addressline');
352 $this->pgExec('TRUNCATE place_boundingbox');
354 $this->pgExec('TRUNCATE location_area');
356 if (!$this->dbReverseOnly()) {
357 $this->pgExec('TRUNCATE search_name');
360 $this->pgExec('TRUNCATE search_name_blank');
362 $this->pgExec('DROP SEQUENCE seq_place');
364 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
367 $sSQL = 'select distinct partition from country_name';
368 $aPartitions = $this->oDB->getCol($sSQL);
370 if (!$this->bNoPartitions) $aPartitions[] = 0;
371 foreach ($aPartitions as $sPartition) {
372 $this->pgExec('TRUNCATE location_road_'.$sPartition);
376 // used by getorcreate_word_id to ignore frequent partial words
377 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
378 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
379 $this->pgExec($sSQL);
382 // pre-create the word list
383 if (!$bDisableTokenPrecalc) {
384 info('Loading word list');
385 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
389 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
391 $aDBInstances = array();
392 $iLoadThreads = max(1, $this->iInstances - 1);
393 for ($i = 0; $i < $iLoadThreads; $i++) {
394 // https://secure.php.net/manual/en/function.pg-connect.php
395 $DSN = CONST_Database_DSN;
396 $DSN = preg_replace('/^pgsql:/', '', $DSN);
397 $DSN = preg_replace('/;/', ' ', $DSN);
398 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
399 pg_ping($aDBInstances[$i]);
402 for ($i = 0; $i < $iLoadThreads; $i++) {
403 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
404 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
405 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
406 $sSQL .= ' and ST_IsValid(geometry)';
407 if ($this->bVerbose) echo "$sSQL\n";
408 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
409 fail(pg_last_error($aDBInstances[$i]));
413 // last thread for interpolation lines
414 // https://secure.php.net/manual/en/function.pg-connect.php
415 $DSN = CONST_Database_DSN;
416 $DSN = preg_replace('/^pgsql:/', '', $DSN);
417 $DSN = preg_replace('/;/', ' ', $DSN);
418 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
419 pg_ping($aDBInstances[$iLoadThreads]);
420 $sSQL = 'insert into location_property_osmline';
421 $sSQL .= ' (osm_id, address, linegeo)';
422 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
423 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
424 if ($this->bVerbose) echo "$sSQL\n";
425 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
426 fail(pg_last_error($aDBInstances[$iLoadThreads]));
430 for ($i = 0; $i <= $iLoadThreads; $i++) {
431 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
432 $resultStatus = pg_result_status($hPGresult);
433 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
434 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
435 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
436 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
437 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
438 $resultError = pg_result_error($hPGresult);
439 echo '-- error text ' . $i . ': ' . $resultError . "\n";
445 fail('SQL errors loading placex and/or location_property_osmline tables');
448 for ($i = 0; $i < $this->iInstances; $i++) {
449 pg_close($aDBInstances[$i]);
453 info('Reanalysing database');
454 $this->pgsqlRunScript('ANALYSE');
456 $sDatabaseDate = getDatabaseDate($this->oDB);
457 $this->oDB->exec('TRUNCATE import_status');
458 if (!$sDatabaseDate) {
459 warn('could not determine database date.');
461 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
462 $this->oDB->exec($sSQL);
463 echo "Latest data imported from $sDatabaseDate.\n";
467 public function importTigerData()
469 info('Import Tiger data');
471 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
472 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
473 $sTemplate = $this->replaceTablespace(
475 CONST_Tablespace_Aux_Data,
478 $sTemplate = $this->replaceTablespace(
480 CONST_Tablespace_Aux_Index,
483 $this->pgsqlRunScript($sTemplate, false);
485 $aDBInstances = array();
486 for ($i = 0; $i < $this->iInstances; $i++) {
487 // https://secure.php.net/manual/en/function.pg-connect.php
488 $DSN = CONST_Database_DSN;
489 $DSN = preg_replace('/^pgsql:/', '', $DSN);
490 $DSN = preg_replace('/;/', ' ', $DSN);
491 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
492 pg_ping($aDBInstances[$i]);
495 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
497 $hFile = fopen($sFile, 'r');
498 $sSQL = fgets($hFile, 100000);
501 for ($i = 0; $i < $this->iInstances; $i++) {
502 if (!pg_connection_busy($aDBInstances[$i])) {
503 while (pg_get_result($aDBInstances[$i]));
504 $sSQL = fgets($hFile, 100000);
506 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
508 if ($iLines == 1000) {
521 for ($i = 0; $i < $this->iInstances; $i++) {
522 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
529 for ($i = 0; $i < $this->iInstances; $i++) {
530 pg_close($aDBInstances[$i]);
533 info('Creating indexes on Tiger data');
534 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
535 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
536 $sTemplate = $this->replaceTablespace(
538 CONST_Tablespace_Aux_Data,
541 $sTemplate = $this->replaceTablespace(
543 CONST_Tablespace_Aux_Index,
546 $this->pgsqlRunScript($sTemplate, false);
549 public function calculatePostcodes($bCMDResultAll)
551 info('Calculate Postcodes');
552 $this->pgExec('TRUNCATE location_postcode');
554 $sSQL = 'INSERT INTO location_postcode';
555 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
556 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
557 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
558 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
559 $sSQL .= ' FROM placex';
560 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
561 $sSQL .= ' AND geometry IS NOT null';
562 $sSQL .= ' GROUP BY country_code, pc';
563 $this->pgExec($sSQL);
565 // only add postcodes that are not yet available in OSM
566 $sSQL = 'INSERT INTO location_postcode';
567 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
568 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
569 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
570 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
571 $sSQL .= ' (SELECT postcode FROM location_postcode';
572 $sSQL .= " WHERE country_code = 'us')";
573 $this->pgExec($sSQL);
575 // add missing postcodes for GB (if available)
576 $sSQL = 'INSERT INTO location_postcode';
577 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
578 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
579 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
580 $sSQL .= ' (SELECT postcode FROM location_postcode';
581 $sSQL .= " WHERE country_code = 'gb')";
582 $this->pgExec($sSQL);
584 if (!$bCMDResultAll) {
585 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
586 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
587 $this->pgExec($sSQL);
590 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
591 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
592 $this->pgExec($sSQL);
595 public function index($bIndexNoanalyse)
598 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
599 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
600 if (isset($this->aDSNInfo['hostspec'])) {
601 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
603 if (isset($this->aDSNInfo['username'])) {
604 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
607 info('Index ranks 0 - 4');
608 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
610 fail('error status ' . $iStatus . ' running nominatim!');
612 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
614 info('Index ranks 5 - 25');
615 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
617 fail('error status ' . $iStatus . ' running nominatim!');
619 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
621 info('Index ranks 26 - 30');
622 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
624 fail('error status ' . $iStatus . ' running nominatim!');
627 info('Index postcodes');
628 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
629 $this->pgExec($sSQL);
632 public function createSearchIndices()
634 info('Create Search indices');
636 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
637 if (!$this->dbReverseOnly()) {
638 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
640 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
641 $sTemplate = $this->replaceTablespace(
642 '{ts:address-index}',
643 CONST_Tablespace_Address_Index,
646 $sTemplate = $this->replaceTablespace(
648 CONST_Tablespace_Search_Index,
651 $sTemplate = $this->replaceTablespace(
653 CONST_Tablespace_Aux_Index,
656 $this->pgsqlRunScript($sTemplate);
659 public function createCountryNames()
661 info('Create search index for default country names');
663 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
664 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
665 $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');
666 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
667 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
668 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
669 if (CONST_Languages) {
672 foreach (explode(',', CONST_Languages) as $sLang) {
673 $sSQL .= $sDelim."'name:$sLang'";
678 // all include all simple name tags
679 $sSQL .= "like 'name:%'";
682 $this->pgsqlRunScript($sSQL);
685 public function drop()
687 info('Drop tables only required for updates');
689 // The implementation is potentially a bit dangerous because it uses
690 // a positive selection of tables to keep, and deletes everything else.
691 // Including any tables that the unsuspecting user might have manually
692 // created. USE AT YOUR OWN PERIL.
693 // tables we want to keep. everything else goes.
694 $aKeepTables = array(
700 'location_property*',
713 $aDropTables = array();
714 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
716 foreach ($aHaveTables as $sTable) {
718 foreach ($aKeepTables as $sKeep) {
719 if (fnmatch($sKeep, $sTable)) {
724 if (!$bFound) array_push($aDropTables, $sTable);
726 foreach ($aDropTables as $sDrop) {
727 if ($this->bVerbose) echo "Dropping table $sDrop\n";
728 $this->oDB->exec("DROP TABLE $sDrop CASCADE");
729 // ignore warnings/errors as they might be caused by a table having
730 // been deleted already by CASCADE
733 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
734 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
735 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
736 unlink(CONST_Osm2pgsql_Flatnode_File);
741 private function pgsqlRunDropAndRestore($sDumpFile)
743 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' --no-owner -Fc --clean '.$sDumpFile;
744 if ($this->oDB->getPostgresVersion() >= 9.04) {
745 $sCMD .= ' --if-exists';
747 if (isset($this->aDSNInfo['hostspec'])) {
748 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
750 if (isset($this->aDSNInfo['username'])) {
751 $sCMD .= ' -U '.$this->aDSNInfo['username'];
754 $this->runWithPgEnv($sCMD);
757 private function pgsqlRunScript($sScript, $bfatal = true)
767 private function createSqlFunctions()
769 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
770 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
771 if ($this->bEnableDiffUpdates) {
772 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
774 if ($this->bEnableDebugStatements) {
775 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
777 if (CONST_Limit_Reindexing) {
778 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
780 if (!CONST_Use_US_Tiger_Data) {
781 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
783 if (!CONST_Use_Aux_Location_data) {
784 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
787 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
788 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
790 $this->pgsqlRunScript($sTemplate);
793 private function pgsqlRunPartitionScript($sTemplate)
795 $sSQL = 'select distinct partition from country_name';
796 $aPartitions = $this->oDB->getCol($sSQL);
797 if (!$this->bNoPartitions) $aPartitions[] = 0;
799 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
800 foreach ($aMatches as $aMatch) {
802 foreach ($aPartitions as $sPartitionName) {
803 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
805 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
808 $this->pgsqlRunScript($sTemplate);
811 private function pgsqlRunScriptFile($sFilename)
813 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
815 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
816 if (!$this->bVerbose) {
819 if (isset($this->aDSNInfo['hostspec'])) {
820 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
822 if (isset($this->aDSNInfo['username'])) {
823 $sCMD .= ' -U '.$this->aDSNInfo['username'];
826 if (isset($this->aDSNInfo['password'])) {
827 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
830 if (preg_match('/\\.gz$/', $sFilename)) {
831 $aDescriptors = array(
832 0 => array('pipe', 'r'),
833 1 => array('pipe', 'w'),
834 2 => array('file', '/dev/null', 'a')
836 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
837 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
838 $aReadPipe = $ahGzipPipes[1];
839 fclose($ahGzipPipes[0]);
841 $sCMD .= ' -f '.$sFilename;
842 $aReadPipe = array('pipe', 'r');
844 $aDescriptors = array(
846 1 => array('pipe', 'w'),
847 2 => array('file', '/dev/null', 'a')
850 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
851 if (!is_resource($hProcess)) fail('unable to start pgsql');
852 // TODO: error checking
853 while (!feof($ahPipes[1])) {
854 echo fread($ahPipes[1], 4096);
857 $iReturn = proc_close($hProcess);
859 fail("pgsql returned with error code ($iReturn)");
862 fclose($ahGzipPipes[1]);
863 proc_close($hGzipProcess);
867 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
870 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
872 $sSql = str_replace($sTemplate, '', $sSql);
877 private function runWithPgEnv($sCmd)
879 if ($this->bVerbose) {
880 echo "Execute: $sCmd\n";
885 if (isset($this->aDSNInfo['password'])) {
886 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
889 return runWithEnv($sCmd, $aProcEnv);
893 * Execute the SQL command on the open database.
895 * @param string $sSQL SQL command to execute.
899 * @pre connect() must have been called.
901 private function pgExec($sSQL)
903 $this->oDB->exec($sSQL);
907 * Check if the database is in reverse-only mode.
909 * @return True if there is no search_name table and infrastructure.
911 private function dbReverseOnly()
913 return !($this->oDB->tableExists('search_name'));