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 = array_filter(\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->sVerbose = $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         $sDB = \DB::connect(CONST_Database_DSN, false);
 
  78         if (!\PEAR::isError($sDB)) {
 
  79             fail('database already exists ('.CONST_Database_DSN.')');
 
  82         $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
 
  83         if (isset($this->aDSNInfo['username'])) {
 
  84             $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
 
  87         if (isset($this->aDSNInfo['hostspec'])) {
 
  88             $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
 
  91         $result = $this->runWithPgEnv($sCreateDBCmd);
 
  92         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
 
  95     public function connect()
 
  97         $this->oDB =& getDB();
 
 100     public function setupDB()
 
 104         $fPostgresVersion = getPostgresVersion($this->oDB);
 
 105         echo 'Postgres version found: '.$fPostgresVersion."\n";
 
 107         if ($fPostgresVersion < 9.01) {
 
 108             fail('Minimum supported version of Postgresql is 9.1.');
 
 111         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
 
 112         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
 
 114         // For extratags and namedetails the hstore_to_json converter is
 
 115         // needed which is only available from Postgresql 9.3+. For older
 
 116         // versions add a dummy function that returns nothing.
 
 117         $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
 
 119         if ($iNumFunc == 0) {
 
 120             $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
 
 121             warn('Postgresql is too old. extratags and namedetails API not available.');
 
 125         $fPostgisVersion = getPostgisVersion($this->oDB);
 
 126         echo 'Postgis version found: '.$fPostgisVersion."\n";
 
 128         if ($fPostgisVersion < 2.1) {
 
 129             // Functions were renamed in 2.1 and throw an annoying deprecation warning
 
 130             $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
 
 131             $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
 
 133         if ($fPostgisVersion < 2.2) {
 
 134             $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
 
 137         $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
 
 139             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
 
 140             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
 
 144         // Try accessing the C module, so we know early if something is wrong
 
 145         if (!checkModulePresence()) {
 
 146             fail('error loading nominatim.so module');
 
 149         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
 
 150             echo 'Error: you need to download the country_osm_grid first:';
 
 151             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
 
 154         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
 
 155         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
 
 156         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
 
 157         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
 
 159         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
 
 160         if (file_exists($sPostcodeFilename)) {
 
 161             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 163             warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 166         if (CONST_Use_Extra_US_Postcodes) {
 
 167             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
 
 170         if ($this->bNoPartitions) {
 
 171             $this->pgsqlRunScript('update country_name set partition = 0');
 
 174         // the following will be needed by createFunctions later but
 
 175         // is only defined in the subsequently called createTables
 
 176         // Create dummies here that will be overwritten by the proper
 
 177         // versions in create-tables.
 
 178         $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
 
 179         $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
 
 182     public function importData($sOSMFile)
 
 186         $osm2pgsql = CONST_Osm2pgsql_Binary;
 
 187         if (!file_exists($osm2pgsql)) {
 
 188             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
 
 189             echo "Normally you should not need to set this manually.\n";
 
 190             fail("osm2pgsql not found in '$osm2pgsql'");
 
 193         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 194             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
 
 197         if (CONST_Tablespace_Osm2pgsql_Data)
 
 198             $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
 
 199         if (CONST_Tablespace_Osm2pgsql_Index)
 
 200             $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
 
 201         if (CONST_Tablespace_Place_Data)
 
 202             $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
 
 203         if (CONST_Tablespace_Place_Index)
 
 204             $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
 
 205         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
 
 206         $osm2pgsql .= ' -C '.$this->iCacheMemory;
 
 207         $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
 
 208         if (isset($this->aDSNInfo['username'])) {
 
 209             $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
 
 211         if (isset($this->aDSNInfo['hostspec'])) {
 
 212             $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
 
 214         $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
 
 216         $this->runWithPgEnv($osm2pgsql);
 
 218         if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
 
 223     public function createFunctions()
 
 225         info('Create Functions');
 
 227         // Try accessing the C module, so we know eif something is wrong
 
 228         // update.php calls this function
 
 229         if (!checkModulePresence()) {
 
 230             fail('error loading nominatim.so module');
 
 232         $this->createSqlFunctions();
 
 235     public function createTables($bReverseOnly = false)
 
 237         info('Create Tables');
 
 239         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
 
 240         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 241         $sTemplate = $this->replaceTablespace(
 
 243             CONST_Tablespace_Address_Data,
 
 246         $sTemplate = $this->replaceTablespace(
 
 247             '{ts:address-index}',
 
 248             CONST_Tablespace_Address_Index,
 
 251         $sTemplate = $this->replaceTablespace(
 
 253             CONST_Tablespace_Search_Data,
 
 256         $sTemplate = $this->replaceTablespace(
 
 258             CONST_Tablespace_Search_Index,
 
 261         $sTemplate = $this->replaceTablespace(
 
 263             CONST_Tablespace_Aux_Data,
 
 266         $sTemplate = $this->replaceTablespace(
 
 268             CONST_Tablespace_Aux_Index,
 
 272         $this->pgsqlRunScript($sTemplate, false);
 
 275             $this->pgExec('DROP TABLE search_name');
 
 278         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
 
 279         $oAlParser->createTable($this->oDB, 'address_levels');
 
 282     public function createPartitionTables()
 
 284         info('Create Partition Tables');
 
 286         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
 
 287         $sTemplate = $this->replaceTablespace(
 
 289             CONST_Tablespace_Address_Data,
 
 293         $sTemplate = $this->replaceTablespace(
 
 294             '{ts:address-index}',
 
 295             CONST_Tablespace_Address_Index,
 
 299         $sTemplate = $this->replaceTablespace(
 
 301             CONST_Tablespace_Search_Data,
 
 305         $sTemplate = $this->replaceTablespace(
 
 307             CONST_Tablespace_Search_Index,
 
 311         $sTemplate = $this->replaceTablespace(
 
 313             CONST_Tablespace_Aux_Data,
 
 317         $sTemplate = $this->replaceTablespace(
 
 319             CONST_Tablespace_Aux_Index,
 
 323         $this->pgsqlRunPartitionScript($sTemplate);
 
 326     public function createPartitionFunctions()
 
 328         info('Create Partition Functions');
 
 330         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
 
 331         $this->pgsqlRunPartitionScript($sTemplate);
 
 334     public function importWikipediaArticles()
 
 336         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
 
 337         $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
 
 338         if (file_exists($sWikiArticlesFile)) {
 
 339             info('Importing wikipedia articles');
 
 340             $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
 
 342             warn('wikipedia article dump file not found - places will have default importance');
 
 344         if (file_exists($sWikiRedirectsFile)) {
 
 345             info('Importing wikipedia redirects');
 
 346             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
 
 348             warn('wikipedia redirect dump file not found - some place importance values may be missing');
 
 352     public function loadData($bDisableTokenPrecalc)
 
 354         info('Drop old Data');
 
 356         $this->pgExec('TRUNCATE word');
 
 358         $this->pgExec('TRUNCATE placex');
 
 360         $this->pgExec('TRUNCATE location_property_osmline');
 
 362         $this->pgExec('TRUNCATE place_addressline');
 
 364         $this->pgExec('TRUNCATE place_boundingbox');
 
 366         $this->pgExec('TRUNCATE location_area');
 
 368         if (!$this->dbReverseOnly()) {
 
 369             $this->pgExec('TRUNCATE search_name');
 
 372         $this->pgExec('TRUNCATE search_name_blank');
 
 374         $this->pgExec('DROP SEQUENCE seq_place');
 
 376         $this->pgExec('CREATE SEQUENCE seq_place start 100000');
 
 379         $sSQL = 'select distinct partition from country_name';
 
 380         $aPartitions = chksql($this->oDB->getCol($sSQL));
 
 381         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 382         foreach ($aPartitions as $sPartition) {
 
 383             $this->pgExec('TRUNCATE location_road_'.$sPartition);
 
 387         // used by getorcreate_word_id to ignore frequent partial words
 
 388         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 389         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 390         $this->pgExec($sSQL);
 
 393         // pre-create the word list
 
 394         if (!$bDisableTokenPrecalc) {
 
 395             info('Loading word list');
 
 396             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
 
 400         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 401         $aDBInstances = array();
 
 402         $iLoadThreads = max(1, $this->iInstances - 1);
 
 403         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 404             $aDBInstances[$i] =& getDB(true);
 
 405             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 406             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 407             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 408             $sSQL .= ' and ST_IsValid(geometry)';
 
 409             if ($this->sVerbose) echo "$sSQL\n";
 
 410             if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
 
 411                 fail(pg_last_error($aDBInstances[$i]->connection));
 
 415         // last thread for interpolation lines
 
 416         $aDBInstances[$iLoadThreads] =& getDB(true);
 
 417         $sSQL = 'insert into location_property_osmline';
 
 418         $sSQL .= ' (osm_id, address, linegeo)';
 
 419         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 420         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 421         if ($this->sVerbose) echo "$sSQL\n";
 
 422         if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
 
 423             fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
 
 427         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 428             while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
 
 429                 $resultStatus = pg_result_status($hPGresult);
 
 430                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 431                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 432                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 433                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 434                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 435                     $resultError = pg_result_error($hPGresult);
 
 436                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 442             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 445         info('Reanalysing database');
 
 446         $this->pgsqlRunScript('ANALYSE');
 
 448         $sDatabaseDate = getDatabaseDate($this->oDB);
 
 449         pg_query($this->oDB->connection, 'TRUNCATE import_status');
 
 450         if ($sDatabaseDate === false) {
 
 451             warn('could not determine database date.');
 
 453             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 454             pg_query($this->oDB->connection, $sSQL);
 
 455             echo "Latest data imported from $sDatabaseDate.\n";
 
 459     public function importTigerData()
 
 461         info('Import Tiger data');
 
 463         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
 
 464         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 465         $sTemplate = $this->replaceTablespace(
 
 467             CONST_Tablespace_Aux_Data,
 
 470         $sTemplate = $this->replaceTablespace(
 
 472             CONST_Tablespace_Aux_Index,
 
 475         $this->pgsqlRunScript($sTemplate, false);
 
 477         $aDBInstances = array();
 
 478         for ($i = 0; $i < $this->iInstances; $i++) {
 
 479             $aDBInstances[$i] =& getDB(true);
 
 482         foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
 
 484             $hFile = fopen($sFile, 'r');
 
 485             $sSQL = fgets($hFile, 100000);
 
 488                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 489                     if (!pg_connection_busy($aDBInstances[$i]->connection)) {
 
 490                         while (pg_get_result($aDBInstances[$i]->connection));
 
 491                         $sSQL = fgets($hFile, 100000);
 
 493                         if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
 
 495                         if ($iLines == 1000) {
 
 508                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 509                     if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
 
 516         info('Creating indexes on Tiger data');
 
 517         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
 
 518         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 519         $sTemplate = $this->replaceTablespace(
 
 521             CONST_Tablespace_Aux_Data,
 
 524         $sTemplate = $this->replaceTablespace(
 
 526             CONST_Tablespace_Aux_Index,
 
 529         $this->pgsqlRunScript($sTemplate, false);
 
 532     public function calculatePostcodes($bCMDResultAll)
 
 534         info('Calculate Postcodes');
 
 535         $this->pgExec('TRUNCATE location_postcode');
 
 537         $sSQL  = 'INSERT INTO location_postcode';
 
 538         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 539         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 540         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 541         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 542         $sSQL .= '  FROM placex';
 
 543         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 544         $sSQL .= '       AND geometry IS NOT null';
 
 545         $sSQL .= ' GROUP BY country_code, pc';
 
 546         $this->pgExec($sSQL);
 
 548         if (CONST_Use_Extra_US_Postcodes) {
 
 549             // only add postcodes that are not yet available in OSM
 
 550             $sSQL  = 'INSERT INTO location_postcode';
 
 551             $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 552             $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 553             $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 554             $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 555             $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 556             $sSQL .= "          WHERE country_code = 'us')";
 
 557             $this->pgExec($sSQL);
 
 560         // add missing postcodes for GB (if available)
 
 561         $sSQL  = 'INSERT INTO location_postcode';
 
 562         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 563         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 564         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 565         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 566         $sSQL .= "             WHERE country_code = 'gb')";
 
 567         $this->pgExec($sSQL);
 
 569         if (!$bCMDResultAll) {
 
 570             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 571             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 572             $this->pgExec($sSQL);
 
 575         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 576         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 577         $this->pgExec($sSQL);
 
 580     public function index($bIndexNoanalyse)
 
 583         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
 
 584             .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
 
 585         if (isset($this->aDSNInfo['hostspec'])) {
 
 586             $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
 
 588         if (isset($this->aDSNInfo['username'])) {
 
 589             $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
 
 592         info('Index ranks 0 - 4');
 
 593         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
 
 595             fail('error status ' . $iStatus . ' running nominatim!');
 
 597         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 599         info('Index ranks 5 - 25');
 
 600         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
 
 602             fail('error status ' . $iStatus . ' running nominatim!');
 
 604         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 606         info('Index ranks 26 - 30');
 
 607         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
 
 609             fail('error status ' . $iStatus . ' running nominatim!');
 
 612         info('Index postcodes');
 
 613         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 614         $this->pgExec($sSQL);
 
 617     public function createSearchIndices()
 
 619         info('Create Search indices');
 
 621         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
 
 622         if (!$this->dbReverseOnly()) {
 
 623             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
 
 625         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 626         $sTemplate = $this->replaceTablespace(
 
 627             '{ts:address-index}',
 
 628             CONST_Tablespace_Address_Index,
 
 631         $sTemplate = $this->replaceTablespace(
 
 633             CONST_Tablespace_Search_Index,
 
 636         $sTemplate = $this->replaceTablespace(
 
 638             CONST_Tablespace_Aux_Index,
 
 641         $this->pgsqlRunScript($sTemplate);
 
 644     public function createCountryNames()
 
 646         info('Create search index for default country names');
 
 648         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
 
 649         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
 
 650         $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');
 
 651         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
 
 652         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
 
 653             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
 
 654         if (CONST_Languages) {
 
 657             foreach (explode(',', CONST_Languages) as $sLang) {
 
 658                 $sSQL .= $sDelim."'name:$sLang'";
 
 663             // all include all simple name tags
 
 664             $sSQL .= "like 'name:%'";
 
 667         $this->pgsqlRunScript($sSQL);
 
 670     public function drop()
 
 672         info('Drop tables only required for updates');
 
 674         // The implementation is potentially a bit dangerous because it uses
 
 675         // a positive selection of tables to keep, and deletes everything else.
 
 676         // Including any tables that the unsuspecting user might have manually
 
 677         // created. USE AT YOUR OWN PERIL.
 
 678         // tables we want to keep. everything else goes.
 
 679         $aKeepTables = array(
 
 685                         'location_property*',
 
 697         $aDropTables = array();
 
 698         $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
 
 700         foreach ($aHaveTables as $sTable) {
 
 702             foreach ($aKeepTables as $sKeep) {
 
 703                 if (fnmatch($sKeep, $sTable)) {
 
 708             if (!$bFound) array_push($aDropTables, $sTable);
 
 710         foreach ($aDropTables as $sDrop) {
 
 711             if ($this->sVerbose) echo "Dropping table $sDrop\n";
 
 712             @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
 
 713             // ignore warnings/errors as they might be caused by a table having
 
 714             // been deleted already by CASCADE
 
 717         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 718             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
 
 719                 if ($this->sVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
 
 720                 unlink(CONST_Osm2pgsql_Flatnode_File);
 
 725     private function pgsqlRunDropAndRestore($sDumpFile)
 
 727         $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
 
 728         if (isset($this->aDSNInfo['hostspec'])) {
 
 729             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 731         if (isset($this->aDSNInfo['username'])) {
 
 732             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 735         $this->runWithPgEnv($sCMD);
 
 738     private function pgsqlRunScript($sScript, $bfatal = true)
 
 748     private function createSqlFunctions()
 
 750         $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
 
 751         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 752         if ($this->bEnableDiffUpdates) {
 
 753             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 755         if ($this->bEnableDebugStatements) {
 
 756             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 758         if (CONST_Limit_Reindexing) {
 
 759             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 761         if (!CONST_Use_US_Tiger_Data) {
 
 762             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 764         if (!CONST_Use_Aux_Location_data) {
 
 765             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 768         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 769         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 771         $this->pgsqlRunScript($sTemplate);
 
 774     private function pgsqlRunPartitionScript($sTemplate)
 
 776         $sSQL = 'select distinct partition from country_name';
 
 777         $aPartitions = chksql($this->oDB->getCol($sSQL));
 
 778         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 780         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 781         foreach ($aMatches as $aMatch) {
 
 783             foreach ($aPartitions as $sPartitionName) {
 
 784                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 786             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 789         $this->pgsqlRunScript($sTemplate);
 
 792     private function pgsqlRunScriptFile($sFilename)
 
 794         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 796         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
 
 797         if (!$this->sVerbose) {
 
 800         if (isset($this->aDSNInfo['hostspec'])) {
 
 801             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 803         if (isset($this->aDSNInfo['username'])) {
 
 804             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 807         if (isset($this->aDSNInfo['password'])) {
 
 808             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 811         if (preg_match('/\\.gz$/', $sFilename)) {
 
 812             $aDescriptors = array(
 
 813                              0 => array('pipe', 'r'),
 
 814                              1 => array('pipe', 'w'),
 
 815                              2 => array('file', '/dev/null', 'a')
 
 817             $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
 
 818             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 819             $aReadPipe = $ahGzipPipes[1];
 
 820             fclose($ahGzipPipes[0]);
 
 822             $sCMD .= ' -f '.$sFilename;
 
 823             $aReadPipe = array('pipe', 'r');
 
 825         $aDescriptors = array(
 
 827                          1 => array('pipe', 'w'),
 
 828                          2 => array('file', '/dev/null', 'a')
 
 831         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
 
 832         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 833         // TODO: error checking
 
 834         while (!feof($ahPipes[1])) {
 
 835             echo fread($ahPipes[1], 4096);
 
 838         $iReturn = proc_close($hProcess);
 
 840             fail("pgsql returned with error code ($iReturn)");
 
 843             fclose($ahGzipPipes[1]);
 
 844             proc_close($hGzipProcess);
 
 848     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
 
 851             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 853             $sSql = str_replace($sTemplate, '', $sSql);
 
 858     private function runWithPgEnv($sCmd)
 
 862         if (isset($this->aDSNInfo['password'])) {
 
 863             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 866         return runWithEnv($sCmd, $aProcEnv);
 
 870      * Execute the SQL command on the open database.
 
 872      * @param string $sSQL SQL command to execute.
 
 876      * @pre connect() must have been called.
 
 878     private function pgExec($sSQL)
 
 880         if (!pg_query($this->oDB->connection, $sSQL)) {
 
 881             fail(pg_last_error($this->oDB->connection));
 
 886      * Check if the database is in reverse-only mode.
 
 888      * @return True if there is no search_name table and infrastructure.
 
 890     private function dbReverseOnly()
 
 892         $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = 'search_name'";
 
 893         return !(chksql($this->oDB->getOne($sSQL)));