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 = $this->replaceSqlPatterns($sTemplate);
228 $this->pgsqlRunScript($sTemplate, false);
231 $this->dropTable('search_name');
234 $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
235 $oAlParser->createTable($this->oDB, 'address_levels');
238 public function createTableTriggers()
240 info('Create Tables');
242 $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
243 $sTemplate = $this->replaceSqlPatterns($sTemplate);
245 $this->pgsqlRunScript($sTemplate, false);
248 public function createPartitionTables()
250 info('Create Partition Tables');
252 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
253 $sTemplate = $this->replaceSqlPatterns($sTemplate);
255 $this->pgsqlRunPartitionScript($sTemplate);
258 public function createPartitionFunctions()
260 info('Create Partition Functions');
262 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
263 $this->pgsqlRunPartitionScript($sTemplate);
266 public function importWikipediaArticles()
268 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
269 if (file_exists($sWikiArticlesFile)) {
270 info('Importing wikipedia articles and redirects');
271 $this->dropTable('wikipedia_article');
272 $this->dropTable('wikipedia_redirect');
273 $this->pgsqlRunScriptFile($sWikiArticlesFile);
275 warn('wikipedia importance dump file not found - places will have default importance');
279 public function loadData($bDisableTokenPrecalc)
281 info('Drop old Data');
283 $this->oDB->exec('TRUNCATE word');
285 $this->oDB->exec('TRUNCATE placex');
287 $this->oDB->exec('TRUNCATE location_property_osmline');
289 $this->oDB->exec('TRUNCATE place_addressline');
291 $this->oDB->exec('TRUNCATE location_area');
293 if (!$this->dbReverseOnly()) {
294 $this->oDB->exec('TRUNCATE search_name');
297 $this->oDB->exec('TRUNCATE search_name_blank');
299 $this->oDB->exec('DROP SEQUENCE seq_place');
301 $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
304 $sSQL = 'select distinct partition from country_name';
305 $aPartitions = $this->oDB->getCol($sSQL);
307 if (!$this->bNoPartitions) $aPartitions[] = 0;
308 foreach ($aPartitions as $sPartition) {
309 $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
313 // used by getorcreate_word_id to ignore frequent partial words
314 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
315 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
316 $this->oDB->exec($sSQL);
319 // pre-create the word list
320 if (!$bDisableTokenPrecalc) {
321 info('Loading word list');
322 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
326 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
328 $aDBInstances = array();
329 $iLoadThreads = max(1, $this->iInstances - 1);
330 for ($i = 0; $i < $iLoadThreads; $i++) {
331 // https://secure.php.net/manual/en/function.pg-connect.php
332 $DSN = CONST_Database_DSN;
333 $DSN = preg_replace('/^pgsql:/', '', $DSN);
334 $DSN = preg_replace('/;/', ' ', $DSN);
335 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
336 pg_ping($aDBInstances[$i]);
339 for ($i = 0; $i < $iLoadThreads; $i++) {
340 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
341 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
342 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
343 $sSQL .= ' and ST_IsValid(geometry)';
344 if ($this->bVerbose) echo "$sSQL\n";
345 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
346 fail(pg_last_error($aDBInstances[$i]));
350 // last thread for interpolation lines
351 // https://secure.php.net/manual/en/function.pg-connect.php
352 $DSN = CONST_Database_DSN;
353 $DSN = preg_replace('/^pgsql:/', '', $DSN);
354 $DSN = preg_replace('/;/', ' ', $DSN);
355 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
356 pg_ping($aDBInstances[$iLoadThreads]);
357 $sSQL = 'insert into location_property_osmline';
358 $sSQL .= ' (osm_id, address, linegeo)';
359 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
360 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
361 if ($this->bVerbose) echo "$sSQL\n";
362 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
363 fail(pg_last_error($aDBInstances[$iLoadThreads]));
367 for ($i = 0; $i <= $iLoadThreads; $i++) {
368 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
369 $resultStatus = pg_result_status($hPGresult);
370 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
371 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
372 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
373 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
374 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
375 $resultError = pg_result_error($hPGresult);
376 echo '-- error text ' . $i . ': ' . $resultError . "\n";
382 fail('SQL errors loading placex and/or location_property_osmline tables');
385 for ($i = 0; $i < $this->iInstances; $i++) {
386 pg_close($aDBInstances[$i]);
390 info('Reanalysing database');
391 $this->pgsqlRunScript('ANALYSE');
393 $sDatabaseDate = getDatabaseDate($this->oDB);
394 $this->oDB->exec('TRUNCATE import_status');
395 if (!$sDatabaseDate) {
396 warn('could not determine database date.');
398 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
399 $this->oDB->exec($sSQL);
400 echo "Latest data imported from $sDatabaseDate.\n";
404 public function importTigerData()
406 info('Import Tiger data');
408 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
409 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
410 if (empty($aFilenames)) return;
412 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
413 $sTemplate = $this->replaceSqlPatterns($sTemplate);
415 $this->pgsqlRunScript($sTemplate, false);
417 $aDBInstances = array();
418 for ($i = 0; $i < $this->iInstances; $i++) {
419 // https://secure.php.net/manual/en/function.pg-connect.php
420 $DSN = CONST_Database_DSN;
421 $DSN = preg_replace('/^pgsql:/', '', $DSN);
422 $DSN = preg_replace('/;/', ' ', $DSN);
423 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
424 pg_ping($aDBInstances[$i]);
427 foreach ($aFilenames as $sFile) {
429 $hFile = fopen($sFile, 'r');
430 $sSQL = fgets($hFile, 100000);
433 for ($i = 0; $i < $this->iInstances; $i++) {
434 if (!pg_connection_busy($aDBInstances[$i])) {
435 while (pg_get_result($aDBInstances[$i]));
436 $sSQL = fgets($hFile, 100000);
438 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
440 if ($iLines == 1000) {
453 for ($i = 0; $i < $this->iInstances; $i++) {
454 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
461 for ($i = 0; $i < $this->iInstances; $i++) {
462 pg_close($aDBInstances[$i]);
465 info('Creating indexes on Tiger data');
466 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
467 $sTemplate = $this->replaceSqlPatterns($sTemplate);
469 $this->pgsqlRunScript($sTemplate, false);
472 public function calculatePostcodes($bCMDResultAll)
474 info('Calculate Postcodes');
475 $this->oDB->exec('TRUNCATE location_postcode');
477 $sSQL = 'INSERT INTO location_postcode';
478 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
479 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
480 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
481 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
482 $sSQL .= ' FROM placex';
483 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
484 $sSQL .= ' AND geometry IS NOT null';
485 $sSQL .= ' GROUP BY country_code, pc';
486 $this->oDB->exec($sSQL);
488 // only add postcodes that are not yet available in OSM
489 $sSQL = 'INSERT INTO location_postcode';
490 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
491 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
492 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
493 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
494 $sSQL .= ' (SELECT postcode FROM location_postcode';
495 $sSQL .= " WHERE country_code = 'us')";
496 $this->oDB->exec($sSQL);
498 // add missing postcodes for GB (if available)
499 $sSQL = 'INSERT INTO location_postcode';
500 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
501 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
502 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
503 $sSQL .= ' (SELECT postcode FROM location_postcode';
504 $sSQL .= " WHERE country_code = 'gb')";
505 $this->oDB->exec($sSQL);
507 if (!$bCMDResultAll) {
508 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
509 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
510 $this->oDB->exec($sSQL);
513 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
514 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
515 $this->oDB->exec($sSQL);
518 public function index($bIndexNoanalyse)
521 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i'
522 .' -d '.escapeshellarg($this->aDSNInfo['database'])
523 .' -P '.escapeshellarg($this->aDSNInfo['port'])
524 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
525 if (isset($this->aDSNInfo['hostspec'])) {
526 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
528 if (isset($this->aDSNInfo['username'])) {
529 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
532 info('Index ranks 0 - 4');
533 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
535 fail('error status ' . $iStatus . ' running nominatim!');
537 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
539 info('Index ranks 5 - 25');
540 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
542 fail('error status ' . $iStatus . ' running nominatim!');
544 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
546 info('Index ranks 26 - 30');
547 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
549 fail('error status ' . $iStatus . ' running nominatim!');
552 info('Index postcodes');
553 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
554 $this->oDB->exec($sSQL);
557 public function createSearchIndices()
559 info('Create Search indices');
561 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
562 if (!$this->dbReverseOnly()) {
563 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
565 $sTemplate = $this->replaceSqlPatterns($sTemplate);
567 $this->pgsqlRunScript($sTemplate);
570 public function createCountryNames()
572 info('Create search index for default country names');
574 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
575 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
576 $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');
577 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
578 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
579 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
580 if (CONST_Languages) {
583 foreach (explode(',', CONST_Languages) as $sLang) {
584 $sSQL .= $sDelim."'name:$sLang'";
589 // all include all simple name tags
590 $sSQL .= "like 'name:%'";
593 $this->pgsqlRunScript($sSQL);
596 public function drop()
598 info('Drop tables only required for updates');
600 // The implementation is potentially a bit dangerous because it uses
601 // a positive selection of tables to keep, and deletes everything else.
602 // Including any tables that the unsuspecting user might have manually
603 // created. USE AT YOUR OWN PERIL.
604 // tables we want to keep. everything else goes.
605 $aKeepTables = array(
611 'location_property*',
624 $aDropTables = array();
625 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
627 foreach ($aHaveTables as $sTable) {
629 foreach ($aKeepTables as $sKeep) {
630 if (fnmatch($sKeep, $sTable)) {
635 if (!$bFound) array_push($aDropTables, $sTable);
637 foreach ($aDropTables as $sDrop) {
638 $this->dropTable($sDrop);
641 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
642 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
643 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
644 unlink(CONST_Osm2pgsql_Flatnode_File);
649 private function pgsqlRunScript($sScript, $bfatal = true)
659 private function createSqlFunctions()
661 $sBasePath = CONST_BasePath.'/sql/functions/';
662 $sTemplate = file_get_contents($sBasePath.'utils.sql');
663 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
664 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
665 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
666 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
667 if ($this->oDB->tableExists('place')) {
668 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
670 if ($this->oDB->tableExists('placex')) {
671 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
673 if ($this->oDB->tableExists('location_postcode')) {
674 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
676 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
677 if ($this->bEnableDiffUpdates) {
678 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
680 if ($this->bEnableDebugStatements) {
681 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
683 if (CONST_Limit_Reindexing) {
684 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
686 if (!CONST_Use_US_Tiger_Data) {
687 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
689 if (!CONST_Use_Aux_Location_data) {
690 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
693 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
694 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
696 $this->pgsqlRunScript($sTemplate);
699 private function pgsqlRunPartitionScript($sTemplate)
701 $sSQL = 'select distinct partition from country_name';
702 $aPartitions = $this->oDB->getCol($sSQL);
703 if (!$this->bNoPartitions) $aPartitions[] = 0;
705 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
706 foreach ($aMatches as $aMatch) {
708 foreach ($aPartitions as $sPartitionName) {
709 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
711 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
714 $this->pgsqlRunScript($sTemplate);
717 private function pgsqlRunScriptFile($sFilename)
719 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
722 .' -p '.escapeshellarg($this->aDSNInfo['port'])
723 .' -d '.escapeshellarg($this->aDSNInfo['database']);
724 if (!$this->bVerbose) {
727 if (isset($this->aDSNInfo['hostspec'])) {
728 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
730 if (isset($this->aDSNInfo['username'])) {
731 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
734 if (isset($this->aDSNInfo['password'])) {
735 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
738 if (preg_match('/\\.gz$/', $sFilename)) {
739 $aDescriptors = array(
740 0 => array('pipe', 'r'),
741 1 => array('pipe', 'w'),
742 2 => array('file', '/dev/null', 'a')
744 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
745 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
746 $aReadPipe = $ahGzipPipes[1];
747 fclose($ahGzipPipes[0]);
749 $sCMD .= ' -f '.escapeshellarg($sFilename);
750 $aReadPipe = array('pipe', 'r');
752 $aDescriptors = array(
754 1 => array('pipe', 'w'),
755 2 => array('file', '/dev/null', 'a')
758 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
759 if (!is_resource($hProcess)) fail('unable to start pgsql');
760 // TODO: error checking
761 while (!feof($ahPipes[1])) {
762 echo fread($ahPipes[1], 4096);
765 $iReturn = proc_close($hProcess);
767 fail("pgsql returned with error code ($iReturn)");
770 fclose($ahGzipPipes[1]);
771 proc_close($hGzipProcess);
775 private function replaceSqlPatterns($sSql)
777 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
780 '{ts:address-data}' => CONST_Tablespace_Address_Data,
781 '{ts:address-index}' => CONST_Tablespace_Address_Index,
782 '{ts:search-data}' => CONST_Tablespace_Search_Data,
783 '{ts:search-index}' => CONST_Tablespace_Search_Index,
784 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
785 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
788 foreach ($aPatterns as $sPattern => $sTablespace) {
790 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
792 $sSql = str_replace($sPattern, '', $sSql);
799 private function runWithPgEnv($sCmd)
801 if ($this->bVerbose) {
802 echo "Execute: $sCmd\n";
807 if (isset($this->aDSNInfo['password'])) {
808 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
811 return runWithEnv($sCmd, $aProcEnv);
815 * Drop table with the given name if it exists.
817 * @param string $sName Name of table to remove.
821 * @pre connect() must have been called.
823 private function dropTable($sName)
825 if ($this->bVerbose) echo "Dropping table $sName\n";
826 $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
830 * Check if the database is in reverse-only mode.
832 * @return True if there is no search_name table and infrastructure.
834 private function dbReverseOnly()
836 return !($this->oDB->tableExists('search_name'));