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($aCMDResult)
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'];
48 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
50 //setting default values which are not set by the update.php array
51 if (isset($aCMDResult['ignore-errors'])) {
52 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
54 $this->sIgnoreErrors = false;
56 if (isset($aCMDResult['enable-debug-statements'])) {
57 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
59 $this->bEnableDebugStatements = false;
61 if (isset($aCMDResult['no-partitions'])) {
62 $this->bNoPartitions = $aCMDResult['no-partitions'];
64 $this->bNoPartitions = false;
68 public function createDB()
71 $sDB = \DB::connect(CONST_Database_DSN, false);
72 if (!\PEAR::isError($sDB)) {
73 fail('database already exists ('.CONST_Database_DSN.')');
76 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
77 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
78 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
81 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
82 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
86 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
87 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
90 $result = runWithEnv($sCreateDBCmd, $aProcEnv);
91 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
94 public function setupDB()
97 $this->oDB =& getDB();
99 $fPostgresVersion = getPostgresVersion($this->oDB);
100 echo 'Postgres version found: '.$fPostgresVersion."\n";
102 if ($fPostgresVersion < 9.1) {
103 fail('Minimum supported version of Postgresql is 9.1.');
106 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
107 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
109 // For extratags and namedetails the hstore_to_json converter is
110 // needed which is only available from Postgresql 9.3+. For older
111 // versions add a dummy function that returns nothing.
112 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
114 if ($iNumFunc == 0) {
115 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
116 warn('Postgresql is too old. extratags and namedetails API not available.');
120 $fPostgisVersion = getPostgisVersion($this->oDB);
121 echo 'Postgis version found: '.$fPostgisVersion."\n";
123 if ($fPostgisVersion < 2.1) {
124 // Functions were renamed in 2.1 and throw an annoying deprecation warning
125 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
126 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
128 if ($fPostgisVersion < 2.2) {
129 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
132 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
134 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
135 echo "\n createuser ".CONST_Database_Web_User."\n\n";
139 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
140 echo 'Error: you need to download the country_osm_grid first:';
141 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
144 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
145 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
146 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
147 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
150 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
151 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
153 warn('external UK postcode table not found.');
156 if (CONST_Use_Extra_US_Postcodes) {
157 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
160 if ($this->bNoPartitions) {
161 $this->pgsqlRunScript('update country_name set partition = 0');
164 // the following will be needed by create_functions later but
165 // is only defined in the subsequently called T
166 // Create dummies here that will be overwritten by the proper
167 // versions in create-tables.
168 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
169 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
172 public function importData($sOSMFile)
176 $osm2pgsql = CONST_Osm2pgsql_Binary;
177 if (!file_exists($osm2pgsql)) {
178 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
179 echo "Normally you should not need to set this manually.\n";
180 fail("osm2pgsql not found in '$osm2pgsql'");
185 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
186 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
189 if (CONST_Tablespace_Osm2pgsql_Data)
190 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
191 if (CONST_Tablespace_Osm2pgsql_Index)
192 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
193 if (CONST_Tablespace_Place_Data)
194 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
195 if (CONST_Tablespace_Place_Index)
196 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
197 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
198 $osm2pgsql .= ' -C '.$this->iCacheMemory;
199 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
200 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
201 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
203 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
204 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
207 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
208 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
210 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
211 runWithEnv($osm2pgsql, $aProcEnv);
212 if ($this->oDB == null) $this->oDB =& getDB();
213 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
218 public function createFunctions()
220 info('Create Functions');
222 $this->createSqlFunctions();
225 public function createTables()
227 info('Create Tables');
229 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
230 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
231 $sTemplate = $this->replaceTablespace(
233 CONST_Tablespace_Address_Data,
236 $sTemplate = $this->replaceTablespace(
237 '{ts:address-index}',
238 CONST_Tablespace_Address_Index,
241 $sTemplate = $this->replaceTablespace(
243 CONST_Tablespace_Search_Data,
246 $sTemplate = $this->replaceTablespace(
248 CONST_Tablespace_Search_Index,
251 $sTemplate = $this->replaceTablespace(
253 CONST_Tablespace_Aux_Data,
256 $sTemplate = $this->replaceTablespace(
258 CONST_Tablespace_Aux_Index,
262 $this->pgsqlRunScript($sTemplate, false);
265 public function createPartitionTables()
267 info('Create Partition Tables');
269 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
270 $sTemplate = $this->replaceTablespace(
272 CONST_Tablespace_Address_Data,
276 $sTemplate = $this->replaceTablespace(
277 '{ts:address-index}',
278 CONST_Tablespace_Address_Index,
282 $sTemplate = $this->replaceTablespace(
284 CONST_Tablespace_Search_Data,
288 $sTemplate = $this->replaceTablespace(
290 CONST_Tablespace_Search_Index,
294 $sTemplate = $this->replaceTablespace(
296 CONST_Tablespace_Aux_Data,
300 $sTemplate = $this->replaceTablespace(
302 CONST_Tablespace_Aux_Index,
306 $this->pgsqlRunPartitionScript($sTemplate);
309 public function createPartitionFunctions()
311 info('Create Partition Functions');
313 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
314 $this->pgsqlRunPartitionScript($sTemplate);
317 public function importWikipediaArticles()
319 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
320 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
321 if (file_exists($sWikiArticlesFile)) {
322 info('Importing wikipedia articles');
323 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
325 warn('wikipedia article dump file not found - places will have default importance');
327 if (file_exists($sWikiRedirectsFile)) {
328 info('Importing wikipedia redirects');
329 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
331 warn('wikipedia redirect dump file not found - some place importance values may be missing');
333 echo ' finish wikipedia';
336 public function loadData($bDisableTokenPrecalc)
338 info('Drop old Data');
340 if ($this->oDB == null) $this->oDB =& getDB();
342 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
344 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
346 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
348 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
350 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
352 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
354 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
356 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
358 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
360 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
363 $sSQL = 'select distinct partition from country_name';
364 $aPartitions = chksql($this->oDB->getCol($sSQL));
365 if (!$this->bNoPartitions) $aPartitions[] = 0;
366 foreach ($aPartitions as $sPartition) {
367 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
371 // used by getorcreate_word_id to ignore frequent partial words
372 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
373 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
374 if (!pg_query($this->oDB->connection, $sSQL)) {
375 fail(pg_last_error($this->oDB->connection));
379 // pre-create the word list
380 if (!$bDisableTokenPrecalc) {
381 info('Loading word list');
382 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
386 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
387 $aDBInstances = array();
388 $iLoadThreads = max(1, $this->iInstances - 1);
389 for ($i = 0; $i < $iLoadThreads; $i++) {
390 $aDBInstances[$i] =& getDB(true);
391 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
392 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
393 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
394 $sSQL .= ' and ST_IsValid(geometry)';
395 if ($this->sVerbose) echo "$sSQL\n";
396 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
397 fail(pg_last_error($aDBInstances[$i]->connection));
401 // last thread for interpolation lines
402 $aDBInstances[$iLoadThreads] =& getDB(true);
403 $sSQL = 'insert into location_property_osmline';
404 $sSQL .= ' (osm_id, address, linegeo)';
405 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
406 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
407 if ($this->sVerbose) echo "$sSQL\n";
408 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
409 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
413 for ($i = 0; $i <= $iLoadThreads; $i++) {
414 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
415 $resultStatus = pg_result_status($hPGresult);
416 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
417 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
418 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
419 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
420 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
421 $resultError = pg_result_error($hPGresult);
422 echo '-- error text ' . $i . ': ' . $resultError . "\n";
428 fail('SQL errors loading placex and/or location_property_osmline tables');
431 info('Reanalysing database');
432 $this->pgsqlRunScript('ANALYSE');
434 $sDatabaseDate = getDatabaseDate($this->oDB);
435 pg_query($this->oDB->connection, 'TRUNCATE import_status');
436 if ($sDatabaseDate === false) {
437 warn('could not determine database date.');
439 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
440 pg_query($this->oDB->connection, $sSQL);
441 echo "Latest data imported from $sDatabaseDate.\n";
445 public function importTigerData()
447 info('Import Tiger data');
449 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
450 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
451 $sTemplate = $this->replaceTablespace(
453 CONST_Tablespace_Aux_Data,
456 $sTemplate = $this->replaceTablespace(
458 CONST_Tablespace_Aux_Index,
461 $this->pgsqlRunScript($sTemplate, false);
463 $aDBInstances = array();
464 for ($i = 0; $i < $this->iInstances; $i++) {
465 $aDBInstances[$i] =& getDB(true);
468 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
470 $hFile = fopen($sFile, 'r');
471 $sSQL = fgets($hFile, 100000);
474 for ($i = 0; $i < $this->iInstances; $i++) {
475 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
476 while (pg_get_result($aDBInstances[$i]->connection));
477 $sSQL = fgets($hFile, 100000);
479 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
481 if ($iLines == 1000) {
494 for ($i = 0; $i < $this->iInstances; $i++) {
495 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
502 info('Creating indexes on Tiger data');
503 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
504 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
505 $sTemplate = $this->replaceTablespace(
507 CONST_Tablespace_Aux_Data,
510 $sTemplate = $this->replaceTablespace(
512 CONST_Tablespace_Aux_Index,
515 $this->pgsqlRunScript($sTemplate, false);
518 public function calculatePostcodes($bCMDResultAll)
520 info('Calculate Postcodes');
521 if ($this->oDB == null) $this->oDB =& getDB();
522 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
523 fail(pg_last_error($this->oDB->connection));
527 $sSQL = 'INSERT INTO location_postcode';
528 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
529 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
530 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
531 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
532 $sSQL .= ' FROM placex';
533 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
534 $sSQL .= ' AND geometry IS NOT null';
535 $sSQL .= ' GROUP BY country_code, pc';
537 if (!pg_query($this->oDB->connection, $sSQL)) {
538 fail(pg_last_error($this->oDB->connection));
541 if (CONST_Use_Extra_US_Postcodes) {
542 // only add postcodes that are not yet available in OSM
543 $sSQL = 'INSERT INTO location_postcode';
544 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
545 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
546 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
547 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
548 $sSQL .= ' (SELECT postcode FROM location_postcode';
549 $sSQL .= " WHERE country_code = 'us')";
550 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
553 // add missing postcodes for GB (if available)
554 $sSQL = 'INSERT INTO location_postcode';
555 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
556 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
557 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
558 $sSQL .= ' (SELECT postcode FROM location_postcode';
559 $sSQL .= " WHERE country_code = 'gb')";
560 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
562 if (!$bCMDResultAll) {
563 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
564 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
565 if (!pg_query($this->oDB->connection, $sSQL)) {
566 fail(pg_last_error($this->oDB->connection));
569 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
570 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
572 if (!pg_query($this->oDB->connection, $sSQL)) {
573 fail(pg_last_error($this->oDB->connection));
577 public function index($bIndexNoanalyse)
580 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
581 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
582 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
583 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
585 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
586 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
589 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
590 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
593 info('Index ranks 0 - 4');
594 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
596 fail('error status ' . $iStatus . ' running nominatim!');
598 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
599 info('Index ranks 5 - 25');
600 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
602 fail('error status ' . $iStatus . ' running nominatim!');
604 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
605 info('Index ranks 26 - 30');
606 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
608 fail('error status ' . $iStatus . ' running nominatim!');
610 info('Index postcodes');
611 if ($this->oDB == null) $this->oDB =& getDB();
612 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
613 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
616 public function createSearchIndices()
618 info('Create Search indices');
620 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
621 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
622 $sTemplate = $this->replaceTablespace(
623 '{ts:address-index}',
624 CONST_Tablespace_Address_Index,
627 $sTemplate = $this->replaceTablespace(
629 CONST_Tablespace_Search_Index,
632 $sTemplate = $this->replaceTablespace(
634 CONST_Tablespace_Aux_Index,
637 $this->pgsqlRunScript($sTemplate);
640 public function createCountryNames()
642 info('Create search index for default country names');
644 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
645 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
646 $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');
647 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
648 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
649 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
650 if (CONST_Languages) {
653 foreach (explode(',', CONST_Languages) as $sLang) {
654 $sSQL .= $sDelim."'name:$sLang'";
659 // all include all simple name tags
660 $sSQL .= "like 'name:%'";
663 $this->pgsqlRunScript($sSQL);
666 public function drop()
668 info('Drop tables only required for updates');
670 // The implementation is potentially a bit dangerous because it uses
671 // a positive selection of tables to keep, and deletes everything else.
672 // Including any tables that the unsuspecting user might have manually
673 // created. USE AT YOUR OWN PERIL.
674 // tables we want to keep. everything else goes.
675 $aKeepTables = array(
681 'location_property*',
693 if ($this->oDB = null) $this->oDB =& getDB();
694 $aDropTables = array();
695 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
697 foreach ($aHaveTables as $sTable) {
699 foreach ($aKeepTables as $sKeep) {
700 if (fnmatch($sKeep, $sTable)) {
705 if (!$bFound) array_push($aDropTables, $sTable);
707 foreach ($aDropTables as $sDrop) {
708 if ($this->sVerbose) echo "dropping table $sDrop\n";
709 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
710 // ignore warnings/errors as they might be caused by a table having
711 // been deleted already by CASCADE
714 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
715 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
716 unlink(CONST_Osm2pgsql_Flatnode_File);
720 private function pgsqlRunDropAndRestore($sDumpFile)
722 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
723 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
724 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
725 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
727 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
728 $sCMD .= ' -U '.$this->aDSNInfo['username'];
731 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
732 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
734 $iReturn = runWithEnv($sCMD, $aProcEnv); // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
737 private function pgsqlRunScript($sScript, $bfatal = true)
747 private function createSqlFunctions()
749 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
750 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
751 if ($this->bEnableDiffUpdates) {
752 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
754 if ($this->bEnableDebugStatements) {
755 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
757 if (CONST_Limit_Reindexing) {
758 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
760 if (!CONST_Use_US_Tiger_Data) {
761 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
763 if (!CONST_Use_Aux_Location_data) {
764 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
766 $this->pgsqlRunScript($sTemplate);
769 private function pgsqlRunPartitionScript($sTemplate)
771 if ($this->oDB == null) $this->oDB =& getDB();
773 $sSQL = 'select distinct partition from country_name';
774 $aPartitions = chksql($this->oDB->getCol($sSQL));
775 if (!$this->bNoPartitions) $aPartitions[] = 0;
777 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
778 foreach ($aMatches as $aMatch) {
780 foreach ($aPartitions as $sPartitionName) {
781 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
783 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
786 $this->pgsqlRunScript($sTemplate);
789 private function pgsqlRunScriptFile($sFilename)
791 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
793 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
794 if (!$this->sVerbose) {
797 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
798 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
800 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
801 $sCMD .= ' -U '.$this->aDSNInfo['username'];
804 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
805 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
808 if (preg_match('/\\.gz$/', $sFilename)) {
809 $aDescriptors = array(
810 0 => array('pipe', 'r'),
811 1 => array('pipe', 'w'),
812 2 => array('file', '/dev/null', 'a')
814 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
815 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
816 $aReadPipe = $ahGzipPipes[1];
817 fclose($ahGzipPipes[0]);
819 $sCMD .= ' -f '.$sFilename;
820 $aReadPipe = array('pipe', 'r');
822 $aDescriptors = array(
824 1 => array('pipe', 'w'),
825 2 => array('file', '/dev/null', 'a')
828 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
829 if (!is_resource($hProcess)) fail('unable to start pgsql');
830 // TODO: error checking
831 while (!feof($ahPipes[1])) {
832 echo fread($ahPipes[1], 4096);
835 $iReturn = proc_close($hProcess);
837 fail("pgsql returned with error code ($iReturn)");
840 fclose($ahGzipPipes[1]);
841 proc_close($hGzipProcess);
845 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
848 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
850 $sSql = str_replace($sTemplate, '', $sSql);