3 namespace Nominatim\Setup;
7 protected $iCacheMemory;
9 protected $sModulePath;
12 protected $sIgnoreErrors;
13 protected $bEnableDiffUpdates;
14 protected $bEnableDebugStatements;
15 protected $bNoPartitions;
16 protected $oDB = null;
18 public function __construct(array $aCMDResult)
20 // by default, use all but one processor, but never more than 15.
21 $this->iInstances = isset($aCMDResult['threads'])
22 ? $aCMDResult['threads']
23 : (min(16, getProcessorCount()) - 1);
25 if ($this->iInstances < 1) {
26 $this->iInstances = 1;
27 warn('resetting threads to '.$this->iInstances);
30 // Assume we can steal all the cache memory in the box (unless told otherwise)
31 if (isset($aCMDResult['osm2pgsql-cache'])) {
32 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
34 $this->iCacheMemory = getCacheMemoryMB();
37 $this->sModulePath = CONST_Database_Module_Path;
38 info('module path: ' . $this->sModulePath);
40 // parse database string
41 $this->aDSNInfo = array_filter(\DB::parseDSN(CONST_Database_DSN));
42 if (!isset($this->aDSNInfo['port'])) {
43 $this->aDSNInfo['port'] = 5432;
46 // setting member variables based on command line options stored in $aCMDResult
47 $this->sVerbose = $aCMDResult['verbose'];
49 //setting default values which are not set by the update.php array
50 if (isset($aCMDResult['ignore-errors'])) {
51 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
53 $this->sIgnoreErrors = false;
55 if (isset($aCMDResult['enable-debug-statements'])) {
56 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
58 $this->bEnableDebugStatements = false;
60 if (isset($aCMDResult['no-partitions'])) {
61 $this->bNoPartitions = $aCMDResult['no-partitions'];
63 $this->bNoPartitions = false;
65 if (isset($aCMDResult['enable-diff-updates'])) {
66 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
68 $this->bEnableDiffUpdates = false;
72 public function createDB()
75 $sDB = \DB::connect(CONST_Database_DSN, false);
76 if (!\PEAR::isError($sDB)) {
77 fail('database already exists ('.CONST_Database_DSN.')');
80 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
81 if (isset($this->aDSNInfo['username'])) {
82 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
85 if (isset($this->aDSNInfo['hostspec'])) {
86 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
89 $result = $this->runWithPgEnv($sCreateDBCmd);
90 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
93 public function connect($sDatabaseDSN)
95 $this->oDB =& getDB();
98 public function setupDB()
102 $fPostgresVersion = getPostgresVersion($this->oDB);
103 echo 'Postgres version found: '.$fPostgresVersion."\n";
105 if ($fPostgresVersion < 9.01) {
106 fail('Minimum supported version of Postgresql is 9.1.');
109 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
110 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
112 // For extratags and namedetails the hstore_to_json converter is
113 // needed which is only available from Postgresql 9.3+. For older
114 // versions add a dummy function that returns nothing.
115 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
117 if ($iNumFunc == 0) {
118 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
119 warn('Postgresql is too old. extratags and namedetails API not available.');
123 $fPostgisVersion = getPostgisVersion($this->oDB);
124 echo 'Postgis version found: '.$fPostgisVersion."\n";
126 if ($fPostgisVersion < 2.1) {
127 // Functions were renamed in 2.1 and throw an annoying deprecation warning
128 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
129 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
131 if ($fPostgisVersion < 2.2) {
132 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
135 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
137 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
138 echo "\n createuser ".CONST_Database_Web_User."\n\n";
142 // Try accessing the C module, so we know early if something is wrong
143 if (!checkModulePresence()) {
144 fail('error loading nominatim.so module');
147 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
148 echo 'Error: you need to download the country_osm_grid first:';
149 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
152 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
153 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
154 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
155 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
157 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
158 if (file_exists($sPostcodeFilename)) {
159 $this->pgsqlRunScriptFile($sPostcodeFilename);
161 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
164 if (CONST_Use_Extra_US_Postcodes) {
165 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
168 if ($this->bNoPartitions) {
169 $this->pgsqlRunScript('update country_name set partition = 0');
172 // the following will be needed by createFunctions later but
173 // is only defined in the subsequently called createTables
174 // Create dummies here that will be overwritten by the proper
175 // versions in create-tables.
176 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
177 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
180 public function importData($sOSMFile)
184 $osm2pgsql = CONST_Osm2pgsql_Binary;
185 if (!file_exists($osm2pgsql)) {
186 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
187 echo "Normally you should not need to set this manually.\n";
188 fail("osm2pgsql not found in '$osm2pgsql'");
191 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
195 if (CONST_Tablespace_Osm2pgsql_Data)
196 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
197 if (CONST_Tablespace_Osm2pgsql_Index)
198 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
199 if (CONST_Tablespace_Place_Data)
200 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
201 if (CONST_Tablespace_Place_Index)
202 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
203 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
204 $osm2pgsql .= ' -C '.$this->iCacheMemory;
205 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
206 if (isset($this->aDSNInfo['username'])) {
207 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
209 if (isset($this->aDSNInfo['hostspec'])) {
210 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
212 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
214 $this->runWithPgEnv($osm2pgsql);
216 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
221 public function createFunctions()
223 info('Create Functions');
225 // Try accessing the C module, so we know eif something is wrong
226 // update.php calls this function
227 if (!checkModulePresence()) {
228 fail('error loading nominatim.so module');
230 $this->createSqlFunctions();
233 public function createTables()
235 info('Create Tables');
237 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
238 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
239 $sTemplate = $this->replaceTablespace(
241 CONST_Tablespace_Address_Data,
244 $sTemplate = $this->replaceTablespace(
245 '{ts:address-index}',
246 CONST_Tablespace_Address_Index,
249 $sTemplate = $this->replaceTablespace(
251 CONST_Tablespace_Search_Data,
254 $sTemplate = $this->replaceTablespace(
256 CONST_Tablespace_Search_Index,
259 $sTemplate = $this->replaceTablespace(
261 CONST_Tablespace_Aux_Data,
264 $sTemplate = $this->replaceTablespace(
266 CONST_Tablespace_Aux_Index,
270 $this->pgsqlRunScript($sTemplate, false);
273 public function createPartitionTables()
275 info('Create Partition Tables');
277 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
278 $sTemplate = $this->replaceTablespace(
280 CONST_Tablespace_Address_Data,
284 $sTemplate = $this->replaceTablespace(
285 '{ts:address-index}',
286 CONST_Tablespace_Address_Index,
290 $sTemplate = $this->replaceTablespace(
292 CONST_Tablespace_Search_Data,
296 $sTemplate = $this->replaceTablespace(
298 CONST_Tablespace_Search_Index,
302 $sTemplate = $this->replaceTablespace(
304 CONST_Tablespace_Aux_Data,
308 $sTemplate = $this->replaceTablespace(
310 CONST_Tablespace_Aux_Index,
314 $this->pgsqlRunPartitionScript($sTemplate);
317 public function createPartitionFunctions()
319 info('Create Partition Functions');
321 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
322 $this->pgsqlRunPartitionScript($sTemplate);
325 public function importWikipediaArticles()
327 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
328 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
329 if (file_exists($sWikiArticlesFile)) {
330 info('Importing wikipedia articles');
331 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
333 warn('wikipedia article dump file not found - places will have default importance');
335 if (file_exists($sWikiRedirectsFile)) {
336 info('Importing wikipedia redirects');
337 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
339 warn('wikipedia redirect dump file not found - some place importance values may be missing');
343 public function loadData($bDisableTokenPrecalc)
345 info('Drop old Data');
347 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
349 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
351 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
353 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
355 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
357 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
359 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
361 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
363 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
365 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
368 $sSQL = 'select distinct partition from country_name';
369 $aPartitions = chksql($this->oDB->getCol($sSQL));
370 if (!$this->bNoPartitions) $aPartitions[] = 0;
371 foreach ($aPartitions as $sPartition) {
372 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
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 if (!pg_query($this->oDB->connection, $sSQL)) {
380 fail(pg_last_error($this->oDB->connection));
384 // pre-create the word list
385 if (!$bDisableTokenPrecalc) {
386 info('Loading word list');
387 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
391 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
392 $aDBInstances = array();
393 $iLoadThreads = max(1, $this->iInstances - 1);
394 for ($i = 0; $i < $iLoadThreads; $i++) {
395 $aDBInstances[$i] =& getDB(true);
396 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
397 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
398 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
399 $sSQL .= ' and ST_IsValid(geometry)';
400 if ($this->sVerbose) echo "$sSQL\n";
401 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
402 fail(pg_last_error($aDBInstances[$i]->connection));
406 // last thread for interpolation lines
407 $aDBInstances[$iLoadThreads] =& getDB(true);
408 $sSQL = 'insert into location_property_osmline';
409 $sSQL .= ' (osm_id, address, linegeo)';
410 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
411 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
412 if ($this->sVerbose) echo "$sSQL\n";
413 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
414 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
418 for ($i = 0; $i <= $iLoadThreads; $i++) {
419 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
420 $resultStatus = pg_result_status($hPGresult);
421 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
422 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
423 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
424 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
425 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
426 $resultError = pg_result_error($hPGresult);
427 echo '-- error text ' . $i . ': ' . $resultError . "\n";
433 fail('SQL errors loading placex and/or location_property_osmline tables');
436 info('Reanalysing database');
437 $this->pgsqlRunScript('ANALYSE');
439 $sDatabaseDate = getDatabaseDate($this->oDB);
440 pg_query($this->oDB->connection, 'TRUNCATE import_status');
441 if ($sDatabaseDate === false) {
442 warn('could not determine database date.');
444 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
445 pg_query($this->oDB->connection, $sSQL);
446 echo "Latest data imported from $sDatabaseDate.\n";
450 public function importTigerData()
452 info('Import Tiger data');
454 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
455 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
456 $sTemplate = $this->replaceTablespace(
458 CONST_Tablespace_Aux_Data,
461 $sTemplate = $this->replaceTablespace(
463 CONST_Tablespace_Aux_Index,
466 $this->pgsqlRunScript($sTemplate, false);
468 $aDBInstances = array();
469 for ($i = 0; $i < $this->iInstances; $i++) {
470 $aDBInstances[$i] =& getDB(true);
473 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
475 $hFile = fopen($sFile, 'r');
476 $sSQL = fgets($hFile, 100000);
479 for ($i = 0; $i < $this->iInstances; $i++) {
480 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
481 while (pg_get_result($aDBInstances[$i]->connection));
482 $sSQL = fgets($hFile, 100000);
484 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
486 if ($iLines == 1000) {
499 for ($i = 0; $i < $this->iInstances; $i++) {
500 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
507 info('Creating indexes on Tiger data');
508 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
509 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
510 $sTemplate = $this->replaceTablespace(
512 CONST_Tablespace_Aux_Data,
515 $sTemplate = $this->replaceTablespace(
517 CONST_Tablespace_Aux_Index,
520 $this->pgsqlRunScript($sTemplate, false);
523 public function calculatePostcodes($bCMDResultAll)
525 info('Calculate Postcodes');
526 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
527 fail(pg_last_error($this->oDB->connection));
531 $sSQL = 'INSERT INTO location_postcode';
532 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
533 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
534 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
535 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
536 $sSQL .= ' FROM placex';
537 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
538 $sSQL .= ' AND geometry IS NOT null';
539 $sSQL .= ' GROUP BY country_code, pc';
541 if (!pg_query($this->oDB->connection, $sSQL)) {
542 fail(pg_last_error($this->oDB->connection));
545 if (CONST_Use_Extra_US_Postcodes) {
546 // only add postcodes that are not yet available in OSM
547 $sSQL = 'INSERT INTO location_postcode';
548 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
549 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
550 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
551 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
552 $sSQL .= ' (SELECT postcode FROM location_postcode';
553 $sSQL .= " WHERE country_code = 'us')";
554 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
557 // add missing postcodes for GB (if available)
558 $sSQL = 'INSERT INTO location_postcode';
559 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
560 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
561 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
562 $sSQL .= ' (SELECT postcode FROM location_postcode';
563 $sSQL .= " WHERE country_code = 'gb')";
564 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
566 if (!$bCMDResultAll) {
567 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
568 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
569 if (!pg_query($this->oDB->connection, $sSQL)) {
570 fail(pg_last_error($this->oDB->connection));
573 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
574 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
576 if (!pg_query($this->oDB->connection, $sSQL)) {
577 fail(pg_last_error($this->oDB->connection));
581 public function index($bIndexNoanalyse)
584 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
585 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
586 if (isset($this->aDSNInfo['hostspec'])) {
587 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
589 if (isset($this->aDSNInfo['username'])) {
590 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
593 info('Index ranks 0 - 4');
594 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
596 fail('error status ' . $iStatus . ' running nominatim!');
598 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
599 info('Index ranks 5 - 25');
600 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
602 fail('error status ' . $iStatus . ' running nominatim!');
604 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
605 info('Index ranks 26 - 30');
606 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
608 fail('error status ' . $iStatus . ' running nominatim!');
610 info('Index postcodes');
611 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
612 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
615 public function createSearchIndices()
617 info('Create Search indices');
619 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
620 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
621 $sTemplate = $this->replaceTablespace(
622 '{ts:address-index}',
623 CONST_Tablespace_Address_Index,
626 $sTemplate = $this->replaceTablespace(
628 CONST_Tablespace_Search_Index,
631 $sTemplate = $this->replaceTablespace(
633 CONST_Tablespace_Aux_Index,
636 $this->pgsqlRunScript($sTemplate);
639 public function createCountryNames()
641 info('Create search index for default country names');
643 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
644 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
645 $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');
646 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
647 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
648 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
649 if (CONST_Languages) {
652 foreach (explode(',', CONST_Languages) as $sLang) {
653 $sSQL .= $sDelim."'name:$sLang'";
658 // all include all simple name tags
659 $sSQL .= "like 'name:%'";
662 $this->pgsqlRunScript($sSQL);
665 public function drop()
667 info('Drop tables only required for updates');
669 // The implementation is potentially a bit dangerous because it uses
670 // a positive selection of tables to keep, and deletes everything else.
671 // Including any tables that the unsuspecting user might have manually
672 // created. USE AT YOUR OWN PERIL.
673 // tables we want to keep. everything else goes.
674 $aKeepTables = array(
680 'location_property*',
692 $aDropTables = array();
693 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
695 foreach ($aHaveTables as $sTable) {
697 foreach ($aKeepTables as $sKeep) {
698 if (fnmatch($sKeep, $sTable)) {
703 if (!$bFound) array_push($aDropTables, $sTable);
705 foreach ($aDropTables as $sDrop) {
706 if ($this->sVerbose) echo "dropping table $sDrop\n";
707 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
708 // ignore warnings/errors as they might be caused by a table having
709 // been deleted already by CASCADE
712 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
713 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
714 unlink(CONST_Osm2pgsql_Flatnode_File);
718 private function pgsqlRunDropAndRestore($sDumpFile)
720 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
721 if (isset($this->aDSNInfo['hostspec'])) {
722 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
724 if (isset($this->aDSNInfo['username'])) {
725 $sCMD .= ' -U '.$this->aDSNInfo['username'];
728 $this->runWithPgEnv($sCMD);
731 private function pgsqlRunScript($sScript, $bfatal = true)
741 private function createSqlFunctions()
743 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
744 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
745 if ($this->bEnableDiffUpdates) {
746 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
748 if ($this->bEnableDebugStatements) {
749 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
751 if (CONST_Limit_Reindexing) {
752 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
754 if (!CONST_Use_US_Tiger_Data) {
755 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
757 if (!CONST_Use_Aux_Location_data) {
758 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
760 $this->pgsqlRunScript($sTemplate);
763 private function pgsqlRunPartitionScript($sTemplate)
765 $sSQL = 'select distinct partition from country_name';
766 $aPartitions = chksql($this->oDB->getCol($sSQL));
767 if (!$this->bNoPartitions) $aPartitions[] = 0;
769 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
770 foreach ($aMatches as $aMatch) {
772 foreach ($aPartitions as $sPartitionName) {
773 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
775 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
778 $this->pgsqlRunScript($sTemplate);
781 private function pgsqlRunScriptFile($sFilename)
783 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
785 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
786 if (!$this->sVerbose) {
789 if (isset($this->aDSNInfo['hostspec'])) {
790 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
792 if (isset($this->aDSNInfo['username'])) {
793 $sCMD .= ' -U '.$this->aDSNInfo['username'];
796 if (isset($this->aDSNInfo['password'])) {
797 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
800 if (preg_match('/\\.gz$/', $sFilename)) {
801 $aDescriptors = array(
802 0 => array('pipe', 'r'),
803 1 => array('pipe', 'w'),
804 2 => array('file', '/dev/null', 'a')
806 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
807 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
808 $aReadPipe = $ahGzipPipes[1];
809 fclose($ahGzipPipes[0]);
811 $sCMD .= ' -f '.$sFilename;
812 $aReadPipe = array('pipe', 'r');
814 $aDescriptors = array(
816 1 => array('pipe', 'w'),
817 2 => array('file', '/dev/null', 'a')
820 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
821 if (!is_resource($hProcess)) fail('unable to start pgsql');
822 // TODO: error checking
823 while (!feof($ahPipes[1])) {
824 echo fread($ahPipes[1], 4096);
827 $iReturn = proc_close($hProcess);
829 fail("pgsql returned with error code ($iReturn)");
832 fclose($ahGzipPipes[1]);
833 proc_close($hGzipProcess);
837 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
840 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
842 $sSql = str_replace($sTemplate, '', $sSql);
847 private function runWithPgEnv($sCmd)
851 if (isset($this->aDSNInfo['password'])) {
852 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
855 return runWithEnv($sCmd, $aProcEnv);