3 namespace Nominatim\Setup;
7 protected $iCacheMemory; // set in constructor
8 protected $iInstances; // set in constructor
9 protected $sModulePath; // set in constructor
10 protected $aDSNInfo; // set in constructor = DB::parseDSN(CONST_Database_DSN);
11 protected $sVerbose; // set in constructor
12 protected $sIgnoreErrors; // set in constructor
13 protected $bEnableDiffUpdates; // set in constructor
14 protected $bEnableDebugStatements; // set in constructor
15 protected $bNoPartitions; // set in constructor
16 protected $oDB = null; // set in setupDB (earliest) or later in loadData, importData, drop, createSqlFunctions, importTigerData
17 // pgsqlRunPartitionScript, calculatePostcodes, ..if no already set
19 public function __construct($callingFunction, array $aCMDResult = array())
21 // by default, use all but one processor, but never more than 15.
22 $this->iInstances = isset($aCMDResult['threads'])
23 ? $aCMDResult['threads']
24 : (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 // prepares DB for import or update, sets the Data Source Name
43 $this->aDSNInfo = \DB::parseDSN(CONST_Database_DSN);
44 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
46 // setting member variables based on command line options stored in $aCMDResult
47 $this->sVerbose = $aCMDResult['verbose'];
49 //setting default values which are not set by the update.php array
50 if (isset($aCMDResult['ignore-errors'])) {
51 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
53 $this->sIgnoreErrors = false;
55 if (isset($aCMDResult['enable-debug-statements'])) {
56 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
58 $this->bEnableDebugStatements = false;
60 if (isset($aCMDResult['no-partitions'])) {
61 $this->bNoPartitions = $aCMDResult['no-partitions'];
63 $this->bNoPartitions = false;
66 // if class is instantiated by update.php, we have to set EnableDiffUpdates to true
67 // otherwise set to value provided by setup.php's command line arg array
68 if ($callingFunction == 'update') {
69 $this->bEnableDiffUpdates = true;
70 } elseif ($callingFunction == 'setup') {
71 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
75 public function createDB()
78 $sDB = \DB::connect(CONST_Database_DSN, false);
79 if (!\PEAR::isError($sDB)) {
80 fail('database already exists ('.CONST_Database_DSN.')');
83 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
84 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
85 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
88 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
89 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
93 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
94 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
97 $result = runWithEnv($sCreateDBCmd, $aProcEnv);
98 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
101 public function setupDB()
104 $this->oDB =& getDB();
106 $fPostgresVersion = getPostgresVersion($this->oDB);
107 echo 'Postgres version found: '.$fPostgresVersion."\n";
109 if ($fPostgresVersion < 9.1) {
110 fail('Minimum supported version of Postgresql is 9.1.');
113 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
114 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
116 // For extratags and namedetails the hstore_to_json converter is
117 // needed which is only available from Postgresql 9.3+. For older
118 // versions add a dummy function that returns nothing.
119 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
121 if ($iNumFunc == 0) {
122 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
123 warn('Postgresql is too old. extratags and namedetails API not available.');
127 $fPostgisVersion = getPostgisVersion($this->oDB);
128 echo 'Postgis version found: '.$fPostgisVersion."\n";
130 if ($fPostgisVersion < 2.1) {
131 // Functions were renamed in 2.1 and throw an annoying deprecation warning
132 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
133 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
135 if ($fPostgisVersion < 2.2) {
136 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
139 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
141 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
142 echo "\n createuser ".CONST_Database_Web_User."\n\n";
146 // Try accessing the C module, so we know early if something is wrong
147 if (!checkModulePresence()) {
148 fail('error loading nominatim.so module');
151 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
152 echo 'Error: you need to download the country_osm_grid first:';
153 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
156 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
157 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
158 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
159 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
162 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
163 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
165 warn('external UK postcode table not found.');
168 if (CONST_Use_Extra_US_Postcodes) {
169 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
172 if ($this->bNoPartitions) {
173 $this->pgsqlRunScript('update country_name set partition = 0');
176 // the following will be needed by createFunctions later but
177 // is only defined in the subsequently called createTables
178 // Create dummies here that will be overwritten by the proper
179 // versions in create-tables.
180 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
181 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
184 public function importData($sOSMFile)
188 $osm2pgsql = CONST_Osm2pgsql_Binary;
189 if (!file_exists($osm2pgsql)) {
190 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
191 echo "Normally you should not need to set this manually.\n";
192 fail("osm2pgsql not found in '$osm2pgsql'");
197 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
198 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
201 if (CONST_Tablespace_Osm2pgsql_Data)
202 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
203 if (CONST_Tablespace_Osm2pgsql_Index)
204 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
205 if (CONST_Tablespace_Place_Data)
206 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
207 if (CONST_Tablespace_Place_Index)
208 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
209 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
210 $osm2pgsql .= ' -C '.$this->iCacheMemory;
211 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
212 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
213 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
215 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
216 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
219 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
220 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
222 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
223 runWithEnv($osm2pgsql, $aProcEnv);
224 if ($this->oDB == null) $this->oDB =& getDB();
225 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
230 public function createFunctions()
232 info('Create Functions');
234 // Try accessing the C module, so we know eif something is wrong
235 // update.php calls this function
236 if (!checkModulePresence()) {
237 fail('error loading nominatim.so module');
239 $this->createSqlFunctions();
242 public function createTables()
244 info('Create Tables');
246 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
247 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
248 $sTemplate = $this->replaceTablespace(
250 CONST_Tablespace_Address_Data,
253 $sTemplate = $this->replaceTablespace(
254 '{ts:address-index}',
255 CONST_Tablespace_Address_Index,
258 $sTemplate = $this->replaceTablespace(
260 CONST_Tablespace_Search_Data,
263 $sTemplate = $this->replaceTablespace(
265 CONST_Tablespace_Search_Index,
268 $sTemplate = $this->replaceTablespace(
270 CONST_Tablespace_Aux_Data,
273 $sTemplate = $this->replaceTablespace(
275 CONST_Tablespace_Aux_Index,
279 $this->pgsqlRunScript($sTemplate, false);
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 if ($this->oDB == null) $this->oDB =& getDB();
358 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
360 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
362 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
364 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
366 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
368 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
370 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
372 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
374 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
376 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
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 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
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 if (!pg_query($this->oDB->connection, $sSQL)) {
391 fail(pg_last_error($this->oDB->connection));
395 // pre-create the word list
396 if (!$bDisableTokenPrecalc) {
397 info('Loading word list');
398 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
402 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
403 $aDBInstances = array();
404 $iLoadThreads = max(1, $this->iInstances - 1);
405 for ($i = 0; $i < $iLoadThreads; $i++) {
406 $aDBInstances[$i] =& getDB(true);
407 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
408 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
409 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
410 $sSQL .= ' and ST_IsValid(geometry)';
411 if ($this->sVerbose) echo "$sSQL\n";
412 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
413 fail(pg_last_error($aDBInstances[$i]->connection));
417 // last thread for interpolation lines
418 $aDBInstances[$iLoadThreads] =& getDB(true);
419 $sSQL = 'insert into location_property_osmline';
420 $sSQL .= ' (osm_id, address, linegeo)';
421 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
422 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
423 if ($this->sVerbose) echo "$sSQL\n";
424 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
425 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
429 for ($i = 0; $i <= $iLoadThreads; $i++) {
430 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
431 $resultStatus = pg_result_status($hPGresult);
432 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
433 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
434 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
435 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
436 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
437 $resultError = pg_result_error($hPGresult);
438 echo '-- error text ' . $i . ': ' . $resultError . "\n";
444 fail('SQL errors loading placex and/or location_property_osmline tables');
447 info('Reanalysing database');
448 $this->pgsqlRunScript('ANALYSE');
450 $sDatabaseDate = getDatabaseDate($this->oDB);
451 pg_query($this->oDB->connection, 'TRUNCATE import_status');
452 if ($sDatabaseDate === false) {
453 warn('could not determine database date.');
455 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
456 pg_query($this->oDB->connection, $sSQL);
457 echo "Latest data imported from $sDatabaseDate.\n";
461 public function importTigerData()
463 info('Import Tiger data');
465 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
466 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
467 $sTemplate = $this->replaceTablespace(
469 CONST_Tablespace_Aux_Data,
472 $sTemplate = $this->replaceTablespace(
474 CONST_Tablespace_Aux_Index,
477 $this->pgsqlRunScript($sTemplate, false);
479 $aDBInstances = array();
480 for ($i = 0; $i < $this->iInstances; $i++) {
481 $aDBInstances[$i] =& getDB(true);
484 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
486 $hFile = fopen($sFile, 'r');
487 $sSQL = fgets($hFile, 100000);
490 for ($i = 0; $i < $this->iInstances; $i++) {
491 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
492 while (pg_get_result($aDBInstances[$i]->connection));
493 $sSQL = fgets($hFile, 100000);
495 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
497 if ($iLines == 1000) {
510 for ($i = 0; $i < $this->iInstances; $i++) {
511 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
518 info('Creating indexes on Tiger data');
519 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
520 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
521 $sTemplate = $this->replaceTablespace(
523 CONST_Tablespace_Aux_Data,
526 $sTemplate = $this->replaceTablespace(
528 CONST_Tablespace_Aux_Index,
531 $this->pgsqlRunScript($sTemplate, false);
534 public function calculatePostcodes($bCMDResultAll)
536 info('Calculate Postcodes');
537 if ($this->oDB == null) $this->oDB =& getDB();
538 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
539 fail(pg_last_error($this->oDB->connection));
543 $sSQL = 'INSERT INTO location_postcode';
544 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
545 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
546 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
547 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
548 $sSQL .= ' FROM placex';
549 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
550 $sSQL .= ' AND geometry IS NOT null';
551 $sSQL .= ' GROUP BY country_code, pc';
553 if (!pg_query($this->oDB->connection, $sSQL)) {
554 fail(pg_last_error($this->oDB->connection));
557 if (CONST_Use_Extra_US_Postcodes) {
558 // only add postcodes that are not yet available in OSM
559 $sSQL = 'INSERT INTO location_postcode';
560 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
561 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
562 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
563 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
564 $sSQL .= ' (SELECT postcode FROM location_postcode';
565 $sSQL .= " WHERE country_code = 'us')";
566 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
569 // add missing postcodes for GB (if available)
570 $sSQL = 'INSERT INTO location_postcode';
571 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
572 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
573 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
574 $sSQL .= ' (SELECT postcode FROM location_postcode';
575 $sSQL .= " WHERE country_code = 'gb')";
576 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
578 if (!$bCMDResultAll) {
579 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
580 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
581 if (!pg_query($this->oDB->connection, $sSQL)) {
582 fail(pg_last_error($this->oDB->connection));
585 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
586 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
588 if (!pg_query($this->oDB->connection, $sSQL)) {
589 fail(pg_last_error($this->oDB->connection));
593 public function index($bIndexNoanalyse)
596 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
597 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
598 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
599 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
601 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
602 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
605 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
606 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
609 info('Index ranks 0 - 4');
610 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
612 fail('error status ' . $iStatus . ' running nominatim!');
614 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
615 info('Index ranks 5 - 25');
616 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
618 fail('error status ' . $iStatus . ' running nominatim!');
620 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
621 info('Index ranks 26 - 30');
622 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
624 fail('error status ' . $iStatus . ' running nominatim!');
626 info('Index postcodes');
627 if ($this->oDB == null) $this->oDB =& getDB();
628 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
629 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
632 public function createSearchIndices()
634 info('Create Search indices');
636 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
637 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
638 $sTemplate = $this->replaceTablespace(
639 '{ts:address-index}',
640 CONST_Tablespace_Address_Index,
643 $sTemplate = $this->replaceTablespace(
645 CONST_Tablespace_Search_Index,
648 $sTemplate = $this->replaceTablespace(
650 CONST_Tablespace_Aux_Index,
653 $this->pgsqlRunScript($sTemplate);
656 public function createCountryNames()
658 info('Create search index for default country names');
660 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
661 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
662 $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');
663 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
664 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
665 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
666 if (CONST_Languages) {
669 foreach (explode(',', CONST_Languages) as $sLang) {
670 $sSQL .= $sDelim."'name:$sLang'";
675 // all include all simple name tags
676 $sSQL .= "like 'name:%'";
679 $this->pgsqlRunScript($sSQL);
682 public function drop()
684 info('Drop tables only required for updates');
686 // The implementation is potentially a bit dangerous because it uses
687 // a positive selection of tables to keep, and deletes everything else.
688 // Including any tables that the unsuspecting user might have manually
689 // created. USE AT YOUR OWN PERIL.
690 // tables we want to keep. everything else goes.
691 $aKeepTables = array(
697 'location_property*',
709 if ($this->oDB = null) $this->oDB =& getDB();
710 $aDropTables = array();
711 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
713 foreach ($aHaveTables as $sTable) {
715 foreach ($aKeepTables as $sKeep) {
716 if (fnmatch($sKeep, $sTable)) {
721 if (!$bFound) array_push($aDropTables, $sTable);
723 foreach ($aDropTables as $sDrop) {
724 if ($this->sVerbose) echo "dropping table $sDrop\n";
725 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
726 // ignore warnings/errors as they might be caused by a table having
727 // been deleted already by CASCADE
730 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
731 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
732 unlink(CONST_Osm2pgsql_Flatnode_File);
736 private function pgsqlRunDropAndRestore($sDumpFile)
738 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
739 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
740 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
741 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
743 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
744 $sCMD .= ' -U '.$this->aDSNInfo['username'];
747 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
748 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
750 $iReturn = runWithEnv($sCMD, $aProcEnv); // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
753 private function pgsqlRunScript($sScript, $bfatal = true)
763 private function createSqlFunctions()
765 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
766 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
767 if ($this->bEnableDiffUpdates) {
768 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
770 if ($this->bEnableDebugStatements) {
771 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
773 if (CONST_Limit_Reindexing) {
774 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
776 if (!CONST_Use_US_Tiger_Data) {
777 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
779 if (!CONST_Use_Aux_Location_data) {
780 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
782 $this->pgsqlRunScript($sTemplate);
785 private function pgsqlRunPartitionScript($sTemplate)
787 if ($this->oDB == null) $this->oDB =& getDB();
789 $sSQL = 'select distinct partition from country_name';
790 $aPartitions = chksql($this->oDB->getCol($sSQL));
791 if (!$this->bNoPartitions) $aPartitions[] = 0;
793 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
794 foreach ($aMatches as $aMatch) {
796 foreach ($aPartitions as $sPartitionName) {
797 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
799 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
802 $this->pgsqlRunScript($sTemplate);
805 private function pgsqlRunScriptFile($sFilename)
807 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
809 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
810 if (!$this->sVerbose) {
813 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
814 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
816 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
817 $sCMD .= ' -U '.$this->aDSNInfo['username'];
820 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
821 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
824 if (preg_match('/\\.gz$/', $sFilename)) {
825 $aDescriptors = array(
826 0 => array('pipe', 'r'),
827 1 => array('pipe', 'w'),
828 2 => array('file', '/dev/null', 'a')
830 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
831 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
832 $aReadPipe = $ahGzipPipes[1];
833 fclose($ahGzipPipes[0]);
835 $sCMD .= ' -f '.$sFilename;
836 $aReadPipe = array('pipe', 'r');
838 $aDescriptors = array(
840 1 => array('pipe', 'w'),
841 2 => array('file', '/dev/null', 'a')
844 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
845 if (!is_resource($hProcess)) fail('unable to start pgsql');
846 // TODO: error checking
847 while (!feof($ahPipes[1])) {
848 echo fread($ahPipes[1], 4096);
851 $iReturn = proc_close($hProcess);
853 fail("pgsql returned with error code ($iReturn)");
856 fclose($ahGzipPipes[1]);
857 proc_close($hGzipProcess);
861 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
864 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
866 $sSql = str_replace($sTemplate, '', $sSql);