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         // Assume we can steal all the cache memory in the box (unless told otherwise)
 
  33         if (isset($aCMDResult['osm2pgsql-cache'])) {
 
  34             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
 
  36             $this->iCacheMemory = getCacheMemoryMB();
 
  39         $this->sModulePath = CONST_Database_Module_Path;
 
  40         info('module path: ' . $this->sModulePath);
 
  42         // parse database string
 
  43         $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
 
  44         if (!isset($this->aDSNInfo['port'])) {
 
  45             $this->aDSNInfo['port'] = 5432;
 
  48         // setting member variables based on command line options stored in $aCMDResult
 
  49         $this->bVerbose = $aCMDResult['verbose'];
 
  51         //setting default values which are not set by the update.php array
 
  52         if (isset($aCMDResult['ignore-errors'])) {
 
  53             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
 
  55             $this->sIgnoreErrors = false;
 
  57         if (isset($aCMDResult['enable-debug-statements'])) {
 
  58             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
 
  60             $this->bEnableDebugStatements = false;
 
  62         if (isset($aCMDResult['no-partitions'])) {
 
  63             $this->bNoPartitions = $aCMDResult['no-partitions'];
 
  65             $this->bNoPartitions = false;
 
  67         if (isset($aCMDResult['enable-diff-updates'])) {
 
  68             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
 
  70             $this->bEnableDiffUpdates = false;
 
  74     public function createDB()
 
  77         $oDB = new \Nominatim\DB;
 
  79         if ($oDB->databaseExists()) {
 
  80             fail('database already exists ('.CONST_Database_DSN.')');
 
  83         $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
 
  84         if (isset($this->aDSNInfo['username'])) {
 
  85             $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
 
  88         if (isset($this->aDSNInfo['hostspec'])) {
 
  89             $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
 
  92         $result = $this->runWithPgEnv($sCreateDBCmd);
 
  93         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
 
  96     public function connect()
 
  98         $this->oDB = new \Nominatim\DB();
 
  99         $this->oDB->connect();
 
 102     public function setupDB()
 
 106         $fPostgresVersion = $this->oDB->getPostgresVersion();
 
 107         echo 'Postgres version found: '.$fPostgresVersion."\n";
 
 109         if ($fPostgresVersion < 9.03) {
 
 110             fail('Minimum supported version of Postgresql is 9.3.');
 
 113         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
 
 114         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
 
 116         $fPostgisVersion = $this->oDB->getPostgisVersion();
 
 117         echo 'Postgis version found: '.$fPostgisVersion."\n";
 
 119         if ($fPostgisVersion < 2.2) {
 
 120             echo "Minimum required Postgis version 2.2\n";
 
 124         $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
 
 126             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
 
 127             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
 
 131         // Try accessing the C module, so we know early if something is wrong
 
 132         checkModulePresence(); // raises exception on failure
 
 134         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
 
 135             echo 'Error: you need to download the country_osm_grid first:';
 
 136             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
 
 139         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
 
 140         $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
 
 141         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
 
 142         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
 
 144         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
 
 145         if (file_exists($sPostcodeFilename)) {
 
 146             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 148             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 151         $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
 
 152         if (file_exists($sPostcodeFilename)) {
 
 153             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 155             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 158         if ($this->bNoPartitions) {
 
 159             $this->pgsqlRunScript('update country_name set partition = 0');
 
 162         // the following will be needed by createFunctions later but
 
 163         // is only defined in the subsequently called createTables
 
 164         // Create dummies here that will be overwritten by the proper
 
 165         // versions in create-tables.
 
 166         $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
 
 167         $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
 
 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 '.CONST_Import_Style;
 
 183         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 184             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
 
 187         if (CONST_Tablespace_Osm2pgsql_Data)
 
 188             $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
 
 189         if (CONST_Tablespace_Osm2pgsql_Index)
 
 190             $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
 
 191         if (CONST_Tablespace_Place_Data)
 
 192             $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
 
 193         if (CONST_Tablespace_Place_Index)
 
 194             $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
 
 195         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
 
 196         $osm2pgsql .= ' -C '.$this->iCacheMemory;
 
 197         $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
 
 198         if (isset($this->aDSNInfo['username'])) {
 
 199             $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
 
 201         if (isset($this->aDSNInfo['hostspec'])) {
 
 202             $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
 
 204         $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$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 = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 229         $sTemplate = $this->replaceTablespace(
 
 231             CONST_Tablespace_Address_Data,
 
 234         $sTemplate = $this->replaceTablespace(
 
 235             '{ts:address-index}',
 
 236             CONST_Tablespace_Address_Index,
 
 239         $sTemplate = $this->replaceTablespace(
 
 241             CONST_Tablespace_Search_Data,
 
 244         $sTemplate = $this->replaceTablespace(
 
 246             CONST_Tablespace_Search_Index,
 
 249         $sTemplate = $this->replaceTablespace(
 
 251             CONST_Tablespace_Aux_Data,
 
 254         $sTemplate = $this->replaceTablespace(
 
 256             CONST_Tablespace_Aux_Index,
 
 260         $this->pgsqlRunScript($sTemplate, false);
 
 263             $this->pgExec('DROP TABLE search_name');
 
 266         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
 
 267         $oAlParser->createTable($this->oDB, 'address_levels');
 
 270     public function createPartitionTables()
 
 272         info('Create Partition Tables');
 
 274         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
 
 275         $sTemplate = $this->replaceTablespace(
 
 277             CONST_Tablespace_Address_Data,
 
 281         $sTemplate = $this->replaceTablespace(
 
 282             '{ts:address-index}',
 
 283             CONST_Tablespace_Address_Index,
 
 287         $sTemplate = $this->replaceTablespace(
 
 289             CONST_Tablespace_Search_Data,
 
 293         $sTemplate = $this->replaceTablespace(
 
 295             CONST_Tablespace_Search_Index,
 
 299         $sTemplate = $this->replaceTablespace(
 
 301             CONST_Tablespace_Aux_Data,
 
 305         $sTemplate = $this->replaceTablespace(
 
 307             CONST_Tablespace_Aux_Index,
 
 311         $this->pgsqlRunPartitionScript($sTemplate);
 
 314     public function createPartitionFunctions()
 
 316         info('Create Partition Functions');
 
 318         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
 
 319         $this->pgsqlRunPartitionScript($sTemplate);
 
 322     public function importWikipediaArticles()
 
 324         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
 
 325         $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
 
 326         if (file_exists($sWikiArticlesFile)) {
 
 327             info('Importing wikipedia articles');
 
 328             $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
 
 330             warn('wikipedia article dump file not found - places will have default importance');
 
 332         if (file_exists($sWikiRedirectsFile)) {
 
 333             info('Importing wikipedia redirects');
 
 334             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
 
 336             warn('wikipedia redirect dump file not found - some place importance values may be missing');
 
 340     public function loadData($bDisableTokenPrecalc)
 
 342         info('Drop old Data');
 
 344         $this->pgExec('TRUNCATE word');
 
 346         $this->pgExec('TRUNCATE placex');
 
 348         $this->pgExec('TRUNCATE location_property_osmline');
 
 350         $this->pgExec('TRUNCATE place_addressline');
 
 352         $this->pgExec('TRUNCATE place_boundingbox');
 
 354         $this->pgExec('TRUNCATE location_area');
 
 356         if (!$this->dbReverseOnly()) {
 
 357             $this->pgExec('TRUNCATE search_name');
 
 360         $this->pgExec('TRUNCATE search_name_blank');
 
 362         $this->pgExec('DROP SEQUENCE seq_place');
 
 364         $this->pgExec('CREATE SEQUENCE seq_place start 100000');
 
 367         $sSQL = 'select distinct partition from country_name';
 
 368         $aPartitions = $this->oDB->getCol($sSQL);
 
 370         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 371         foreach ($aPartitions as $sPartition) {
 
 372             $this->pgExec('TRUNCATE location_road_'.$sPartition);
 
 376         // used by getorcreate_word_id to ignore frequent partial words
 
 377         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 378         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 379         $this->pgExec($sSQL);
 
 382         // pre-create the word list
 
 383         if (!$bDisableTokenPrecalc) {
 
 384             info('Loading word list');
 
 385             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
 
 389         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 391         $aDBInstances = array();
 
 392         $iLoadThreads = max(1, $this->iInstances - 1);
 
 393         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 394             // https://secure.php.net/manual/en/function.pg-connect.php
 
 395             $DSN = CONST_Database_DSN;
 
 396             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 397             $DSN = preg_replace('/;/', ' ', $DSN);
 
 398             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 399             pg_ping($aDBInstances[$i]);
 
 402         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 403             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 404             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 405             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 406             $sSQL .= ' and ST_IsValid(geometry)';
 
 407             if ($this->bVerbose) echo "$sSQL\n";
 
 408             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
 
 409                 fail(pg_last_error($aDBInstances[$i]));
 
 413         // last thread for interpolation lines
 
 414         // https://secure.php.net/manual/en/function.pg-connect.php
 
 415         $DSN = CONST_Database_DSN;
 
 416         $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 417         $DSN = preg_replace('/;/', ' ', $DSN);
 
 418         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 419         pg_ping($aDBInstances[$iLoadThreads]);
 
 420         $sSQL = 'insert into location_property_osmline';
 
 421         $sSQL .= ' (osm_id, address, linegeo)';
 
 422         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 423         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 424         if ($this->bVerbose) echo "$sSQL\n";
 
 425         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
 
 426             fail(pg_last_error($aDBInstances[$iLoadThreads]));
 
 430         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 431             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
 
 432                 $resultStatus = pg_result_status($hPGresult);
 
 433                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 434                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 435                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 436                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 437                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 438                     $resultError = pg_result_error($hPGresult);
 
 439                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 445             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 448         for ($i = 0; $i < $this->iInstances; $i++) {
 
 449             pg_close($aDBInstances[$i]);
 
 453         info('Reanalysing database');
 
 454         $this->pgsqlRunScript('ANALYSE');
 
 456         $sDatabaseDate = getDatabaseDate($this->oDB);
 
 457         $this->oDB->exec('TRUNCATE import_status');
 
 458         if (!$sDatabaseDate) {
 
 459             warn('could not determine database date.');
 
 461             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 462             $this->oDB->exec($sSQL);
 
 463             echo "Latest data imported from $sDatabaseDate.\n";
 
 467     public function importTigerData()
 
 469         info('Import Tiger data');
 
 471         $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
 
 472         info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
 
 473         if (empty($aFilenames)) return;
 
 475         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
 
 476         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 477         $sTemplate = $this->replaceTablespace(
 
 479             CONST_Tablespace_Aux_Data,
 
 482         $sTemplate = $this->replaceTablespace(
 
 484             CONST_Tablespace_Aux_Index,
 
 487         $this->pgsqlRunScript($sTemplate, false);
 
 489         $aDBInstances = array();
 
 490         for ($i = 0; $i < $this->iInstances; $i++) {
 
 491             // https://secure.php.net/manual/en/function.pg-connect.php
 
 492             $DSN = CONST_Database_DSN;
 
 493             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 494             $DSN = preg_replace('/;/', ' ', $DSN);
 
 495             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
 
 496             pg_ping($aDBInstances[$i]);
 
 499         foreach ($aFilenames as $sFile) {
 
 501             $hFile = fopen($sFile, 'r');
 
 502             $sSQL = fgets($hFile, 100000);
 
 505                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 506                     if (!pg_connection_busy($aDBInstances[$i])) {
 
 507                         while (pg_get_result($aDBInstances[$i]));
 
 508                         $sSQL = fgets($hFile, 100000);
 
 510                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
 
 512                         if ($iLines == 1000) {
 
 525                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 526                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
 
 533         for ($i = 0; $i < $this->iInstances; $i++) {
 
 534             pg_close($aDBInstances[$i]);
 
 537         info('Creating indexes on Tiger data');
 
 538         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
 
 539         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 540         $sTemplate = $this->replaceTablespace(
 
 542             CONST_Tablespace_Aux_Data,
 
 545         $sTemplate = $this->replaceTablespace(
 
 547             CONST_Tablespace_Aux_Index,
 
 550         $this->pgsqlRunScript($sTemplate, false);
 
 553     public function calculatePostcodes($bCMDResultAll)
 
 555         info('Calculate Postcodes');
 
 556         $this->pgExec('TRUNCATE location_postcode');
 
 558         $sSQL  = 'INSERT INTO location_postcode';
 
 559         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 560         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 561         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 562         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 563         $sSQL .= '  FROM placex';
 
 564         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 565         $sSQL .= '       AND geometry IS NOT null';
 
 566         $sSQL .= ' GROUP BY country_code, pc';
 
 567         $this->pgExec($sSQL);
 
 569         // only add postcodes that are not yet available in OSM
 
 570         $sSQL  = 'INSERT INTO location_postcode';
 
 571         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 572         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 573         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 574         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 575         $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 576         $sSQL .= "          WHERE country_code = 'us')";
 
 577         $this->pgExec($sSQL);
 
 579         // add missing postcodes for GB (if available)
 
 580         $sSQL  = 'INSERT INTO location_postcode';
 
 581         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 582         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 583         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 584         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 585         $sSQL .= "             WHERE country_code = 'gb')";
 
 586         $this->pgExec($sSQL);
 
 588         if (!$bCMDResultAll) {
 
 589             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 590             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 591             $this->pgExec($sSQL);
 
 594         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 595         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 596         $this->pgExec($sSQL);
 
 599     public function index($bIndexNoanalyse)
 
 602         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
 
 603             .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
 
 604         if (isset($this->aDSNInfo['hostspec'])) {
 
 605             $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
 
 607         if (isset($this->aDSNInfo['username'])) {
 
 608             $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
 
 611         info('Index ranks 0 - 4');
 
 612         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
 
 614             fail('error status ' . $iStatus . ' running nominatim!');
 
 616         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 618         info('Index ranks 5 - 25');
 
 619         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
 
 621             fail('error status ' . $iStatus . ' running nominatim!');
 
 623         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 625         info('Index ranks 26 - 30');
 
 626         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
 
 628             fail('error status ' . $iStatus . ' running nominatim!');
 
 631         info('Index postcodes');
 
 632         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 633         $this->pgExec($sSQL);
 
 636     public function createSearchIndices()
 
 638         info('Create Search indices');
 
 640         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
 
 641         if (!$this->dbReverseOnly()) {
 
 642             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
 
 644         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 645         $sTemplate = $this->replaceTablespace(
 
 646             '{ts:address-index}',
 
 647             CONST_Tablespace_Address_Index,
 
 650         $sTemplate = $this->replaceTablespace(
 
 652             CONST_Tablespace_Search_Index,
 
 655         $sTemplate = $this->replaceTablespace(
 
 657             CONST_Tablespace_Aux_Index,
 
 660         $this->pgsqlRunScript($sTemplate);
 
 663     public function createCountryNames()
 
 665         info('Create search index for default country names');
 
 667         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
 
 668         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
 
 669         $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');
 
 670         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
 
 671         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
 
 672             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
 
 673         if (CONST_Languages) {
 
 676             foreach (explode(',', CONST_Languages) as $sLang) {
 
 677                 $sSQL .= $sDelim."'name:$sLang'";
 
 682             // all include all simple name tags
 
 683             $sSQL .= "like 'name:%'";
 
 686         $this->pgsqlRunScript($sSQL);
 
 689     public function drop()
 
 691         info('Drop tables only required for updates');
 
 693         // The implementation is potentially a bit dangerous because it uses
 
 694         // a positive selection of tables to keep, and deletes everything else.
 
 695         // Including any tables that the unsuspecting user might have manually
 
 696         // created. USE AT YOUR OWN PERIL.
 
 697         // tables we want to keep. everything else goes.
 
 698         $aKeepTables = array(
 
 704                         'location_property*',
 
 717         $aDropTables = array();
 
 718         $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
 
 720         foreach ($aHaveTables as $sTable) {
 
 722             foreach ($aKeepTables as $sKeep) {
 
 723                 if (fnmatch($sKeep, $sTable)) {
 
 728             if (!$bFound) array_push($aDropTables, $sTable);
 
 730         foreach ($aDropTables as $sDrop) {
 
 731             if ($this->bVerbose) echo "Dropping table $sDrop\n";
 
 732             $this->oDB->exec("DROP TABLE IF EXISTS $sDrop CASCADE");
 
 735         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 736             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
 
 737                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
 
 738                 unlink(CONST_Osm2pgsql_Flatnode_File);
 
 743     private function pgsqlRunDropAndRestore($sDumpFile)
 
 745         $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' --no-owner -Fc --clean '.$sDumpFile;
 
 746         if ($this->oDB->getPostgresVersion() >= 9.04) {
 
 747             $sCMD .= ' --if-exists';
 
 749         if (isset($this->aDSNInfo['hostspec'])) {
 
 750             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 752         if (isset($this->aDSNInfo['username'])) {
 
 753             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 756         $this->runWithPgEnv($sCMD);
 
 759     private function pgsqlRunScript($sScript, $bfatal = true)
 
 769     private function createSqlFunctions()
 
 771         $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
 
 772         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 773         if ($this->bEnableDiffUpdates) {
 
 774             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 776         if ($this->bEnableDebugStatements) {
 
 777             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 779         if (CONST_Limit_Reindexing) {
 
 780             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 782         if (!CONST_Use_US_Tiger_Data) {
 
 783             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 785         if (!CONST_Use_Aux_Location_data) {
 
 786             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 789         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 790         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 792         $this->pgsqlRunScript($sTemplate);
 
 795     private function pgsqlRunPartitionScript($sTemplate)
 
 797         $sSQL = 'select distinct partition from country_name';
 
 798         $aPartitions = $this->oDB->getCol($sSQL);
 
 799         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 801         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 802         foreach ($aMatches as $aMatch) {
 
 804             foreach ($aPartitions as $sPartitionName) {
 
 805                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 807             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 810         $this->pgsqlRunScript($sTemplate);
 
 813     private function pgsqlRunScriptFile($sFilename)
 
 815         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 817         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
 
 818         if (!$this->bVerbose) {
 
 821         if (isset($this->aDSNInfo['hostspec'])) {
 
 822             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 824         if (isset($this->aDSNInfo['username'])) {
 
 825             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 828         if (isset($this->aDSNInfo['password'])) {
 
 829             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 832         if (preg_match('/\\.gz$/', $sFilename)) {
 
 833             $aDescriptors = array(
 
 834                              0 => array('pipe', 'r'),
 
 835                              1 => array('pipe', 'w'),
 
 836                              2 => array('file', '/dev/null', 'a')
 
 838             $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
 
 839             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 840             $aReadPipe = $ahGzipPipes[1];
 
 841             fclose($ahGzipPipes[0]);
 
 843             $sCMD .= ' -f '.$sFilename;
 
 844             $aReadPipe = array('pipe', 'r');
 
 846         $aDescriptors = array(
 
 848                          1 => array('pipe', 'w'),
 
 849                          2 => array('file', '/dev/null', 'a')
 
 852         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
 
 853         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 854         // TODO: error checking
 
 855         while (!feof($ahPipes[1])) {
 
 856             echo fread($ahPipes[1], 4096);
 
 859         $iReturn = proc_close($hProcess);
 
 861             fail("pgsql returned with error code ($iReturn)");
 
 864             fclose($ahGzipPipes[1]);
 
 865             proc_close($hGzipProcess);
 
 869     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
 
 872             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 874             $sSql = str_replace($sTemplate, '', $sSql);
 
 879     private function runWithPgEnv($sCmd)
 
 881         if ($this->bVerbose) {
 
 882             echo "Execute: $sCmd\n";
 
 887         if (isset($this->aDSNInfo['password'])) {
 
 888             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 891         return runWithEnv($sCmd, $aProcEnv);
 
 895      * Execute the SQL command on the open database.
 
 897      * @param string $sSQL SQL command to execute.
 
 901      * @pre connect() must have been called.
 
 903     private function pgExec($sSQL)
 
 905         $this->oDB->exec($sSQL);
 
 909      * Check if the database is in reverse-only mode.
 
 911      * @return True if there is no search_name table and infrastructure.
 
 913     private function dbReverseOnly()
 
 915         return !($this->oDB->tableExists('search_name'));