3 namespace Nominatim\Setup;
 
   5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
 
   9     protected $iCacheMemory;
 
  10     protected $iInstances;
 
  11     protected $sModulePath;
 
  15     protected $sIgnoreErrors;
 
  16     protected $bEnableDiffUpdates;
 
  17     protected $bEnableDebugStatements;
 
  18     protected $bNoPartitions;
 
  20     protected $oDB = null;
 
  22     public function __construct(array $aCMDResult)
 
  24         // by default, use all but one processor, but never more than 15.
 
  25         $this->iInstances = isset($aCMDResult['threads'])
 
  26             ? $aCMDResult['threads']
 
  27             : (min(16, getProcessorCount()) - 1);
 
  29         if ($this->iInstances < 1) {
 
  30             $this->iInstances = 1;
 
  31             warn('resetting threads to '.$this->iInstances);
 
  34         if (isset($aCMDResult['osm2pgsql-cache'])) {
 
  35             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
 
  36         } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
 
  37             // When flatnode files are enabled then disable cache per default.
 
  38             $this->iCacheMemory = 0;
 
  40             // Otherwise: Assume we can steal all the cache memory in the box.
 
  41             $this->iCacheMemory = getCacheMemoryMB();
 
  44         $this->sModulePath = CONST_Database_Module_Path;
 
  45         info('module path: ' . $this->sModulePath);
 
  47         // parse database string
 
  48         $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
 
  49         if (!isset($this->aDSNInfo['port'])) {
 
  50             $this->aDSNInfo['port'] = 5432;
 
  53         // setting member variables based on command line options stored in $aCMDResult
 
  54         $this->bQuiet = $aCMDResult['quiet'];
 
  55         $this->bVerbose = $aCMDResult['verbose'];
 
  57         //setting default values which are not set by the update.php array
 
  58         if (isset($aCMDResult['ignore-errors'])) {
 
  59             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
 
  61             $this->sIgnoreErrors = false;
 
  63         if (isset($aCMDResult['enable-debug-statements'])) {
 
  64             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
 
  66             $this->bEnableDebugStatements = false;
 
  68         if (isset($aCMDResult['no-partitions'])) {
 
  69             $this->bNoPartitions = $aCMDResult['no-partitions'];
 
  71             $this->bNoPartitions = false;
 
  73         if (isset($aCMDResult['enable-diff-updates'])) {
 
  74             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
 
  76             $this->bEnableDiffUpdates = false;
 
  79         $this->bDrop = $aCMDResult['drop'];
 
  82     public function createDB()
 
  85         $oDB = new \Nominatim\DB;
 
  87         if ($oDB->databaseExists()) {
 
  88             fail('database already exists ('.CONST_Database_DSN.')');
 
  91         $sCreateDBCmd = 'createdb -E UTF-8'
 
  92             .' -p '.escapeshellarg($this->aDSNInfo['port'])
 
  93             .' '.escapeshellarg($this->aDSNInfo['database']);
 
  94         if (isset($this->aDSNInfo['username'])) {
 
  95             $sCreateDBCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
  98         if (isset($this->aDSNInfo['hostspec'])) {
 
  99             $sCreateDBCmd .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 102         $result = $this->runWithPgEnv($sCreateDBCmd);
 
 103         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
 
 106     public function connect()
 
 108         $this->oDB = new \Nominatim\DB();
 
 109         $this->oDB->connect();
 
 112     public function setupDB()
 
 116         $fPostgresVersion = $this->oDB->getPostgresVersion();
 
 117         echo 'Postgres version found: '.$fPostgresVersion."\n";
 
 119         if ($fPostgresVersion < 9.03) {
 
 120             fail('Minimum supported version of Postgresql is 9.3.');
 
 123         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
 
 124         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
 
 126         $fPostgisVersion = $this->oDB->getPostgisVersion();
 
 127         echo 'Postgis version found: '.$fPostgisVersion."\n";
 
 129         if ($fPostgisVersion < 2.2) {
 
 130             echo "Minimum required Postgis version 2.2\n";
 
 134         $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
 
 136             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
 
 137             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
 
 141         // Try accessing the C module, so we know early if something is wrong
 
 142         checkModulePresence(); // raises exception on failure
 
 144         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
 
 145             echo 'Error: you need to download the country_osm_grid first:';
 
 146             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
 
 149         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
 
 150         $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
 
 151         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
 
 152         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
 
 154         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
 
 155         if (file_exists($sPostcodeFilename)) {
 
 156             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 158             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 161         $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
 
 162         if (file_exists($sPostcodeFilename)) {
 
 163             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 165             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 168         if ($this->bNoPartitions) {
 
 169             $this->pgsqlRunScript('update country_name set partition = 0');
 
 173     public function importData($sOSMFile)
 
 177         $osm2pgsql = CONST_Osm2pgsql_Binary;
 
 178         if (!file_exists($osm2pgsql)) {
 
 179             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
 
 180             echo "Normally you should not need to set this manually.\n";
 
 181             fail("osm2pgsql not found in '$osm2pgsql'");
 
 184         $osm2pgsql .= ' -S '.escapeshellarg(CONST_Import_Style);
 
 186         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 187             $osm2pgsql .= ' --flat-nodes '.escapeshellarg(CONST_Osm2pgsql_Flatnode_File);
 
 190         if (CONST_Tablespace_Osm2pgsql_Data)
 
 191             $osm2pgsql .= ' --tablespace-slim-data '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Data);
 
 192         if (CONST_Tablespace_Osm2pgsql_Index)
 
 193             $osm2pgsql .= ' --tablespace-slim-index '.escapeshellarg(CONST_Tablespace_Osm2pgsql_Index);
 
 194         if (CONST_Tablespace_Place_Data)
 
 195             $osm2pgsql .= ' --tablespace-main-data '.escapeshellarg(CONST_Tablespace_Place_Data);
 
 196         if (CONST_Tablespace_Place_Index)
 
 197             $osm2pgsql .= ' --tablespace-main-index '.escapeshellarg(CONST_Tablespace_Place_Index);
 
 198         $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
 
 199         $osm2pgsql .= ' -C '.escapeshellarg($this->iCacheMemory);
 
 200         $osm2pgsql .= ' -P '.escapeshellarg($this->aDSNInfo['port']);
 
 201         if (isset($this->aDSNInfo['username'])) {
 
 202             $osm2pgsql .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 204         if (isset($this->aDSNInfo['hostspec'])) {
 
 205             $osm2pgsql .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 207         $osm2pgsql .= ' -d '.escapeshellarg($this->aDSNInfo['database']).' '.escapeshellarg($sOSMFile);
 
 209         $this->runWithPgEnv($osm2pgsql);
 
 211         if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
 
 216             $this->dropTable('planet_osm_nodes');
 
 217             $this->removeFlatnodeFile();
 
 221     public function createFunctions()
 
 223         info('Create Functions');
 
 225         // Try accessing the C module, so we know early if something is wrong
 
 226         checkModulePresence(); // raises exception on failure
 
 228         $this->createSqlFunctions();
 
 231     public function createTables($bReverseOnly = false)
 
 233         info('Create Tables');
 
 235         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
 
 236         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 238         $this->pgsqlRunScript($sTemplate, false);
 
 241             $this->dropTable('search_name');
 
 244         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
 
 245         $oAlParser->createTable($this->oDB, 'address_levels');
 
 248     public function createTableTriggers()
 
 250         info('Create Tables');
 
 252         $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
 
 253         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 255         $this->pgsqlRunScript($sTemplate, false);
 
 258     public function createPartitionTables()
 
 260         info('Create Partition Tables');
 
 262         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
 
 263         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 265         $this->pgsqlRunPartitionScript($sTemplate);
 
 268     public function createPartitionFunctions()
 
 270         info('Create Partition Functions');
 
 272         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
 
 273         $this->pgsqlRunPartitionScript($sTemplate);
 
 276     public function importWikipediaArticles()
 
 278         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
 
 279         if (file_exists($sWikiArticlesFile)) {
 
 280             info('Importing wikipedia articles and redirects');
 
 281             $this->dropTable('wikipedia_article');
 
 282             $this->dropTable('wikipedia_redirect');
 
 283             $this->pgsqlRunScriptFile($sWikiArticlesFile);
 
 285             warn('wikipedia importance dump file not found - places will have default importance');
 
 289     public function loadData($bDisableTokenPrecalc)
 
 291         info('Drop old Data');
 
 293         $this->oDB->exec('TRUNCATE word');
 
 295         $this->oDB->exec('TRUNCATE placex');
 
 297         $this->oDB->exec('TRUNCATE location_property_osmline');
 
 299         $this->oDB->exec('TRUNCATE place_addressline');
 
 301         $this->oDB->exec('TRUNCATE location_area');
 
 303         if (!$this->dbReverseOnly()) {
 
 304             $this->oDB->exec('TRUNCATE search_name');
 
 307         $this->oDB->exec('TRUNCATE search_name_blank');
 
 309         $this->oDB->exec('DROP SEQUENCE seq_place');
 
 311         $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
 
 314         $sSQL = 'select distinct partition from country_name';
 
 315         $aPartitions = $this->oDB->getCol($sSQL);
 
 317         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 318         foreach ($aPartitions as $sPartition) {
 
 319             $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
 
 323         // used by getorcreate_word_id to ignore frequent partial words
 
 324         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 325         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 326         $this->oDB->exec($sSQL);
 
 329         // pre-create the word list
 
 330         if (!$bDisableTokenPrecalc) {
 
 331             info('Loading word list');
 
 332             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
 
 336         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 338         $aDBInstances = array();
 
 339         $iLoadThreads = max(1, $this->iInstances - 1);
 
 340         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 341             // https://secure.php.net/manual/en/function.pg-connect.php
 
 342             $DSN = CONST_Database_DSN;
 
 343             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 344             $DSN = preg_replace('/;/', ' ', $DSN);
 
 345             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 346             pg_ping($aDBInstances[$i]);
 
 349         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 350             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 351             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 352             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 353             $sSQL .= ' and ST_IsValid(geometry)';
 
 354             if ($this->bVerbose) echo "$sSQL\n";
 
 355             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
 
 356                 fail(pg_last_error($aDBInstances[$i]));
 
 360         // last thread for interpolation lines
 
 361         // https://secure.php.net/manual/en/function.pg-connect.php
 
 362         $DSN = CONST_Database_DSN;
 
 363         $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 364         $DSN = preg_replace('/;/', ' ', $DSN);
 
 365         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 366         pg_ping($aDBInstances[$iLoadThreads]);
 
 367         $sSQL = 'insert into location_property_osmline';
 
 368         $sSQL .= ' (osm_id, address, linegeo)';
 
 369         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 370         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 371         if ($this->bVerbose) echo "$sSQL\n";
 
 372         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
 
 373             fail(pg_last_error($aDBInstances[$iLoadThreads]));
 
 377         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 378             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
 
 379                 $resultStatus = pg_result_status($hPGresult);
 
 380                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 381                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 382                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 383                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 384                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 385                     $resultError = pg_result_error($hPGresult);
 
 386                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 392             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 395         for ($i = 0; $i < $this->iInstances; $i++) {
 
 396             pg_close($aDBInstances[$i]);
 
 400         info('Reanalysing database');
 
 401         $this->pgsqlRunScript('ANALYSE');
 
 403         $sDatabaseDate = getDatabaseDate($this->oDB);
 
 404         $this->oDB->exec('TRUNCATE import_status');
 
 405         if (!$sDatabaseDate) {
 
 406             warn('could not determine database date.');
 
 408             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 409             $this->oDB->exec($sSQL);
 
 410             echo "Latest data imported from $sDatabaseDate.\n";
 
 414     public function importTigerData()
 
 416         info('Import Tiger data');
 
 418         $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
 
 419         info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
 
 420         if (empty($aFilenames)) {
 
 421             warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
 
 424         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
 
 425         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 427         $this->pgsqlRunScript($sTemplate, false);
 
 429         $aDBInstances = array();
 
 430         for ($i = 0; $i < $this->iInstances; $i++) {
 
 431             // https://secure.php.net/manual/en/function.pg-connect.php
 
 432             $DSN = CONST_Database_DSN;
 
 433             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 434             $DSN = preg_replace('/;/', ' ', $DSN);
 
 435             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
 
 436             pg_ping($aDBInstances[$i]);
 
 439         foreach ($aFilenames as $sFile) {
 
 441             $hFile = fopen($sFile, 'r');
 
 442             $sSQL = fgets($hFile, 100000);
 
 445                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 446                     if (!pg_connection_busy($aDBInstances[$i])) {
 
 447                         while (pg_get_result($aDBInstances[$i]));
 
 448                         $sSQL = fgets($hFile, 100000);
 
 450                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
 
 452                         if ($iLines == 1000) {
 
 465                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 466                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
 
 473         for ($i = 0; $i < $this->iInstances; $i++) {
 
 474             pg_close($aDBInstances[$i]);
 
 477         info('Creating indexes on Tiger data');
 
 478         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
 
 479         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 481         $this->pgsqlRunScript($sTemplate, false);
 
 484     public function calculatePostcodes($bCMDResultAll)
 
 486         info('Calculate Postcodes');
 
 487         $this->oDB->exec('TRUNCATE location_postcode');
 
 489         $sSQL  = 'INSERT INTO location_postcode';
 
 490         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 491         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 492         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 493         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 494         $sSQL .= '  FROM placex';
 
 495         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 496         $sSQL .= '       AND geometry IS NOT null';
 
 497         $sSQL .= ' GROUP BY country_code, pc';
 
 498         $this->oDB->exec($sSQL);
 
 500         // only add postcodes that are not yet available in OSM
 
 501         $sSQL  = 'INSERT INTO location_postcode';
 
 502         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 503         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 504         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 505         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 506         $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 507         $sSQL .= "          WHERE country_code = 'us')";
 
 508         $this->oDB->exec($sSQL);
 
 510         // add missing postcodes for GB (if available)
 
 511         $sSQL  = 'INSERT INTO location_postcode';
 
 512         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 513         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 514         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 515         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 516         $sSQL .= "             WHERE country_code = 'gb')";
 
 517         $this->oDB->exec($sSQL);
 
 519         if (!$bCMDResultAll) {
 
 520             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 521             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 522             $this->oDB->exec($sSQL);
 
 525         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 526         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 527         $this->oDB->exec($sSQL);
 
 530     public function index($bIndexNoanalyse)
 
 532         $sBaseCmd = CONST_BasePath.'/nominatim/nominatim.py'
 
 533             .' -d '.escapeshellarg($this->aDSNInfo['database'])
 
 534             .' -P '.escapeshellarg($this->aDSNInfo['port'])
 
 535             .' -t '.escapeshellarg($this->iInstances);
 
 536         if (!$this->bQuiet) {
 
 539         if ($this->bVerbose) {
 
 542         if (isset($this->aDSNInfo['hostspec'])) {
 
 543             $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 545         if (isset($this->aDSNInfo['username'])) {
 
 546             $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 549         info('Index ranks 0 - 4');
 
 550         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
 
 552             fail('error status ' . $iStatus . ' running nominatim!');
 
 554         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 556         info('Index ranks 5 - 25');
 
 557         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
 
 559             fail('error status ' . $iStatus . ' running nominatim!');
 
 561         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 563         info('Index ranks 26 - 30');
 
 564         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
 
 566             fail('error status ' . $iStatus . ' running nominatim!');
 
 569         info('Index postcodes');
 
 570         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 571         $this->oDB->exec($sSQL);
 
 574     public function createSearchIndices()
 
 576         info('Create Search indices');
 
 578         $sSQL = 'SELECT relname FROM pg_class, pg_index ';
 
 579         $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
 
 580         $aInvalidIndices = $this->oDB->getCol($sSQL);
 
 582         foreach ($aInvalidIndices as $sIndexName) {
 
 583             info("Cleaning up invalid index $sIndexName");
 
 584             $this->oDB->exec("DROP INDEX $sIndexName;");
 
 587         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
 
 589             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
 
 591         if (!$this->dbReverseOnly()) {
 
 592             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
 
 594         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 596         $this->pgsqlRunScript($sTemplate);
 
 599     public function createCountryNames()
 
 601         info('Create search index for default country names');
 
 603         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
 
 604         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
 
 605         $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');
 
 606         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
 
 607         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
 
 608             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
 
 609         if (CONST_Languages) {
 
 612             foreach (explode(',', CONST_Languages) as $sLang) {
 
 613                 $sSQL .= $sDelim."'name:$sLang'";
 
 618             // all include all simple name tags
 
 619             $sSQL .= "like 'name:%'";
 
 622         $this->pgsqlRunScript($sSQL);
 
 625     public function drop()
 
 627         info('Drop tables only required for updates');
 
 629         // The implementation is potentially a bit dangerous because it uses
 
 630         // a positive selection of tables to keep, and deletes everything else.
 
 631         // Including any tables that the unsuspecting user might have manually
 
 632         // created. USE AT YOUR OWN PERIL.
 
 633         // tables we want to keep. everything else goes.
 
 634         $aKeepTables = array(
 
 640                         'location_property*',
 
 653         $aDropTables = array();
 
 654         $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
 
 656         foreach ($aHaveTables as $sTable) {
 
 658             foreach ($aKeepTables as $sKeep) {
 
 659                 if (fnmatch($sKeep, $sTable)) {
 
 664             if (!$bFound) array_push($aDropTables, $sTable);
 
 666         foreach ($aDropTables as $sDrop) {
 
 667             $this->dropTable($sDrop);
 
 670         $this->removeFlatnodeFile();
 
 673     private function removeFlatnodeFile()
 
 675         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
 
 676             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
 
 677                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
 
 678                 unlink(CONST_Osm2pgsql_Flatnode_File);
 
 683     private function pgsqlRunScript($sScript, $bfatal = true)
 
 693     private function createSqlFunctions()
 
 695         $sBasePath = CONST_BasePath.'/sql/functions/';
 
 696         $sTemplate = file_get_contents($sBasePath.'utils.sql');
 
 697         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
 
 698         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
 
 699         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
 
 700         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
 
 701         if ($this->oDB->tableExists('place')) {
 
 702             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
 
 704         if ($this->oDB->tableExists('placex')) {
 
 705             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
 
 707         if ($this->oDB->tableExists('location_postcode')) {
 
 708             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
 
 710         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 711         if ($this->bEnableDiffUpdates) {
 
 712             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 714         if ($this->bEnableDebugStatements) {
 
 715             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 717         if (CONST_Limit_Reindexing) {
 
 718             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 720         if (!CONST_Use_US_Tiger_Data) {
 
 721             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 723         if (!CONST_Use_Aux_Location_data) {
 
 724             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 727         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 728         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 730         $this->pgsqlRunScript($sTemplate);
 
 733     private function pgsqlRunPartitionScript($sTemplate)
 
 735         $sSQL = 'select distinct partition from country_name';
 
 736         $aPartitions = $this->oDB->getCol($sSQL);
 
 737         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 739         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 740         foreach ($aMatches as $aMatch) {
 
 742             foreach ($aPartitions as $sPartitionName) {
 
 743                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 745             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 748         $this->pgsqlRunScript($sTemplate);
 
 751     private function pgsqlRunScriptFile($sFilename)
 
 753         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 756             .' -p '.escapeshellarg($this->aDSNInfo['port'])
 
 757             .' -d '.escapeshellarg($this->aDSNInfo['database']);
 
 758         if (!$this->bVerbose) {
 
 761         if (isset($this->aDSNInfo['hostspec'])) {
 
 762             $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
 
 764         if (isset($this->aDSNInfo['username'])) {
 
 765             $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
 
 768         if (isset($this->aDSNInfo['password'])) {
 
 769             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 772         if (preg_match('/\\.gz$/', $sFilename)) {
 
 773             $aDescriptors = array(
 
 774                              0 => array('pipe', 'r'),
 
 775                              1 => array('pipe', 'w'),
 
 776                              2 => array('file', '/dev/null', 'a')
 
 778             $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
 
 779             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 780             $aReadPipe = $ahGzipPipes[1];
 
 781             fclose($ahGzipPipes[0]);
 
 783             $sCMD .= ' -f '.escapeshellarg($sFilename);
 
 784             $aReadPipe = array('pipe', 'r');
 
 786         $aDescriptors = array(
 
 788                          1 => array('pipe', 'w'),
 
 789                          2 => array('file', '/dev/null', 'a')
 
 792         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
 
 793         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 794         // TODO: error checking
 
 795         while (!feof($ahPipes[1])) {
 
 796             echo fread($ahPipes[1], 4096);
 
 799         $iReturn = proc_close($hProcess);
 
 801             fail("pgsql returned with error code ($iReturn)");
 
 804             fclose($ahGzipPipes[1]);
 
 805             proc_close($hGzipProcess);
 
 809     private function replaceSqlPatterns($sSql)
 
 811         $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
 
 814                       '{ts:address-data}' => CONST_Tablespace_Address_Data,
 
 815                       '{ts:address-index}' => CONST_Tablespace_Address_Index,
 
 816                       '{ts:search-data}' => CONST_Tablespace_Search_Data,
 
 817                       '{ts:search-index}' =>  CONST_Tablespace_Search_Index,
 
 818                       '{ts:aux-data}' =>  CONST_Tablespace_Aux_Data,
 
 819                       '{ts:aux-index}' =>  CONST_Tablespace_Aux_Index,
 
 822         foreach ($aPatterns as $sPattern => $sTablespace) {
 
 824                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 826                 $sSql = str_replace($sPattern, '', $sSql);
 
 833     private function runWithPgEnv($sCmd)
 
 835         if ($this->bVerbose) {
 
 836             echo "Execute: $sCmd\n";
 
 841         if (isset($this->aDSNInfo['password'])) {
 
 842             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
 
 845         return runWithEnv($sCmd, $aProcEnv);
 
 849      * Drop table with the given name if it exists.
 
 851      * @param string $sName Name of table to remove.
 
 855      * @pre connect() must have been called.
 
 857     private function dropTable($sName)
 
 859         if ($this->bVerbose) echo "Dropping table $sName\n";
 
 860         $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
 
 864      * Check if the database is in reverse-only mode.
 
 866      * @return True if there is no search_name table and infrastructure.
 
 868     private function dbReverseOnly()
 
 870         return !($this->oDB->tableExists('search_name'));