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->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         $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_osm_grid.sql.gz');
 
 156         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
 
 158         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
 
 159         if (file_exists($sPostcodeFilename)) {
 
 160             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 162             warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 165         if (CONST_Use_Extra_US_Postcodes) {
 
 166             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
 
 169         if ($this->bNoPartitions) {
 
 170             $this->pgsqlRunScript('update country_name set partition = 0');
 
 173         // the following will be needed by createFunctions later but
 
 174         // is only defined in the subsequently called createTables
 
 175         // Create dummies here that will be overwritten by the proper
 
 176         // versions in create-tables.
 
 177         $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
 
 178         $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
 
 181     public function importData($sOSMFile)
 
 185         $osm2pgsql = CONST_Osm2pgsql_Binary;
 
 186         if (!file_exists($osm2pgsql)) {
 
 187             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
 
 188             echo "Normally you should not need to set this manually.\n";
 
 189             fail("osm2pgsql not found in '$osm2pgsql'");
 
 192         $osm2pgsql .= ' -S '.CONST_Import_Style;
 
 194         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 195             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
 
 198         if (CONST_Tablespace_Osm2pgsql_Data)
 
 199             $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
 
 200         if (CONST_Tablespace_Osm2pgsql_Index)
 
 201             $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
 
 202         if (CONST_Tablespace_Place_Data)
 
 203             $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
 
 204         if (CONST_Tablespace_Place_Index)
 
 205             $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
 
 206         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
 
 207         $osm2pgsql .= ' -C '.$this->iCacheMemory;
 
 208         $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
 
 209         if (isset($this->aDSNInfo['username'])) {
 
 210             $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
 
 212         if (isset($this->aDSNInfo['hostspec'])) {
 
 213             $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
 
 215         $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
 
 217         $this->runWithPgEnv($osm2pgsql);
 
 219         if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
 
 224     public function createFunctions()
 
 226         info('Create Functions');
 
 228         // Try accessing the C module, so we know eif something is wrong
 
 229         // update.php calls this function
 
 230         if (!checkModulePresence()) {
 
 231             fail('error loading nominatim.so module');
 
 233         $this->createSqlFunctions();
 
 236     public function createTables($bReverseOnly = false)
 
 238         info('Create Tables');
 
 240         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
 
 241         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 242         $sTemplate = $this->replaceTablespace(
 
 244             CONST_Tablespace_Address_Data,
 
 247         $sTemplate = $this->replaceTablespace(
 
 248             '{ts:address-index}',
 
 249             CONST_Tablespace_Address_Index,
 
 252         $sTemplate = $this->replaceTablespace(
 
 254             CONST_Tablespace_Search_Data,
 
 257         $sTemplate = $this->replaceTablespace(
 
 259             CONST_Tablespace_Search_Index,
 
 262         $sTemplate = $this->replaceTablespace(
 
 264             CONST_Tablespace_Aux_Data,
 
 267         $sTemplate = $this->replaceTablespace(
 
 269             CONST_Tablespace_Aux_Index,
 
 273         $this->pgsqlRunScript($sTemplate, false);
 
 276             $this->pgExec('DROP TABLE search_name');
 
 279         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
 
 280         $oAlParser->createTable($this->oDB, 'address_levels');
 
 283     public function createPartitionTables()
 
 285         info('Create Partition Tables');
 
 287         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
 
 288         $sTemplate = $this->replaceTablespace(
 
 290             CONST_Tablespace_Address_Data,
 
 294         $sTemplate = $this->replaceTablespace(
 
 295             '{ts:address-index}',
 
 296             CONST_Tablespace_Address_Index,
 
 300         $sTemplate = $this->replaceTablespace(
 
 302             CONST_Tablespace_Search_Data,
 
 306         $sTemplate = $this->replaceTablespace(
 
 308             CONST_Tablespace_Search_Index,
 
 312         $sTemplate = $this->replaceTablespace(
 
 314             CONST_Tablespace_Aux_Data,
 
 318         $sTemplate = $this->replaceTablespace(
 
 320             CONST_Tablespace_Aux_Index,
 
 324         $this->pgsqlRunPartitionScript($sTemplate);
 
 327     public function createPartitionFunctions()
 
 329         info('Create Partition Functions');
 
 331         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
 
 332         $this->pgsqlRunPartitionScript($sTemplate);
 
 335     public function importWikipediaArticles()
 
 337         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
 
 338         $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
 
 339         if (file_exists($sWikiArticlesFile)) {
 
 340             info('Importing wikipedia articles');
 
 341             $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
 
 343             warn('wikipedia article dump file not found - places will have default importance');
 
 345         if (file_exists($sWikiRedirectsFile)) {
 
 346             info('Importing wikipedia redirects');
 
 347             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
 
 349             warn('wikipedia redirect dump file not found - some place importance values may be missing');
 
 353     public function loadData($bDisableTokenPrecalc)
 
 355         info('Drop old Data');
 
 357         $this->pgExec('TRUNCATE word');
 
 359         $this->pgExec('TRUNCATE placex');
 
 361         $this->pgExec('TRUNCATE location_property_osmline');
 
 363         $this->pgExec('TRUNCATE place_addressline');
 
 365         $this->pgExec('TRUNCATE place_boundingbox');
 
 367         $this->pgExec('TRUNCATE location_area');
 
 369         if (!$this->dbReverseOnly()) {
 
 370             $this->pgExec('TRUNCATE search_name');
 
 373         $this->pgExec('TRUNCATE search_name_blank');
 
 375         $this->pgExec('DROP SEQUENCE seq_place');
 
 377         $this->pgExec('CREATE SEQUENCE seq_place start 100000');
 
 380         $sSQL = 'select distinct partition from country_name';
 
 381         $aPartitions = chksql($this->oDB->getCol($sSQL));
 
 382         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 383         foreach ($aPartitions as $sPartition) {
 
 384             $this->pgExec('TRUNCATE location_road_'.$sPartition);
 
 388         // used by getorcreate_word_id to ignore frequent partial words
 
 389         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 390         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 391         $this->pgExec($sSQL);
 
 394         // pre-create the word list
 
 395         if (!$bDisableTokenPrecalc) {
 
 396             info('Loading word list');
 
 397             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
 
 401         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 402         $aDBInstances = array();
 
 403         $iLoadThreads = max(1, $this->iInstances - 1);
 
 404         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 405             $aDBInstances[$i] =& getDB(true);
 
 406             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 407             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 408             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 409             $sSQL .= ' and ST_IsValid(geometry)';
 
 410             if ($this->bVerbose) echo "$sSQL\n";
 
 411             if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
 
 412                 fail(pg_last_error($aDBInstances[$i]->connection));
 
 416         // last thread for interpolation lines
 
 417         $aDBInstances[$iLoadThreads] =& getDB(true);
 
 418         $sSQL = 'insert into location_property_osmline';
 
 419         $sSQL .= ' (osm_id, address, linegeo)';
 
 420         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 421         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 422         if ($this->bVerbose) echo "$sSQL\n";
 
 423         if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
 
 424             fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
 
 428         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 429             while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
 
 430                 $resultStatus = pg_result_status($hPGresult);
 
 431                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 432                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 433                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 434                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 435                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 436                     $resultError = pg_result_error($hPGresult);
 
 437                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 443             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 446         info('Reanalysing database');
 
 447         $this->pgsqlRunScript('ANALYSE');
 
 449         $sDatabaseDate = getDatabaseDate($this->oDB);
 
 450         pg_query($this->oDB->connection, 'TRUNCATE import_status');
 
 451         if ($sDatabaseDate === false) {
 
 452             warn('could not determine database date.');
 
 454             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 455             pg_query($this->oDB->connection, $sSQL);
 
 456             echo "Latest data imported from $sDatabaseDate.\n";
 
 460     public function importTigerData()
 
 462         info('Import Tiger data');
 
 464         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
 
 465         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 466         $sTemplate = $this->replaceTablespace(
 
 468             CONST_Tablespace_Aux_Data,
 
 471         $sTemplate = $this->replaceTablespace(
 
 473             CONST_Tablespace_Aux_Index,
 
 476         $this->pgsqlRunScript($sTemplate, false);
 
 478         $aDBInstances = array();
 
 479         for ($i = 0; $i < $this->iInstances; $i++) {
 
 480             $aDBInstances[$i] =& getDB(true);
 
 483         foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
 
 485             $hFile = fopen($sFile, 'r');
 
 486             $sSQL = fgets($hFile, 100000);
 
 489                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 490                     if (!pg_connection_busy($aDBInstances[$i]->connection)) {
 
 491                         while (pg_get_result($aDBInstances[$i]->connection));
 
 492                         $sSQL = fgets($hFile, 100000);
 
 494                         if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
 
 496                         if ($iLines == 1000) {
 
 509                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 510                     if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
 
 517         info('Creating indexes on Tiger data');
 
 518         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
 
 519         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 520         $sTemplate = $this->replaceTablespace(
 
 522             CONST_Tablespace_Aux_Data,
 
 525         $sTemplate = $this->replaceTablespace(
 
 527             CONST_Tablespace_Aux_Index,
 
 530         $this->pgsqlRunScript($sTemplate, false);
 
 533     public function calculatePostcodes($bCMDResultAll)
 
 535         info('Calculate Postcodes');
 
 536         $this->pgExec('TRUNCATE location_postcode');
 
 538         $sSQL  = 'INSERT INTO location_postcode';
 
 539         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 540         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 541         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 542         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 543         $sSQL .= '  FROM placex';
 
 544         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 545         $sSQL .= '       AND geometry IS NOT null';
 
 546         $sSQL .= ' GROUP BY country_code, pc';
 
 547         $this->pgExec($sSQL);
 
 549         if (CONST_Use_Extra_US_Postcodes) {
 
 550             // only add postcodes that are not yet available in OSM
 
 551             $sSQL  = 'INSERT INTO location_postcode';
 
 552             $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 553             $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 554             $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 555             $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 556             $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 557             $sSQL .= "          WHERE country_code = 'us')";
 
 558             $this->pgExec($sSQL);
 
 561         // add missing postcodes for GB (if available)
 
 562         $sSQL  = 'INSERT INTO location_postcode';
 
 563         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 564         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 565         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 566         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 567         $sSQL .= "             WHERE country_code = 'gb')";
 
 568         $this->pgExec($sSQL);
 
 570         if (!$bCMDResultAll) {
 
 571             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 572             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 573             $this->pgExec($sSQL);
 
 576         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 577         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 578         $this->pgExec($sSQL);
 
 581     public function index($bIndexNoanalyse)
 
 584         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
 
 585             .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
 
 586         if (isset($this->aDSNInfo['hostspec'])) {
 
 587             $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
 
 589         if (isset($this->aDSNInfo['username'])) {
 
 590             $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
 
 593         info('Index ranks 0 - 4');
 
 594         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
 
 596             fail('error status ' . $iStatus . ' running nominatim!');
 
 598         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 600         info('Index ranks 5 - 25');
 
 601         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
 
 603             fail('error status ' . $iStatus . ' running nominatim!');
 
 605         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 607         info('Index ranks 26 - 30');
 
 608         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
 
 610             fail('error status ' . $iStatus . ' running nominatim!');
 
 613         info('Index postcodes');
 
 614         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 615         $this->pgExec($sSQL);
 
 618     public function createSearchIndices()
 
 620         info('Create Search indices');
 
 622         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
 
 623         if (!$this->dbReverseOnly()) {
 
 624             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
 
 626         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
 
 627         $sTemplate = $this->replaceTablespace(
 
 628             '{ts:address-index}',
 
 629             CONST_Tablespace_Address_Index,
 
 632         $sTemplate = $this->replaceTablespace(
 
 634             CONST_Tablespace_Search_Index,
 
 637         $sTemplate = $this->replaceTablespace(
 
 639             CONST_Tablespace_Aux_Index,
 
 642         $this->pgsqlRunScript($sTemplate);
 
 645     public function createCountryNames()
 
 647         info('Create search index for default country names');
 
 649         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
 
 650         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
 
 651         $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');
 
 652         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
 
 653         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
 
 654             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
 
 655         if (CONST_Languages) {
 
 658             foreach (explode(',', CONST_Languages) as $sLang) {
 
 659                 $sSQL .= $sDelim."'name:$sLang'";
 
 664             // all include all simple name tags
 
 665             $sSQL .= "like 'name:%'";
 
 668         $this->pgsqlRunScript($sSQL);
 
 671     public function drop()
 
 673         info('Drop tables only required for updates');
 
 675         // The implementation is potentially a bit dangerous because it uses
 
 676         // a positive selection of tables to keep, and deletes everything else.
 
 677         // Including any tables that the unsuspecting user might have manually
 
 678         // created. USE AT YOUR OWN PERIL.
 
 679         // tables we want to keep. everything else goes.
 
 680         $aKeepTables = array(
 
 686                         'location_property*',
 
 699         $aDropTables = array();
 
 700         $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
 
 702         foreach ($aHaveTables as $sTable) {
 
 704             foreach ($aKeepTables as $sKeep) {
 
 705                 if (fnmatch($sKeep, $sTable)) {
 
 710             if (!$bFound) array_push($aDropTables, $sTable);
 
 712         foreach ($aDropTables as $sDrop) {
 
 713             if ($this->bVerbose) echo "Dropping table $sDrop\n";
 
 714             @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
 
 715             // ignore warnings/errors as they might be caused by a table having
 
 716             // been deleted already by CASCADE
 
 719         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 720             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
 
 721                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
 
 722                 unlink(CONST_Osm2pgsql_Flatnode_File);
 
 727     private function pgsqlRunDropAndRestore($sDumpFile)
 
 729         $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
 
 730         if (isset($this->aDSNInfo['hostspec'])) {
 
 731             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 733         if (isset($this->aDSNInfo['username'])) {
 
 734             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 737         $this->runWithPgEnv($sCMD);
 
 740     private function pgsqlRunScript($sScript, $bfatal = true)
 
 750     private function createSqlFunctions()
 
 752         $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
 
 753         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 754         if ($this->bEnableDiffUpdates) {
 
 755             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 757         if ($this->bEnableDebugStatements) {
 
 758             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 760         if (CONST_Limit_Reindexing) {
 
 761             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 763         if (!CONST_Use_US_Tiger_Data) {
 
 764             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 766         if (!CONST_Use_Aux_Location_data) {
 
 767             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 770         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 771         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 773         $this->pgsqlRunScript($sTemplate);
 
 776     private function pgsqlRunPartitionScript($sTemplate)
 
 778         $sSQL = 'select distinct partition from country_name';
 
 779         $aPartitions = chksql($this->oDB->getCol($sSQL));
 
 780         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 782         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 783         foreach ($aMatches as $aMatch) {
 
 785             foreach ($aPartitions as $sPartitionName) {
 
 786                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 788             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 791         $this->pgsqlRunScript($sTemplate);
 
 794     private function pgsqlRunScriptFile($sFilename)
 
 796         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 798         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
 
 799         if (!$this->bVerbose) {
 
 802         if (isset($this->aDSNInfo['hostspec'])) {
 
 803             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
 
 805         if (isset($this->aDSNInfo['username'])) {
 
 806             $sCMD .= ' -U '.$this->aDSNInfo['username'];
 
 809         if (isset($this->aDSNInfo['password'])) {
 
 810             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 813         if (preg_match('/\\.gz$/', $sFilename)) {
 
 814             $aDescriptors = array(
 
 815                              0 => array('pipe', 'r'),
 
 816                              1 => array('pipe', 'w'),
 
 817                              2 => array('file', '/dev/null', 'a')
 
 819             $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
 
 820             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 821             $aReadPipe = $ahGzipPipes[1];
 
 822             fclose($ahGzipPipes[0]);
 
 824             $sCMD .= ' -f '.$sFilename;
 
 825             $aReadPipe = array('pipe', 'r');
 
 827         $aDescriptors = array(
 
 829                          1 => array('pipe', 'w'),
 
 830                          2 => array('file', '/dev/null', 'a')
 
 833         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
 
 834         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 835         // TODO: error checking
 
 836         while (!feof($ahPipes[1])) {
 
 837             echo fread($ahPipes[1], 4096);
 
 840         $iReturn = proc_close($hProcess);
 
 842             fail("pgsql returned with error code ($iReturn)");
 
 845             fclose($ahGzipPipes[1]);
 
 846             proc_close($hGzipProcess);
 
 850     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
 
 853             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 855             $sSql = str_replace($sTemplate, '', $sSql);
 
 860     private function runWithPgEnv($sCmd)
 
 862         if ($this->bVerbose) {
 
 863             echo "Execute: $sCmd\n";
 
 868         if (isset($this->aDSNInfo['password'])) {
 
 869             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 872         return runWithEnv($sCmd, $aProcEnv);
 
 876      * Execute the SQL command on the open database.
 
 878      * @param string $sSQL SQL command to execute.
 
 882      * @pre connect() must have been called.
 
 884     private function pgExec($sSQL)
 
 886         if (!pg_query($this->oDB->connection, $sSQL)) {
 
 887             fail(pg_last_error($this->oDB->connection));
 
 892      * Check if the database is in reverse-only mode.
 
 894      * @return True if there is no search_name table and infrastructure.
 
 896     private function dbReverseOnly()
 
 898         $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = 'search_name'";
 
 899         return !(chksql($this->oDB->getOne($sSQL)));