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 createPartitionTables()
240 info('Create Partition Tables');
242 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
243 $sTemplate = $this->replaceSqlPatterns($sTemplate);
245 $this->pgsqlRunPartitionScript($sTemplate);
248 public function createPartitionFunctions()
250 info('Create Partition Functions');
252 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
253 $this->pgsqlRunPartitionScript($sTemplate);
256 public function importWikipediaArticles()
258 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
259 if (file_exists($sWikiArticlesFile)) {
260 info('Importing wikipedia articles and redirects');
261 $this->dropTable('wikipedia_article');
262 $this->dropTable('wikipedia_redirect');
263 $this->pgsqlRunScriptFile($sWikiArticlesFile);
265 warn('wikipedia importance dump file not found - places will have default importance');
269 public function loadData($bDisableTokenPrecalc)
271 info('Drop old Data');
273 $this->oDB->exec('TRUNCATE word');
275 $this->oDB->exec('TRUNCATE placex');
277 $this->oDB->exec('TRUNCATE location_property_osmline');
279 $this->oDB->exec('TRUNCATE place_addressline');
281 $this->oDB->exec('TRUNCATE location_area');
283 if (!$this->dbReverseOnly()) {
284 $this->oDB->exec('TRUNCATE search_name');
287 $this->oDB->exec('TRUNCATE search_name_blank');
289 $this->oDB->exec('DROP SEQUENCE seq_place');
291 $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
294 $sSQL = 'select distinct partition from country_name';
295 $aPartitions = $this->oDB->getCol($sSQL);
297 if (!$this->bNoPartitions) $aPartitions[] = 0;
298 foreach ($aPartitions as $sPartition) {
299 $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
303 // used by getorcreate_word_id to ignore frequent partial words
304 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
305 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
306 $this->oDB->exec($sSQL);
309 // pre-create the word list
310 if (!$bDisableTokenPrecalc) {
311 info('Loading word list');
312 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
316 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
318 $aDBInstances = array();
319 $iLoadThreads = max(1, $this->iInstances - 1);
320 for ($i = 0; $i < $iLoadThreads; $i++) {
321 // https://secure.php.net/manual/en/function.pg-connect.php
322 $DSN = CONST_Database_DSN;
323 $DSN = preg_replace('/^pgsql:/', '', $DSN);
324 $DSN = preg_replace('/;/', ' ', $DSN);
325 $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
326 pg_ping($aDBInstances[$i]);
329 for ($i = 0; $i < $iLoadThreads; $i++) {
330 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
331 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
332 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
333 $sSQL .= ' and ST_IsValid(geometry)';
334 if ($this->bVerbose) echo "$sSQL\n";
335 if (!pg_send_query($aDBInstances[$i], $sSQL)) {
336 fail(pg_last_error($aDBInstances[$i]));
340 // last thread for interpolation lines
341 // https://secure.php.net/manual/en/function.pg-connect.php
342 $DSN = CONST_Database_DSN;
343 $DSN = preg_replace('/^pgsql:/', '', $DSN);
344 $DSN = preg_replace('/;/', ' ', $DSN);
345 $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
346 pg_ping($aDBInstances[$iLoadThreads]);
347 $sSQL = 'insert into location_property_osmline';
348 $sSQL .= ' (osm_id, address, linegeo)';
349 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
350 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
351 if ($this->bVerbose) echo "$sSQL\n";
352 if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
353 fail(pg_last_error($aDBInstances[$iLoadThreads]));
357 for ($i = 0; $i <= $iLoadThreads; $i++) {
358 while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
359 $resultStatus = pg_result_status($hPGresult);
360 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
361 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
362 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
363 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
364 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
365 $resultError = pg_result_error($hPGresult);
366 echo '-- error text ' . $i . ': ' . $resultError . "\n";
372 fail('SQL errors loading placex and/or location_property_osmline tables');
375 for ($i = 0; $i < $this->iInstances; $i++) {
376 pg_close($aDBInstances[$i]);
380 info('Reanalysing database');
381 $this->pgsqlRunScript('ANALYSE');
383 $sDatabaseDate = getDatabaseDate($this->oDB);
384 $this->oDB->exec('TRUNCATE import_status');
385 if (!$sDatabaseDate) {
386 warn('could not determine database date.');
388 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
389 $this->oDB->exec($sSQL);
390 echo "Latest data imported from $sDatabaseDate.\n";
394 public function importTigerData()
396 info('Import Tiger data');
398 $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
399 info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
400 if (empty($aFilenames)) return;
402 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
403 $sTemplate = $this->replaceSqlPatterns($sTemplate);
405 $this->pgsqlRunScript($sTemplate, false);
407 $aDBInstances = array();
408 for ($i = 0; $i < $this->iInstances; $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 | PGSQL_CONNECT_ASYNC);
414 pg_ping($aDBInstances[$i]);
417 foreach ($aFilenames as $sFile) {
419 $hFile = fopen($sFile, 'r');
420 $sSQL = fgets($hFile, 100000);
423 for ($i = 0; $i < $this->iInstances; $i++) {
424 if (!pg_connection_busy($aDBInstances[$i])) {
425 while (pg_get_result($aDBInstances[$i]));
426 $sSQL = fgets($hFile, 100000);
428 if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
430 if ($iLines == 1000) {
443 for ($i = 0; $i < $this->iInstances; $i++) {
444 if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
451 for ($i = 0; $i < $this->iInstances; $i++) {
452 pg_close($aDBInstances[$i]);
455 info('Creating indexes on Tiger data');
456 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
457 $sTemplate = $this->replaceSqlPatterns($sTemplate);
459 $this->pgsqlRunScript($sTemplate, false);
462 public function calculatePostcodes($bCMDResultAll)
464 info('Calculate Postcodes');
465 $this->oDB->exec('TRUNCATE location_postcode');
467 $sSQL = 'INSERT INTO location_postcode';
468 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
469 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
470 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
471 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
472 $sSQL .= ' FROM placex';
473 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
474 $sSQL .= ' AND geometry IS NOT null';
475 $sSQL .= ' GROUP BY country_code, pc';
476 $this->oDB->exec($sSQL);
478 // only add postcodes that are not yet available in OSM
479 $sSQL = 'INSERT INTO location_postcode';
480 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
481 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
482 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
483 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
484 $sSQL .= ' (SELECT postcode FROM location_postcode';
485 $sSQL .= " WHERE country_code = 'us')";
486 $this->oDB->exec($sSQL);
488 // add missing postcodes for GB (if available)
489 $sSQL = 'INSERT INTO location_postcode';
490 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
491 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
492 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
493 $sSQL .= ' (SELECT postcode FROM location_postcode';
494 $sSQL .= " WHERE country_code = 'gb')";
495 $this->oDB->exec($sSQL);
497 if (!$bCMDResultAll) {
498 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
499 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
500 $this->oDB->exec($sSQL);
503 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
504 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
505 $this->oDB->exec($sSQL);
508 public function index($bIndexNoanalyse)
511 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i'
512 .' -d '.escapeshellarg($this->aDSNInfo['database'])
513 .' -P '.escapeshellarg($this->aDSNInfo['port'])
514 .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
515 if (isset($this->aDSNInfo['hostspec'])) {
516 $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
518 if (isset($this->aDSNInfo['username'])) {
519 $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
522 info('Index ranks 0 - 4');
523 $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
525 fail('error status ' . $iStatus . ' running nominatim!');
527 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
529 info('Index ranks 5 - 25');
530 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
532 fail('error status ' . $iStatus . ' running nominatim!');
534 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
536 info('Index ranks 26 - 30');
537 $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
539 fail('error status ' . $iStatus . ' running nominatim!');
542 info('Index postcodes');
543 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
544 $this->oDB->exec($sSQL);
547 public function createSearchIndices()
549 info('Create Search indices');
551 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
552 if (!$this->dbReverseOnly()) {
553 $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
555 $sTemplate = $this->replaceSqlPatterns($sTemplate);
557 $this->pgsqlRunScript($sTemplate);
560 public function createCountryNames()
562 info('Create search index for default country names');
564 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
565 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
566 $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');
567 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
568 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
569 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
570 if (CONST_Languages) {
573 foreach (explode(',', CONST_Languages) as $sLang) {
574 $sSQL .= $sDelim."'name:$sLang'";
579 // all include all simple name tags
580 $sSQL .= "like 'name:%'";
583 $this->pgsqlRunScript($sSQL);
586 public function drop()
588 info('Drop tables only required for updates');
590 // The implementation is potentially a bit dangerous because it uses
591 // a positive selection of tables to keep, and deletes everything else.
592 // Including any tables that the unsuspecting user might have manually
593 // created. USE AT YOUR OWN PERIL.
594 // tables we want to keep. everything else goes.
595 $aKeepTables = array(
601 'location_property*',
614 $aDropTables = array();
615 $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
617 foreach ($aHaveTables as $sTable) {
619 foreach ($aKeepTables as $sKeep) {
620 if (fnmatch($sKeep, $sTable)) {
625 if (!$bFound) array_push($aDropTables, $sTable);
627 foreach ($aDropTables as $sDrop) {
628 $this->dropTable($sDrop);
631 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
632 if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
633 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
634 unlink(CONST_Osm2pgsql_Flatnode_File);
639 private function pgsqlRunScript($sScript, $bfatal = true)
649 private function createSqlFunctions()
651 $sBasePath = CONST_BasePath.'/sql/functions/';
652 $sTemplate = file_get_contents($sBasePath.'utils.sql');
653 $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
654 $sTemplate .= file_get_contents($sBasePath.'importance.sql');
655 $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
656 $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
657 $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
658 $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
659 $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
660 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
661 if ($this->bEnableDiffUpdates) {
662 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
664 if ($this->bEnableDebugStatements) {
665 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
667 if (CONST_Limit_Reindexing) {
668 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
670 if (!CONST_Use_US_Tiger_Data) {
671 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
673 if (!CONST_Use_Aux_Location_data) {
674 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
677 $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
678 $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
680 $this->pgsqlRunScript($sTemplate);
683 private function pgsqlRunPartitionScript($sTemplate)
685 $sSQL = 'select distinct partition from country_name';
686 $aPartitions = $this->oDB->getCol($sSQL);
687 if (!$this->bNoPartitions) $aPartitions[] = 0;
689 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
690 foreach ($aMatches as $aMatch) {
692 foreach ($aPartitions as $sPartitionName) {
693 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
695 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
698 $this->pgsqlRunScript($sTemplate);
701 private function pgsqlRunScriptFile($sFilename)
703 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
706 .' -p '.escapeshellarg($this->aDSNInfo['port'])
707 .' -d '.escapeshellarg($this->aDSNInfo['database']);
708 if (!$this->bVerbose) {
711 if (isset($this->aDSNInfo['hostspec'])) {
712 $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
714 if (isset($this->aDSNInfo['username'])) {
715 $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
718 if (isset($this->aDSNInfo['password'])) {
719 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
722 if (preg_match('/\\.gz$/', $sFilename)) {
723 $aDescriptors = array(
724 0 => array('pipe', 'r'),
725 1 => array('pipe', 'w'),
726 2 => array('file', '/dev/null', 'a')
728 $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
729 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
730 $aReadPipe = $ahGzipPipes[1];
731 fclose($ahGzipPipes[0]);
733 $sCMD .= ' -f '.escapeshellarg($sFilename);
734 $aReadPipe = array('pipe', 'r');
736 $aDescriptors = array(
738 1 => array('pipe', 'w'),
739 2 => array('file', '/dev/null', 'a')
742 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
743 if (!is_resource($hProcess)) fail('unable to start pgsql');
744 // TODO: error checking
745 while (!feof($ahPipes[1])) {
746 echo fread($ahPipes[1], 4096);
749 $iReturn = proc_close($hProcess);
751 fail("pgsql returned with error code ($iReturn)");
754 fclose($ahGzipPipes[1]);
755 proc_close($hGzipProcess);
759 private function replaceSqlPatterns($sSql)
761 $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
764 '{ts:address-data}' => CONST_Tablespace_Address_Data,
765 '{ts:address-index}' => CONST_Tablespace_Address_Index,
766 '{ts:search-data}' => CONST_Tablespace_Search_Data,
767 '{ts:search-index}' => CONST_Tablespace_Search_Index,
768 '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
769 '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
772 foreach ($aPatterns as $sPattern => $sTablespace) {
774 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
776 $sSql = str_replace($sPattern, '', $sSql);
783 private function runWithPgEnv($sCmd)
785 if ($this->bVerbose) {
786 echo "Execute: $sCmd\n";
791 if (isset($this->aDSNInfo['password'])) {
792 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
795 return runWithEnv($sCmd, $aProcEnv);
799 * Drop table with the given name if it exists.
801 * @param string $sName Name of table to remove.
805 * @pre connect() must have been called.
807 private function dropTable($sName)
809 if ($this->bVerbose) echo "Dropping table $sName\n";
810 $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
814 * Check if the database is in reverse-only mode.
816 * @return True if there is no search_name table and infrastructure.
818 private function dbReverseOnly()
820 return !($this->oDB->tableExists('search_name'));