3 namespace Nominatim\Setup;
 
   5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
 
   9     protected $iCacheMemory;
 
  10     protected $iInstances;
 
  11     protected $sModulePath;
 
  15     protected $sIgnoreErrors;
 
  16     protected $bEnableDiffUpdates;
 
  17     protected $bEnableDebugStatements;
 
  18     protected $bNoPartitions;
 
  19     protected $oDB = null;
 
  21     public function __construct(array $aCMDResult)
 
  23         // by default, use all but one processor, but never more than 15.
 
  24         $this->iInstances = isset($aCMDResult['threads'])
 
  25             ? $aCMDResult['threads']
 
  26             : (min(16, getProcessorCount()) - 1);
 
  28         if ($this->iInstances < 1) {
 
  29             $this->iInstances = 1;
 
  30             warn('resetting threads to '.$this->iInstances);
 
  33         if (isset($aCMDResult['osm2pgsql-cache'])) {
 
  34             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
 
  35         } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
 
  36             // When flatnode files are enabled then disable cache per default.
 
  37             $this->iCacheMemory = 0;
 
  39             // Otherwise: Assume we can steal all the cache memory in the box.
 
  40             $this->iCacheMemory = getCacheMemoryMB();
 
  43         $this->sModulePath = CONST_Database_Module_Path;
 
  44         info('module path: ' . $this->sModulePath);
 
  46         // parse database string
 
  47         $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
 
  48         if (!isset($this->aDSNInfo['port'])) {
 
  49             $this->aDSNInfo['port'] = 5432;
 
  52         // setting member variables based on command line options stored in $aCMDResult
 
  53         $this->bQuiet = $aCMDResult['quiet'];
 
  54         $this->bVerbose = $aCMDResult['verbose'];
 
  56         //setting default values which are not set by the update.php array
 
  57         if (isset($aCMDResult['ignore-errors'])) {
 
  58             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
 
  60             $this->sIgnoreErrors = false;
 
  62         if (isset($aCMDResult['enable-debug-statements'])) {
 
  63             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
 
  65             $this->bEnableDebugStatements = false;
 
  67         if (isset($aCMDResult['no-partitions'])) {
 
  68             $this->bNoPartitions = $aCMDResult['no-partitions'];
 
  70             $this->bNoPartitions = false;
 
  72         if (isset($aCMDResult['enable-diff-updates'])) {
 
  73             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
 
  75             $this->bEnableDiffUpdates = false;
 
  79     public function createDB()
 
  82         $oDB = new \Nominatim\DB;
 
  84         if ($oDB->databaseExists()) {
 
  85             fail('database already exists ('.CONST_Database_DSN.')');
 
  88         $sCreateDBCmd = 'createdb -E UTF-8'
 
  89             .' -p '.escapeshellarg($this->aDSNInfo['port'])
 
  90             .' '.escapeshellarg($this->aDSNInfo['database']);
 
  91         if (isset($this->aDSNInfo['username'])) {
 
  92             $sCreateDBCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
  95         if (isset($this->aDSNInfo['hostspec'])) {
 
  96             $sCreateDBCmd .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
 
  99         $result = $this->runWithPgEnv($sCreateDBCmd);
 
 100         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
 
 103     public function connect()
 
 105         $this->oDB = new \Nominatim\DB();
 
 106         $this->oDB->connect();
 
 109     public function setupDB()
 
 113         $fPostgresVersion = $this->oDB->getPostgresVersion();
 
 114         echo 'Postgres version found: '.$fPostgresVersion."\n";
 
 116         if ($fPostgresVersion < 9.03) {
 
 117             fail('Minimum supported version of Postgresql is 9.3.');
 
 120         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
 
 121         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
 
 123         $fPostgisVersion = $this->oDB->getPostgisVersion();
 
 124         echo 'Postgis version found: '.$fPostgisVersion."\n";
 
 126         if ($fPostgisVersion < 2.2) {
 
 127             echo "Minimum required Postgis version 2.2\n";
 
 131         $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
 
 133             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
 
 134             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
 
 138         // Try accessing the C module, so we know early if something is wrong
 
 139         checkModulePresence(); // raises exception on failure
 
 141         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
 
 142             echo 'Error: you need to download the country_osm_grid first:';
 
 143             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
 
 146         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
 
 147         $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
 
 148         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
 
 149         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
 
 151         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
 
 152         if (file_exists($sPostcodeFilename)) {
 
 153             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 155             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 158         $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
 
 159         if (file_exists($sPostcodeFilename)) {
 
 160             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 162             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 165         if ($this->bNoPartitions) {
 
 166             $this->pgsqlRunScript('update country_name set partition = 0');
 
 170     public function importData($sOSMFile)
 
 174         $osm2pgsql = CONST_Osm2pgsql_Binary;
 
 175         if (!file_exists($osm2pgsql)) {
 
 176             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
 
 177             echo "Normally you should not need to set this manually.\n";
 
 178             fail("osm2pgsql not found in '$osm2pgsql'");
 
 181         $osm2pgsql .= ' -S '.escapeshellarg(CONST_Import_Style);
 
 183         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 184             $osm2pgsql .= ' --flat-nodes '.escapeshellarg(CONST_Osm2pgsql_Flatnode_File);
 
 187         if (CONST_Tablespace_Osm2pgsql_Data)
 
 188             $osm2pgsql .= ' --tablespace-slim-data '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Data);
 
 189         if (CONST_Tablespace_Osm2pgsql_Index)
 
 190             $osm2pgsql .= ' --tablespace-slim-index '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Index);
 
 191         if (CONST_Tablespace_Place_Data)
 
 192             $osm2pgsql .= ' --tablespace-main-data '.escapeshellarg(CONST_Tablespace_Place_Data);
 
 193         if (CONST_Tablespace_Place_Index)
 
 194             $osm2pgsql .= ' --tablespace-main-index '.escapeshellarg(CONST_Tablespace_Place_Index);
 
 195         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
 
 196         $osm2pgsql .= ' -C '.escapeshellarg($this->iCacheMemory);
 
 197         $osm2pgsql .= ' -P '.escapeshellarg($this->aDSNInfo['port']);
 
 198         if (isset($this->aDSNInfo['username'])) {
 
 199             $osm2pgsql .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 201         if (isset($this->aDSNInfo['hostspec'])) {
 
 202             $osm2pgsql .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 204         $osm2pgsql .= ' -d '.escapeshellarg($this->aDSNInfo['database']).' '.escapeshellarg($sOSMFile);
 
 206         $this->runWithPgEnv($osm2pgsql);
 
 208         if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
 
 213     public function createFunctions()
 
 215         info('Create Functions');
 
 217         // Try accessing the C module, so we know early if something is wrong
 
 218         checkModulePresence(); // raises exception on failure
 
 220         $this->createSqlFunctions();
 
 223     public function createTables($bReverseOnly = false)
 
 225         info('Create Tables');
 
 227         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
 
 228         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 230         $this->pgsqlRunScript($sTemplate, false);
 
 233             $this->dropTable('search_name');
 
 236         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
 
 237         $oAlParser->createTable($this->oDB, 'address_levels');
 
 240     public function createTableTriggers()
 
 242         info('Create Tables');
 
 244         $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
 
 245         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 247         $this->pgsqlRunScript($sTemplate, false);
 
 250     public function createPartitionTables()
 
 252         info('Create Partition Tables');
 
 254         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
 
 255         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 257         $this->pgsqlRunPartitionScript($sTemplate);
 
 260     public function createPartitionFunctions()
 
 262         info('Create Partition Functions');
 
 264         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
 
 265         $this->pgsqlRunPartitionScript($sTemplate);
 
 268     public function importWikipediaArticles()
 
 270         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
 
 271         if (file_exists($sWikiArticlesFile)) {
 
 272             info('Importing wikipedia articles and redirects');
 
 273             $this->dropTable('wikipedia_article');
 
 274             $this->dropTable('wikipedia_redirect');
 
 275             $this->pgsqlRunScriptFile($sWikiArticlesFile);
 
 277             warn('wikipedia importance dump file not found - places will have default importance');
 
 281     public function loadData($bDisableTokenPrecalc)
 
 283         info('Drop old Data');
 
 285         $this->oDB->exec('TRUNCATE word');
 
 287         $this->oDB->exec('TRUNCATE placex');
 
 289         $this->oDB->exec('TRUNCATE location_property_osmline');
 
 291         $this->oDB->exec('TRUNCATE place_addressline');
 
 293         $this->oDB->exec('TRUNCATE location_area');
 
 295         if (!$this->dbReverseOnly()) {
 
 296             $this->oDB->exec('TRUNCATE search_name');
 
 299         $this->oDB->exec('TRUNCATE search_name_blank');
 
 301         $this->oDB->exec('DROP SEQUENCE seq_place');
 
 303         $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
 
 306         $sSQL = 'select distinct partition from country_name';
 
 307         $aPartitions = $this->oDB->getCol($sSQL);
 
 309         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 310         foreach ($aPartitions as $sPartition) {
 
 311             $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
 
 315         // used by getorcreate_word_id to ignore frequent partial words
 
 316         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 317         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 318         $this->oDB->exec($sSQL);
 
 321         // pre-create the word list
 
 322         if (!$bDisableTokenPrecalc) {
 
 323             info('Loading word list');
 
 324             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
 
 328         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 330         $aDBInstances = array();
 
 331         $iLoadThreads = max(1, $this->iInstances - 1);
 
 332         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 333             // https://secure.php.net/manual/en/function.pg-connect.php
 
 334             $DSN = CONST_Database_DSN;
 
 335             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 336             $DSN = preg_replace('/;/', ' ', $DSN);
 
 337             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 338             pg_ping($aDBInstances[$i]);
 
 341         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 342             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 343             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 344             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 345             $sSQL .= ' and ST_IsValid(geometry)';
 
 346             if ($this->bVerbose) echo "$sSQL\n";
 
 347             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
 
 348                 fail(pg_last_error($aDBInstances[$i]));
 
 352         // last thread for interpolation lines
 
 353         // https://secure.php.net/manual/en/function.pg-connect.php
 
 354         $DSN = CONST_Database_DSN;
 
 355         $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 356         $DSN = preg_replace('/;/', ' ', $DSN);
 
 357         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 358         pg_ping($aDBInstances[$iLoadThreads]);
 
 359         $sSQL = 'insert into location_property_osmline';
 
 360         $sSQL .= ' (osm_id, address, linegeo)';
 
 361         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 362         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 363         if ($this->bVerbose) echo "$sSQL\n";
 
 364         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
 
 365             fail(pg_last_error($aDBInstances[$iLoadThreads]));
 
 369         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 370             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
 
 371                 $resultStatus = pg_result_status($hPGresult);
 
 372                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 373                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 374                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 375                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 376                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 377                     $resultError = pg_result_error($hPGresult);
 
 378                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 384             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 387         for ($i = 0; $i < $this->iInstances; $i++) {
 
 388             pg_close($aDBInstances[$i]);
 
 392         info('Reanalysing database');
 
 393         $this->pgsqlRunScript('ANALYSE');
 
 395         $sDatabaseDate = getDatabaseDate($this->oDB);
 
 396         $this->oDB->exec('TRUNCATE import_status');
 
 397         if (!$sDatabaseDate) {
 
 398             warn('could not determine database date.');
 
 400             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 401             $this->oDB->exec($sSQL);
 
 402             echo "Latest data imported from $sDatabaseDate.\n";
 
 406     public function importTigerData()
 
 408         info('Import Tiger data');
 
 410         $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
 
 411         info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
 
 412         if (empty($aFilenames)) return;
 
 414         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
 
 415         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 417         $this->pgsqlRunScript($sTemplate, false);
 
 419         $aDBInstances = array();
 
 420         for ($i = 0; $i < $this->iInstances; $i++) {
 
 421             // https://secure.php.net/manual/en/function.pg-connect.php
 
 422             $DSN = CONST_Database_DSN;
 
 423             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 424             $DSN = preg_replace('/;/', ' ', $DSN);
 
 425             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
 
 426             pg_ping($aDBInstances[$i]);
 
 429         foreach ($aFilenames as $sFile) {
 
 431             $hFile = fopen($sFile, 'r');
 
 432             $sSQL = fgets($hFile, 100000);
 
 435                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 436                     if (!pg_connection_busy($aDBInstances[$i])) {
 
 437                         while (pg_get_result($aDBInstances[$i]));
 
 438                         $sSQL = fgets($hFile, 100000);
 
 440                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
 
 442                         if ($iLines == 1000) {
 
 455                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 456                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
 
 463         for ($i = 0; $i < $this->iInstances; $i++) {
 
 464             pg_close($aDBInstances[$i]);
 
 467         info('Creating indexes on Tiger data');
 
 468         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
 
 469         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 471         $this->pgsqlRunScript($sTemplate, false);
 
 474     public function calculatePostcodes($bCMDResultAll)
 
 476         info('Calculate Postcodes');
 
 477         $this->oDB->exec('TRUNCATE location_postcode');
 
 479         $sSQL  = 'INSERT INTO location_postcode';
 
 480         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 481         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 482         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 483         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 484         $sSQL .= '  FROM placex';
 
 485         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 486         $sSQL .= '       AND geometry IS NOT null';
 
 487         $sSQL .= ' GROUP BY country_code, pc';
 
 488         $this->oDB->exec($sSQL);
 
 490         // only add postcodes that are not yet available in OSM
 
 491         $sSQL  = 'INSERT INTO location_postcode';
 
 492         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 493         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 494         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 495         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 496         $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 497         $sSQL .= "          WHERE country_code = 'us')";
 
 498         $this->oDB->exec($sSQL);
 
 500         // add missing postcodes for GB (if available)
 
 501         $sSQL  = 'INSERT INTO location_postcode';
 
 502         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 503         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 504         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 505         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 506         $sSQL .= "             WHERE country_code = 'gb')";
 
 507         $this->oDB->exec($sSQL);
 
 509         if (!$bCMDResultAll) {
 
 510             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 511             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 512             $this->oDB->exec($sSQL);
 
 515         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 516         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 517         $this->oDB->exec($sSQL);
 
 520     public function index($bIndexNoanalyse)
 
 523         $sBaseCmd = CONST_BasePath.'/nominatim/nominatim.py'
 
 524             .' -d '.escapeshellarg($this->aDSNInfo['database'])
 
 525             .' -P '.escapeshellarg($this->aDSNInfo['port'])
 
 526             .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
 
 527         if (!$this->bQuiet) {
 
 530         if ($this->bVerbose) {
 
 533         if (isset($this->aDSNInfo['hostspec'])) {
 
 534             $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 536         if (isset($this->aDSNInfo['username'])) {
 
 537             $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 540         info('Index ranks 0 - 4');
 
 541         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
 
 543             fail('error status ' . $iStatus . ' running nominatim!');
 
 545         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 547         info('Index ranks 5 - 25');
 
 548         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
 
 550             fail('error status ' . $iStatus . ' running nominatim!');
 
 552         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 554         info('Index ranks 26 - 30');
 
 555         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
 
 557             fail('error status ' . $iStatus . ' running nominatim!');
 
 560         info('Index postcodes');
 
 561         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 562         $this->oDB->exec($sSQL);
 
 565     public function createSearchIndices()
 
 567         info('Create Search indices');
 
 569         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
 
 570         if (!$this->dbReverseOnly()) {
 
 571             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
 
 573         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 575         $this->pgsqlRunScript($sTemplate);
 
 578     public function createCountryNames()
 
 580         info('Create search index for default country names');
 
 582         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
 
 583         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
 
 584         $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');
 
 585         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
 
 586         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
 
 587             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
 
 588         if (CONST_Languages) {
 
 591             foreach (explode(',', CONST_Languages) as $sLang) {
 
 592                 $sSQL .= $sDelim."'name:$sLang'";
 
 597             // all include all simple name tags
 
 598             $sSQL .= "like 'name:%'";
 
 601         $this->pgsqlRunScript($sSQL);
 
 604     public function drop()
 
 606         info('Drop tables only required for updates');
 
 608         // The implementation is potentially a bit dangerous because it uses
 
 609         // a positive selection of tables to keep, and deletes everything else.
 
 610         // Including any tables that the unsuspecting user might have manually
 
 611         // created. USE AT YOUR OWN PERIL.
 
 612         // tables we want to keep. everything else goes.
 
 613         $aKeepTables = array(
 
 619                         'location_property*',
 
 632         $aDropTables = array();
 
 633         $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
 
 635         foreach ($aHaveTables as $sTable) {
 
 637             foreach ($aKeepTables as $sKeep) {
 
 638                 if (fnmatch($sKeep, $sTable)) {
 
 643             if (!$bFound) array_push($aDropTables, $sTable);
 
 645         foreach ($aDropTables as $sDrop) {
 
 646             $this->dropTable($sDrop);
 
 649         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 650             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
 
 651                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
 
 652                 unlink(CONST_Osm2pgsql_Flatnode_File);
 
 657     private function pgsqlRunScript($sScript, $bfatal = true)
 
 667     private function createSqlFunctions()
 
 669         $sBasePath = CONST_BasePath.'/sql/functions/';
 
 670         $sTemplate = file_get_contents($sBasePath.'utils.sql');
 
 671         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
 
 672         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
 
 673         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
 
 674         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
 
 675         if ($this->oDB->tableExists('place')) {
 
 676             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
 
 678         if ($this->oDB->tableExists('placex')) {
 
 679             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
 
 681         if ($this->oDB->tableExists('location_postcode')) {
 
 682             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
 
 684         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 685         if ($this->bEnableDiffUpdates) {
 
 686             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 688         if ($this->bEnableDebugStatements) {
 
 689             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 691         if (CONST_Limit_Reindexing) {
 
 692             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 694         if (!CONST_Use_US_Tiger_Data) {
 
 695             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 697         if (!CONST_Use_Aux_Location_data) {
 
 698             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 701         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 702         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 704         $this->pgsqlRunScript($sTemplate);
 
 707     private function pgsqlRunPartitionScript($sTemplate)
 
 709         $sSQL = 'select distinct partition from country_name';
 
 710         $aPartitions = $this->oDB->getCol($sSQL);
 
 711         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 713         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 714         foreach ($aMatches as $aMatch) {
 
 716             foreach ($aPartitions as $sPartitionName) {
 
 717                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 719             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 722         $this->pgsqlRunScript($sTemplate);
 
 725     private function pgsqlRunScriptFile($sFilename)
 
 727         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 730             .' -p '.escapeshellarg($this->aDSNInfo['port'])
 
 731             .' -d '.escapeshellarg($this->aDSNInfo['database']);
 
 732         if (!$this->bVerbose) {
 
 735         if (isset($this->aDSNInfo['hostspec'])) {
 
 736             $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 738         if (isset($this->aDSNInfo['username'])) {
 
 739             $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 742         if (isset($this->aDSNInfo['password'])) {
 
 743             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 746         if (preg_match('/\\.gz$/', $sFilename)) {
 
 747             $aDescriptors = array(
 
 748                              0 => array('pipe', 'r'),
 
 749                              1 => array('pipe', 'w'),
 
 750                              2 => array('file', '/dev/null', 'a')
 
 752             $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
 
 753             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 754             $aReadPipe = $ahGzipPipes[1];
 
 755             fclose($ahGzipPipes[0]);
 
 757             $sCMD .= ' -f '.escapeshellarg($sFilename);
 
 758             $aReadPipe = array('pipe', 'r');
 
 760         $aDescriptors = array(
 
 762                          1 => array('pipe', 'w'),
 
 763                          2 => array('file', '/dev/null', 'a')
 
 766         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
 
 767         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 768         // TODO: error checking
 
 769         while (!feof($ahPipes[1])) {
 
 770             echo fread($ahPipes[1], 4096);
 
 773         $iReturn = proc_close($hProcess);
 
 775             fail("pgsql returned with error code ($iReturn)");
 
 778             fclose($ahGzipPipes[1]);
 
 779             proc_close($hGzipProcess);
 
 783     private function replaceSqlPatterns($sSql)
 
 785         $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
 
 788                       '{ts:address-data}' => CONST_Tablespace_Address_Data,
 
 789                       '{ts:address-index}' => CONST_Tablespace_Address_Index,
 
 790                       '{ts:search-data}' => CONST_Tablespace_Search_Data,
 
 791                       '{ts:search-index}' =>  CONST_Tablespace_Search_Index,
 
 792                       '{ts:aux-data}' =>  CONST_Tablespace_Aux_Data,
 
 793                       '{ts:aux-index}' =>  CONST_Tablespace_Aux_Index,
 
 796         foreach ($aPatterns as $sPattern => $sTablespace) {
 
 798                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 800                 $sSql = str_replace($sPattern, '', $sSql);
 
 807     private function runWithPgEnv($sCmd)
 
 809         if ($this->bVerbose) {
 
 810             echo "Execute: $sCmd\n";
 
 815         if (isset($this->aDSNInfo['password'])) {
 
 816             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 819         return runWithEnv($sCmd, $aProcEnv);
 
 823      * Drop table with the given name if it exists.
 
 825      * @param string $sName Name of table to remove.
 
 829      * @pre connect() must have been called.
 
 831     private function dropTable($sName)
 
 833         if ($this->bVerbose) echo "Dropping table $sName\n";
 
 834         $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
 
 838      * Check if the database is in reverse-only mode.
 
 840      * @return True if there is no search_name table and infrastructure.
 
 842     private function dbReverseOnly()
 
 844         return !($this->oDB->tableExists('search_name'));