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 if (isset($aCMDResult['osm2pgsql-cache'])) {
33 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
34 } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
35 // When flatnode files are enabled then disable cache per default.
36 $this->iCacheMemory = 0;
38 // Otherwise: Assume we can steal all the cache memory in the box.
39 $this->iCacheMemory = getCacheMemoryMB();
42 $this->sModulePath = CONST_Database_Module_Path;
43 info('module path: ' . $this->sModulePath);
45 // parse database string
46 $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
47 if (!isset($this->aDSNInfo['port'])) {
48 $this->aDSNInfo['port'] = 5432;
51 // setting member variables based on command line options stored in $aCMDResult
52 $this->bVerbose = $aCMDResult['verbose'];
54 //setting default values which are not set by the update.php array
55 if (isset($aCMDResult['ignore-errors'])) {
56 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
58 $this->sIgnoreErrors = false;
60 if (isset($aCMDResult['enable-debug-statements'])) {
61 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
63 $this->bEnableDebugStatements = false;
65 if (isset($aCMDResult['no-partitions'])) {
66 $this->bNoPartitions = $aCMDResult['no-partitions'];
68 $this->bNoPartitions = false;
70 if (isset($aCMDResult['enable-diff-updates'])) {
71 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
73 $this->bEnableDiffUpdates = false;
77 public function createDB()
80 $oDB = new \Nominatim\DB;
82 if ($oDB->databaseExists()) {
83 fail('database already exists ('.CONST_Database_DSN.')');
86 $sCreateDBCmd = 'createdb -E UTF-8'
87 .' -p '.escapeshellarg($this->aDSNInfo['port'])
88 .' '.escapeshellarg($this->aDSNInfo['database']);
89 if (isset($this->aDSNInfo['username'])) {
90 $sCreateDBCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
93 if (isset($this->aDSNInfo['hostspec'])) {
94 $sCreateDBCmd .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
97 $result = $this->runWithPgEnv($sCreateDBCmd);
98 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
101 public function connect()
103 $this->oDB = new \Nominatim\DB();
104 $this->oDB->connect();
107 public function setupDB()
111 $fPostgresVersion = $this->oDB->getPostgresVersion();
112 echo 'Postgres version found: '.$fPostgresVersion."\n";
114 if ($fPostgresVersion < 9.03) {
115 fail('Minimum supported version of Postgresql is 9.3.');
118 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
119 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
121 $fPostgisVersion = $this->oDB->getPostgisVersion();
122 echo 'Postgis version found: '.$fPostgisVersion."\n";
124 if ($fPostgisVersion < 2.2) {
125 echo "Minimum required Postgis version 2.2\n";
129 $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
131 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
132 echo "\n createuser ".CONST_Database_Web_User."\n\n";
136 // Try accessing the C module, so we know early if something is wrong
137 checkModulePresence(); // raises exception on failure
139 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
140 echo 'Error: you need to download the country_osm_grid first:';
141 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
144 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
145 $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
146 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
147 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
149 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
150 if (file_exists($sPostcodeFilename)) {
151 $this->pgsqlRunScriptFile($sPostcodeFilename);
153 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
156 $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
157 if (file_exists($sPostcodeFilename)) {
158 $this->pgsqlRunScriptFile($sPostcodeFilename);
160 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
163 if ($this->bNoPartitions) {
164 $this->pgsqlRunScript('update country_name set partition = 0');
168 public function importData($sOSMFile)
172 $osm2pgsql = CONST_Osm2pgsql_Binary;
173 if (!file_exists($osm2pgsql)) {
174 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
175 echo "Normally you should not need to set this manually.\n";
176 fail("osm2pgsql not found in '$osm2pgsql'");
179 $osm2pgsql .= ' -S '.escapeshellarg(CONST_Import_Style);
181 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
182 $osm2pgsql .= ' --flat-nodes '.escapeshellarg(CONST_Osm2pgsql_Flatnode_File);
185 if (CONST_Tablespace_Osm2pgsql_Data)
186 $osm2pgsql .= ' --tablespace-slim-data '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Data);
187 if (CONST_Tablespace_Osm2pgsql_Index)
188 $osm2pgsql .= ' --tablespace-slim-index '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Index);
189 if (CONST_Tablespace_Place_Data)
190 $osm2pgsql .= ' --tablespace-main-data '.escapeshellarg(CONST_Tablespace_Place_Data);
191 if (CONST_Tablespace_Place_Index)
192 $osm2pgsql .= ' --tablespace-main-index '.escapeshellarg(CONST_Tablespace_Place_Index);
193 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
194 $osm2pgsql .= ' -C '.escapeshellarg($this->iCacheMemory);
195 $osm2pgsql .= ' -P '.escapeshellarg($this->aDSNInfo['port']);
196 if (isset($this->aDSNInfo['username'])) {
197 $osm2pgsql .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
199 if (isset($this->aDSNInfo['hostspec'])) {
200 $osm2pgsql .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
202 $osm2pgsql .= ' -d '.escapeshellarg($this->aDSNInfo['database']).' '.escapeshellarg($sOSMFile);
204 $this->runWithPgEnv($osm2pgsql);
206 if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
211 public function createFunctions()
213 info('Create Functions');
215 // Try accessing the C module, so we know early if something is wrong
216 checkModulePresence(); // raises exception on failure
218 $this->createSqlFunctions();
221 public function createTables($bReverseOnly = false)
223 info('Create Tables');
225 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
226 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
227 $sTemplate = $this->replaceTablespace(
229 CONST_Tablespace_Address_Data,
232 $sTemplate = $this->replaceTablespace(
233 '{ts:address-index}',
234 CONST_Tablespace_Address_Index,
237 $sTemplate = $this->replaceTablespace(
239 CONST_Tablespace_Search_Data,
242 $sTemplate = $this->replaceTablespace(
244 CONST_Tablespace_Search_Index,
247 $sTemplate = $this->replaceTablespace(
249 CONST_Tablespace_Aux_Data,
252 $sTemplate = $this->replaceTablespace(
254 CONST_Tablespace_Aux_Index,
258 $this->pgsqlRunScript($sTemplate, false);
261 $this->pgExec('DROP TABLE search_name');
264 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
265 $oAlParser->createTable($this->oDB, 'address_levels');
268 public function createPartitionTables()
270 info('Create Partition Tables');
272 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
273 $sTemplate = $this->replaceTablespace(
275 CONST_Tablespace_Address_Data,
279 $sTemplate = $this->replaceTablespace(
280 '{ts:address-index}',
281 CONST_Tablespace_Address_Index,
285 $sTemplate = $this->replaceTablespace(
287 CONST_Tablespace_Search_Data,
291 $sTemplate = $this->replaceTablespace(
293 CONST_Tablespace_Search_Index,
297 $sTemplate = $this->replaceTablespace(
299 CONST_Tablespace_Aux_Data,
303 $sTemplate = $this->replaceTablespace(
305 CONST_Tablespace_Aux_Index,
309 $this->pgsqlRunPartitionScript($sTemplate);
312 public function createPartitionFunctions()
314 info('Create Partition Functions');
316 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
317 $this->pgsqlRunPartitionScript($sTemplate);
320 public function importWikipediaArticles()
322 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
323 if (file_exists($sWikiArticlesFile)) {
324 info('Importing wikipedia articles and redirects');
325 $this->pgExec('DROP TABLE IF EXISTS wikipedia_article');
326 $this->pgExec('DROP TABLE IF EXISTS wikipedia_redirect');
327 $this->pgsqlRunScriptFile($sWikiArticlesFile);
329 warn('wikipedia importance dump file not found - places will have default importance');
333 public function loadData($bDisableTokenPrecalc)
335 info('Drop old Data');
337 $this->pgExec('TRUNCATE word');
339 $this->pgExec('TRUNCATE placex');
341 $this->pgExec('TRUNCATE location_property_osmline');
343 $this->pgExec('TRUNCATE place_addressline');
345 $this->pgExec('TRUNCATE location_area');
347 if (!$this->dbReverseOnly()) {
348 $this->pgExec('TRUNCATE search_name');
351 $this->pgExec('TRUNCATE search_name_blank');
353 $this->pgExec('DROP SEQUENCE seq_place');
355 $this->pgExec('CREATE SEQUENCE seq_place start 100000');
358 $sSQL = 'select distinct partition from country_name';
359 $aPartitions = $this->oDB->getCol($sSQL);
361 if (!$this->bNoPartitions) $aPartitions[] = 0;
362 foreach ($aPartitions as $sPartition) {
363 $this->pgExec('TRUNCATE location_road_'.$sPartition);
367 // used by getorcreate_word_id to ignore frequent partial words
368 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
369 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
370 $this->pgExec($sSQL);
373 // pre-create the word list
374 if (!$bDisableTokenPrecalc) {
375 info('Loading word list');
376 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
380 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
382 $aDBInstances = array();
383 $iLoadThreads = max(1, $this->iInstances - 1);
384 for ($i = 0; $i < $iLoadThreads; $i++) {
385 // https://secure.php.net/manual/en/function.pg-connect.php
386 $DSN = CONST_Database_DSN;
387 $DSN = preg_replace('/^pgsql:/', '', $DSN);
388 $DSN = preg_replace('/;/', ' ', $DSN);
389 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
390 pg_ping($aDBInstances[$i]);
393 for ($i = 0; $i < $iLoadThreads; $i++) {
394 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
395 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
396 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
397 $sSQL .= ' and ST_IsValid(geometry)';
398 if ($this->bVerbose) echo "$sSQL\n";
399 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
400 fail(pg_last_error($aDBInstances[$i]));
404 // last thread for interpolation lines
405 // https://secure.php.net/manual/en/function.pg-connect.php
406 $DSN = CONST_Database_DSN;
407 $DSN = preg_replace('/^pgsql:/', '', $DSN);
408 $DSN = preg_replace('/;/', ' ', $DSN);
409 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
410 pg_ping($aDBInstances[$iLoadThreads]);
411 $sSQL = 'insert into location_property_osmline';
412 $sSQL .= ' (osm_id, address, linegeo)';
413 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
414 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
415 if ($this->bVerbose) echo "$sSQL\n";
416 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
417 fail(pg_last_error($aDBInstances[$iLoadThreads]));
421 for ($i = 0; $i <= $iLoadThreads; $i++) {
422 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
423 $resultStatus = pg_result_status($hPGresult);
424 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
425 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
426 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
427 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
428 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
429 $resultError = pg_result_error($hPGresult);
430 echo '-- error text ' . $i . ': ' . $resultError . "\n";
436 fail('SQL errors loading placex and/or location_property_osmline tables');
439 for ($i = 0; $i < $this->iInstances; $i++) {
440 pg_close($aDBInstances[$i]);
444 info('Reanalysing database');
445 $this->pgsqlRunScript('ANALYSE');
447 $sDatabaseDate = getDatabaseDate($this->oDB);
448 $this->oDB->exec('TRUNCATE import_status');
449 if (!$sDatabaseDate) {
450 warn('could not determine database date.');
452 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
453 $this->oDB->exec($sSQL);
454 echo "Latest data imported from $sDatabaseDate.\n";
458 public function importTigerData()
460 info('Import Tiger data');
462 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
463 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
464 if (empty($aFilenames)) return;
466 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
467 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
468 $sTemplate = $this->replaceTablespace(
470 CONST_Tablespace_Aux_Data,
473 $sTemplate = $this->replaceTablespace(
475 CONST_Tablespace_Aux_Index,
478 $this->pgsqlRunScript($sTemplate, false);
480 $aDBInstances = array();
481 for ($i = 0; $i < $this->iInstances; $i++) {
482 // https://secure.php.net/manual/en/function.pg-connect.php
483 $DSN = CONST_Database_DSN;
484 $DSN = preg_replace('/^pgsql:/', '', $DSN);
485 $DSN = preg_replace('/;/', ' ', $DSN);
486 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
487 pg_ping($aDBInstances[$i]);
490 foreach ($aFilenames as $sFile) {
492 $hFile = fopen($sFile, 'r');
493 $sSQL = fgets($hFile, 100000);
496 for ($i = 0; $i < $this->iInstances; $i++) {
497 if (!pg_connection_busy($aDBInstances[$i])) {
498 while (pg_get_result($aDBInstances[$i]));
499 $sSQL = fgets($hFile, 100000);
501 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
503 if ($iLines == 1000) {
516 for ($i = 0; $i < $this->iInstances; $i++) {
517 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
524 for ($i = 0; $i < $this->iInstances; $i++) {
525 pg_close($aDBInstances[$i]);
528 info('Creating indexes on Tiger data');
529 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
530 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
531 $sTemplate = $this->replaceTablespace(
533 CONST_Tablespace_Aux_Data,
536 $sTemplate = $this->replaceTablespace(
538 CONST_Tablespace_Aux_Index,
541 $this->pgsqlRunScript($sTemplate, false);
544 public function calculatePostcodes($bCMDResultAll)
546 info('Calculate Postcodes');
547 $this->pgExec('TRUNCATE location_postcode');
549 $sSQL = 'INSERT INTO location_postcode';
550 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
551 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
552 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
553 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
554 $sSQL .= ' FROM placex';
555 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
556 $sSQL .= ' AND geometry IS NOT null';
557 $sSQL .= ' GROUP BY country_code, pc';
558 $this->pgExec($sSQL);
560 // only add postcodes that are not yet available in OSM
561 $sSQL = 'INSERT INTO location_postcode';
562 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
563 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
564 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
565 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
566 $sSQL .= ' (SELECT postcode FROM location_postcode';
567 $sSQL .= " WHERE country_code = 'us')";
568 $this->pgExec($sSQL);
570 // add missing postcodes for GB (if available)
571 $sSQL = 'INSERT INTO location_postcode';
572 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
573 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
574 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
575 $sSQL .= ' (SELECT postcode FROM location_postcode';
576 $sSQL .= " WHERE country_code = 'gb')";
577 $this->pgExec($sSQL);
579 if (!$bCMDResultAll) {
580 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
581 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
582 $this->pgExec($sSQL);
585 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
586 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
587 $this->pgExec($sSQL);
590 public function index($bIndexNoanalyse)
593 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i'
594 .' -d '.escapeshellarg($this->aDSNInfo['database'])
595 .' -P '.escapeshellarg($this->aDSNInfo['port'])
596 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
597 if (isset($this->aDSNInfo['hostspec'])) {
598 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
600 if (isset($this->aDSNInfo['username'])) {
601 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
604 info('Index ranks 0 - 4');
605 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
607 fail('error status ' . $iStatus . ' running nominatim!');
609 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
611 info('Index ranks 5 - 25');
612 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
614 fail('error status ' . $iStatus . ' running nominatim!');
616 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
618 info('Index ranks 26 - 30');
619 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
621 fail('error status ' . $iStatus . ' running nominatim!');
624 info('Index postcodes');
625 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
626 $this->pgExec($sSQL);
629 public function createSearchIndices()
631 info('Create Search indices');
633 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
634 if (!$this->dbReverseOnly()) {
635 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
637 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
638 $sTemplate = $this->replaceTablespace(
639 '{ts:address-index}',
640 CONST_Tablespace_Address_Index,
643 $sTemplate = $this->replaceTablespace(
645 CONST_Tablespace_Search_Index,
648 $sTemplate = $this->replaceTablespace(
650 CONST_Tablespace_Aux_Index,
653 $this->pgsqlRunScript($sTemplate);
656 public function createCountryNames()
658 info('Create search index for default country names');
660 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
661 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
662 $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');
663 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
664 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
665 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
666 if (CONST_Languages) {
669 foreach (explode(',', CONST_Languages) as $sLang) {
670 $sSQL .= $sDelim."'name:$sLang'";
675 // all include all simple name tags
676 $sSQL .= "like 'name:%'";
679 $this->pgsqlRunScript($sSQL);
682 public function drop()
684 info('Drop tables only required for updates');
686 // The implementation is potentially a bit dangerous because it uses
687 // a positive selection of tables to keep, and deletes everything else.
688 // Including any tables that the unsuspecting user might have manually
689 // created. USE AT YOUR OWN PERIL.
690 // tables we want to keep. everything else goes.
691 $aKeepTables = array(
697 'location_property*',
710 $aDropTables = array();
711 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
713 foreach ($aHaveTables as $sTable) {
715 foreach ($aKeepTables as $sKeep) {
716 if (fnmatch($sKeep, $sTable)) {
721 if (!$bFound) array_push($aDropTables, $sTable);
723 foreach ($aDropTables as $sDrop) {
724 if ($this->bVerbose) echo "Dropping table $sDrop\n";
725 $this->oDB->exec("DROP TABLE IF EXISTS $sDrop CASCADE");
728 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
729 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
730 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
731 unlink(CONST_Osm2pgsql_Flatnode_File);
736 private function pgsqlRunScript($sScript, $bfatal = true)
746 private function createSqlFunctions()
748 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
749 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
750 if ($this->bEnableDiffUpdates) {
751 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
753 if ($this->bEnableDebugStatements) {
754 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
756 if (CONST_Limit_Reindexing) {
757 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
759 if (!CONST_Use_US_Tiger_Data) {
760 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
762 if (!CONST_Use_Aux_Location_data) {
763 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
766 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
767 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
769 $this->pgsqlRunScript($sTemplate);
772 private function pgsqlRunPartitionScript($sTemplate)
774 $sSQL = 'select distinct partition from country_name';
775 $aPartitions = $this->oDB->getCol($sSQL);
776 if (!$this->bNoPartitions) $aPartitions[] = 0;
778 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
779 foreach ($aMatches as $aMatch) {
781 foreach ($aPartitions as $sPartitionName) {
782 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
784 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
787 $this->pgsqlRunScript($sTemplate);
790 private function pgsqlRunScriptFile($sFilename)
792 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
795 .' -p '.escapeshellarg($this->aDSNInfo['port'])
796 .' -d '.escapeshellarg($this->aDSNInfo['database']);
797 if (!$this->bVerbose) {
800 if (isset($this->aDSNInfo['hostspec'])) {
801 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
803 if (isset($this->aDSNInfo['username'])) {
804 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
807 if (isset($this->aDSNInfo['password'])) {
808 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
811 if (preg_match('/\\.gz$/', $sFilename)) {
812 $aDescriptors = array(
813 0 => array('pipe', 'r'),
814 1 => array('pipe', 'w'),
815 2 => array('file', '/dev/null', 'a')
817 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
818 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
819 $aReadPipe = $ahGzipPipes[1];
820 fclose($ahGzipPipes[0]);
822 $sCMD .= ' -f '.escapeshellarg($sFilename);
823 $aReadPipe = array('pipe', 'r');
825 $aDescriptors = array(
827 1 => array('pipe', 'w'),
828 2 => array('file', '/dev/null', 'a')
831 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
832 if (!is_resource($hProcess)) fail('unable to start pgsql');
833 // TODO: error checking
834 while (!feof($ahPipes[1])) {
835 echo fread($ahPipes[1], 4096);
838 $iReturn = proc_close($hProcess);
840 fail("pgsql returned with error code ($iReturn)");
843 fclose($ahGzipPipes[1]);
844 proc_close($hGzipProcess);
848 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
851 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
853 $sSql = str_replace($sTemplate, '', $sSql);
858 private function runWithPgEnv($sCmd)
860 if ($this->bVerbose) {
861 echo "Execute: $sCmd\n";
866 if (isset($this->aDSNInfo['password'])) {
867 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
870 return runWithEnv($sCmd, $aProcEnv);
874 * Execute the SQL command on the open database.
876 * @param string $sSQL SQL command to execute.
880 * @pre connect() must have been called.
882 private function pgExec($sSQL)
884 $this->oDB->exec($sSQL);
888 * Check if the database is in reverse-only mode.
890 * @return True if there is no search_name table and infrastructure.
892 private function dbReverseOnly()
894 return !($this->oDB->tableExists('search_name'));