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.01) {
110 fail('Minimum supported version of Postgresql is 9.1.');
113 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
114 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
116 // For extratags and namedetails the hstore_to_json converter is
117 // needed which is only available from Postgresql 9.3+. For older
118 // versions add a dummy function that returns nothing.
119 $iNumFunc = $this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'");
121 if ($iNumFunc == 0) {
122 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
123 warn('Postgresql is too old. extratags and namedetails API not available.');
127 $fPostgisVersion = $this->oDB->getPostgisVersion();
128 echo 'Postgis version found: '.$fPostgisVersion."\n";
130 if ($fPostgisVersion < 2.1) {
131 // Functions were renamed in 2.1 and throw an annoying deprecation warning
132 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
133 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
135 if ($fPostgisVersion < 2.2) {
136 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
139 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
141 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
142 echo "\n createuser ".CONST_Database_Web_User."\n\n";
146 // Try accessing the C module, so we know early if something is wrong
147 if (!checkModulePresence()) {
148 fail('error loading nominatim.so module');
151 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
152 echo 'Error: you need to download the country_osm_grid first:';
153 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
156 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
157 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
158 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
160 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
161 if (file_exists($sPostcodeFilename)) {
162 $this->pgsqlRunScriptFile($sPostcodeFilename);
164 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
167 if (CONST_Use_Extra_US_Postcodes) {
168 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
171 if ($this->bNoPartitions) {
172 $this->pgsqlRunScript('update country_name set partition = 0');
175 // the following will be needed by createFunctions later but
176 // is only defined in the subsequently called createTables
177 // Create dummies here that will be overwritten by the proper
178 // versions in create-tables.
179 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
180 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
183 public function importData($sOSMFile)
187 $osm2pgsql = CONST_Osm2pgsql_Binary;
188 if (!file_exists($osm2pgsql)) {
189 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
190 echo "Normally you should not need to set this manually.\n";
191 fail("osm2pgsql not found in '$osm2pgsql'");
194 $osm2pgsql .= ' -S '.CONST_Import_Style;
196 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
197 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
200 if (CONST_Tablespace_Osm2pgsql_Data)
201 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
202 if (CONST_Tablespace_Osm2pgsql_Index)
203 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
204 if (CONST_Tablespace_Place_Data)
205 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
206 if (CONST_Tablespace_Place_Index)
207 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
208 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
209 $osm2pgsql .= ' -C '.$this->iCacheMemory;
210 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
211 if (isset($this->aDSNInfo['username'])) {
212 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
214 if (isset($this->aDSNInfo['hostspec'])) {
215 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
217 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
219 $this->runWithPgEnv($osm2pgsql);
221 if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
226 public function createFunctions()
228 info('Create Functions');
230 // Try accessing the C module, so we know eif something is wrong
231 // update.php calls this function
232 if (!checkModulePresence()) {
233 fail('error loading nominatim.so module');
235 $this->createSqlFunctions();
238 public function createTables($bReverseOnly = false)
240 info('Create Tables');
242 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
243 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
244 $sTemplate = $this->replaceTablespace(
246 CONST_Tablespace_Address_Data,
249 $sTemplate = $this->replaceTablespace(
250 '{ts:address-index}',
251 CONST_Tablespace_Address_Index,
254 $sTemplate = $this->replaceTablespace(
256 CONST_Tablespace_Search_Data,
259 $sTemplate = $this->replaceTablespace(
261 CONST_Tablespace_Search_Index,
264 $sTemplate = $this->replaceTablespace(
266 CONST_Tablespace_Aux_Data,
269 $sTemplate = $this->replaceTablespace(
271 CONST_Tablespace_Aux_Index,
275 $this->pgsqlRunScript($sTemplate, false);
278 $this->pgExec('DROP TABLE search_name');
281 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
282 $oAlParser->createTable($this->oDB, 'address_levels');
285 public function createPartitionTables()
287 info('Create Partition Tables');
289 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
290 $sTemplate = $this->replaceTablespace(
292 CONST_Tablespace_Address_Data,
296 $sTemplate = $this->replaceTablespace(
297 '{ts:address-index}',
298 CONST_Tablespace_Address_Index,
302 $sTemplate = $this->replaceTablespace(
304 CONST_Tablespace_Search_Data,
308 $sTemplate = $this->replaceTablespace(
310 CONST_Tablespace_Search_Index,
314 $sTemplate = $this->replaceTablespace(
316 CONST_Tablespace_Aux_Data,
320 $sTemplate = $this->replaceTablespace(
322 CONST_Tablespace_Aux_Index,
326 $this->pgsqlRunPartitionScript($sTemplate);
329 public function createPartitionFunctions()
331 info('Create Partition Functions');
333 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
334 $this->pgsqlRunPartitionScript($sTemplate);
337 public function importWikipediaArticles()
339 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
340 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
341 if (file_exists($sWikiArticlesFile)) {
342 info('Importing wikipedia articles');
343 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
345 warn('wikipedia article dump file not found - places will have default importance');
347 if (file_exists($sWikiRedirectsFile)) {
348 info('Importing wikipedia redirects');
349 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
351 warn('wikipedia redirect dump file not found - some place importance values may be missing');
355 public function loadData($bDisableTokenPrecalc)
357 info('Drop old Data');
359 $this->pgExec('TRUNCATE word');
361 $this->pgExec('TRUNCATE placex');
363 $this->pgExec('TRUNCATE location_property_osmline');
365 $this->pgExec('TRUNCATE place_addressline');
367 $this->pgExec('TRUNCATE place_boundingbox');
369 $this->pgExec('TRUNCATE location_area');
371 if (!$this->dbReverseOnly()) {
372 $this->pgExec('TRUNCATE search_name');
375 $this->pgExec('TRUNCATE search_name_blank');
377 $this->pgExec('DROP SEQUENCE seq_place');
379 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
382 $sSQL = 'select distinct partition from country_name';
383 $aPartitions = $this->oDB->getCol($sSQL);
385 if (!$this->bNoPartitions) $aPartitions[] = 0;
386 foreach ($aPartitions as $sPartition) {
387 $this->pgExec('TRUNCATE location_road_'.$sPartition);
391 // used by getorcreate_word_id to ignore frequent partial words
392 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
393 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
394 $this->pgExec($sSQL);
397 // pre-create the word list
398 if (!$bDisableTokenPrecalc) {
399 info('Loading word list');
400 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
404 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
406 $aDBInstances = array();
407 $iLoadThreads = max(1, $this->iInstances - 1);
408 for ($i = 0; $i < $iLoadThreads; $i++) {
409 // https://secure.php.net/manual/en/function.pg-connect.php
410 $DSN = CONST_Database_DSN;
411 $DSN = preg_replace('/^pgsql:/', '', $DSN);
412 $DSN = preg_replace('/;/', ' ', $DSN);
413 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
414 pg_ping($aDBInstances[$i]);
417 for ($i = 0; $i < $iLoadThreads; $i++) {
418 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
419 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
420 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
421 $sSQL .= ' and ST_IsValid(geometry)';
422 if ($this->bVerbose) echo "$sSQL\n";
423 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
424 fail(pg_last_error($aDBInstances[$i]));
428 // last thread for interpolation lines
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[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
434 pg_ping($aDBInstances[$iLoadThreads]);
435 $sSQL = 'insert into location_property_osmline';
436 $sSQL .= ' (osm_id, address, linegeo)';
437 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
438 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
439 if ($this->bVerbose) echo "$sSQL\n";
440 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
441 fail(pg_last_error($aDBInstances[$iLoadThreads]));
445 for ($i = 0; $i <= $iLoadThreads; $i++) {
446 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
447 $resultStatus = pg_result_status($hPGresult);
448 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
449 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
450 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
451 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
452 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
453 $resultError = pg_result_error($hPGresult);
454 echo '-- error text ' . $i . ': ' . $resultError . "\n";
460 fail('SQL errors loading placex and/or location_property_osmline tables');
463 for ($i = 0; $i < $this->iInstances; $i++) {
464 pg_close($aDBInstances[$i]);
468 info('Reanalysing database');
469 $this->pgsqlRunScript('ANALYSE');
471 $sDatabaseDate = getDatabaseDate($this->oDB);
472 $this->oDB->exec('TRUNCATE import_status');
473 if (!$sDatabaseDate) {
474 warn('could not determine database date.');
476 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
477 $this->oDB->exec($sSQL);
478 echo "Latest data imported from $sDatabaseDate.\n";
482 public function importTigerData()
484 info('Import Tiger data');
486 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
487 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
488 $sTemplate = $this->replaceTablespace(
490 CONST_Tablespace_Aux_Data,
493 $sTemplate = $this->replaceTablespace(
495 CONST_Tablespace_Aux_Index,
498 $this->pgsqlRunScript($sTemplate, false);
500 $aDBInstances = array();
501 for ($i = 0; $i < $this->iInstances; $i++) {
502 // https://secure.php.net/manual/en/function.pg-connect.php
503 $DSN = CONST_Database_DSN;
504 $DSN = preg_replace('/^pgsql:/', '', $DSN);
505 $DSN = preg_replace('/;/', ' ', $DSN);
506 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
507 pg_ping($aDBInstances[$i]);
510 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
512 $hFile = fopen($sFile, 'r');
513 $sSQL = fgets($hFile, 100000);
516 for ($i = 0; $i < $this->iInstances; $i++) {
517 if (!pg_connection_busy($aDBInstances[$i])) {
518 while (pg_get_result($aDBInstances[$i]));
519 $sSQL = fgets($hFile, 100000);
521 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
523 if ($iLines == 1000) {
536 for ($i = 0; $i < $this->iInstances; $i++) {
537 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
544 for ($i = 0; $i < $this->iInstances; $i++) {
545 pg_close($aDBInstances[$i]);
548 info('Creating indexes on Tiger data');
549 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
550 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
551 $sTemplate = $this->replaceTablespace(
553 CONST_Tablespace_Aux_Data,
556 $sTemplate = $this->replaceTablespace(
558 CONST_Tablespace_Aux_Index,
561 $this->pgsqlRunScript($sTemplate, false);
564 public function calculatePostcodes($bCMDResultAll)
566 info('Calculate Postcodes');
567 $this->pgExec('TRUNCATE location_postcode');
569 $sSQL = 'INSERT INTO location_postcode';
570 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
571 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
572 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
573 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
574 $sSQL .= ' FROM placex';
575 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
576 $sSQL .= ' AND geometry IS NOT null';
577 $sSQL .= ' GROUP BY country_code, pc';
578 $this->pgExec($sSQL);
580 if (CONST_Use_Extra_US_Postcodes) {
581 // only add postcodes that are not yet available in OSM
582 $sSQL = 'INSERT INTO location_postcode';
583 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
584 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
585 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
586 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
587 $sSQL .= ' (SELECT postcode FROM location_postcode';
588 $sSQL .= " WHERE country_code = 'us')";
589 $this->pgExec($sSQL);
592 // add missing postcodes for GB (if available)
593 $sSQL = 'INSERT INTO location_postcode';
594 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
595 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
596 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
597 $sSQL .= ' (SELECT postcode FROM location_postcode';
598 $sSQL .= " WHERE country_code = 'gb')";
599 $this->pgExec($sSQL);
601 if (!$bCMDResultAll) {
602 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
603 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
604 $this->pgExec($sSQL);
607 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
608 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
609 $this->pgExec($sSQL);
612 public function index($bIndexNoanalyse)
615 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
616 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
617 if (isset($this->aDSNInfo['hostspec'])) {
618 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
620 if (isset($this->aDSNInfo['username'])) {
621 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
624 info('Index ranks 0 - 4');
625 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
627 fail('error status ' . $iStatus . ' running nominatim!');
629 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
631 info('Index ranks 5 - 25');
632 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
634 fail('error status ' . $iStatus . ' running nominatim!');
636 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
638 info('Index ranks 26 - 30');
639 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
641 fail('error status ' . $iStatus . ' running nominatim!');
644 info('Index postcodes');
645 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
646 $this->pgExec($sSQL);
649 public function createSearchIndices()
651 info('Create Search indices');
653 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
654 if (!$this->dbReverseOnly()) {
655 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
657 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
658 $sTemplate = $this->replaceTablespace(
659 '{ts:address-index}',
660 CONST_Tablespace_Address_Index,
663 $sTemplate = $this->replaceTablespace(
665 CONST_Tablespace_Search_Index,
668 $sTemplate = $this->replaceTablespace(
670 CONST_Tablespace_Aux_Index,
673 $this->pgsqlRunScript($sTemplate);
676 public function createCountryNames()
678 info('Create search index for default country names');
680 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
681 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
682 $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');
683 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
684 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
685 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
686 if (CONST_Languages) {
689 foreach (explode(',', CONST_Languages) as $sLang) {
690 $sSQL .= $sDelim."'name:$sLang'";
695 // all include all simple name tags
696 $sSQL .= "like 'name:%'";
699 $this->pgsqlRunScript($sSQL);
702 public function drop()
704 info('Drop tables only required for updates');
706 // The implementation is potentially a bit dangerous because it uses
707 // a positive selection of tables to keep, and deletes everything else.
708 // Including any tables that the unsuspecting user might have manually
709 // created. USE AT YOUR OWN PERIL.
710 // tables we want to keep. everything else goes.
711 $aKeepTables = array(
717 'location_property*',
730 $aDropTables = array();
731 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
733 foreach ($aHaveTables as $sTable) {
735 foreach ($aKeepTables as $sKeep) {
736 if (fnmatch($sKeep, $sTable)) {
741 if (!$bFound) array_push($aDropTables, $sTable);
743 foreach ($aDropTables as $sDrop) {
744 if ($this->bVerbose) echo "Dropping table $sDrop\n";
745 $this->oDB->exec("DROP TABLE $sDrop CASCADE");
746 // ignore warnings/errors as they might be caused by a table having
747 // been deleted already by CASCADE
750 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
751 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
752 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
753 unlink(CONST_Osm2pgsql_Flatnode_File);
758 private function pgsqlRunDropAndRestore($sDumpFile)
760 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
761 if (isset($this->aDSNInfo['hostspec'])) {
762 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
764 if (isset($this->aDSNInfo['username'])) {
765 $sCMD .= ' -U '.$this->aDSNInfo['username'];
768 $this->runWithPgEnv($sCMD);
771 private function pgsqlRunScript($sScript, $bfatal = true)
781 private function createSqlFunctions()
783 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
784 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
785 if ($this->bEnableDiffUpdates) {
786 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
788 if ($this->bEnableDebugStatements) {
789 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
791 if (CONST_Limit_Reindexing) {
792 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
794 if (!CONST_Use_US_Tiger_Data) {
795 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
797 if (!CONST_Use_Aux_Location_data) {
798 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
801 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
802 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
804 $this->pgsqlRunScript($sTemplate);
807 private function pgsqlRunPartitionScript($sTemplate)
809 $sSQL = 'select distinct partition from country_name';
810 $aPartitions = $this->oDB->getCol($sSQL);
811 if (!$this->bNoPartitions) $aPartitions[] = 0;
813 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
814 foreach ($aMatches as $aMatch) {
816 foreach ($aPartitions as $sPartitionName) {
817 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
819 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
822 $this->pgsqlRunScript($sTemplate);
825 private function pgsqlRunScriptFile($sFilename)
827 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
829 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
830 if (!$this->bVerbose) {
833 if (isset($this->aDSNInfo['hostspec'])) {
834 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
836 if (isset($this->aDSNInfo['username'])) {
837 $sCMD .= ' -U '.$this->aDSNInfo['username'];
840 if (isset($this->aDSNInfo['password'])) {
841 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
844 if (preg_match('/\\.gz$/', $sFilename)) {
845 $aDescriptors = array(
846 0 => array('pipe', 'r'),
847 1 => array('pipe', 'w'),
848 2 => array('file', '/dev/null', 'a')
850 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
851 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
852 $aReadPipe = $ahGzipPipes[1];
853 fclose($ahGzipPipes[0]);
855 $sCMD .= ' -f '.$sFilename;
856 $aReadPipe = array('pipe', 'r');
858 $aDescriptors = array(
860 1 => array('pipe', 'w'),
861 2 => array('file', '/dev/null', 'a')
864 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
865 if (!is_resource($hProcess)) fail('unable to start pgsql');
866 // TODO: error checking
867 while (!feof($ahPipes[1])) {
868 echo fread($ahPipes[1], 4096);
871 $iReturn = proc_close($hProcess);
873 fail("pgsql returned with error code ($iReturn)");
876 fclose($ahGzipPipes[1]);
877 proc_close($hGzipProcess);
881 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
884 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
886 $sSql = str_replace($sTemplate, '', $sSql);
891 private function runWithPgEnv($sCmd)
893 if ($this->bVerbose) {
894 echo "Execute: $sCmd\n";
899 if (isset($this->aDSNInfo['password'])) {
900 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
903 return runWithEnv($sCmd, $aProcEnv);
907 * Execute the SQL command on the open database.
909 * @param string $sSQL SQL command to execute.
913 * @pre connect() must have been called.
915 private function pgExec($sSQL)
917 $this->oDB->exec($sSQL);
921 * Check if the database is in reverse-only mode.
923 * @return True if there is no search_name table and infrastructure.
925 private function dbReverseOnly()
927 return !($this->oDB->tableExists('search_name'));