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 // Try accessing the C module, so we know early if something is wrong
140 if (!checkModulePresence()) {
141 fail('error loading nominatim.so module');
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_BasePath.'/data/country_naturalearthdata.sql');
151 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
152 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
155 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
156 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
158 warn('external UK postcode table not found.');
161 if (CONST_Use_Extra_US_Postcodes) {
162 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
165 if ($this->bNoPartitions) {
166 $this->pgsqlRunScript('update country_name set partition = 0');
169 // the following will be needed by create_functions later but
170 // is only defined in the subsequently called T
171 // Create dummies here that will be overwritten by the proper
172 // versions in create-tables.
173 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
174 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
177 public function importData($sOSMFile)
181 $osm2pgsql = CONST_Osm2pgsql_Binary;
182 if (!file_exists($osm2pgsql)) {
183 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
184 echo "Normally you should not need to set this manually.\n";
185 fail("osm2pgsql not found in '$osm2pgsql'");
190 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
191 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
194 if (CONST_Tablespace_Osm2pgsql_Data)
195 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
196 if (CONST_Tablespace_Osm2pgsql_Index)
197 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
198 if (CONST_Tablespace_Place_Data)
199 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
200 if (CONST_Tablespace_Place_Index)
201 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
202 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
203 $osm2pgsql .= ' -C '.$this->iCacheMemory;
204 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
205 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
206 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
208 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
209 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
212 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
213 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
215 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
216 runWithEnv($osm2pgsql, $aProcEnv);
217 if ($this->oDB == null) $this->oDB =& getDB();
218 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
223 public function createFunctions()
225 info('Create Functions');
227 // Try accessing the C module, so we know eif something is wrong
228 // update.php calls this function
229 if (!checkModulePresence()) {
230 fail('error loading nominatim.so module');
232 $this->createSqlFunctions();
235 public function createTables()
237 info('Create Tables');
239 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
240 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
241 $sTemplate = $this->replaceTablespace(
243 CONST_Tablespace_Address_Data,
246 $sTemplate = $this->replaceTablespace(
247 '{ts:address-index}',
248 CONST_Tablespace_Address_Index,
251 $sTemplate = $this->replaceTablespace(
253 CONST_Tablespace_Search_Data,
256 $sTemplate = $this->replaceTablespace(
258 CONST_Tablespace_Search_Index,
261 $sTemplate = $this->replaceTablespace(
263 CONST_Tablespace_Aux_Data,
266 $sTemplate = $this->replaceTablespace(
268 CONST_Tablespace_Aux_Index,
272 $this->pgsqlRunScript($sTemplate, false);
275 public function createPartitionTables()
277 info('Create Partition Tables');
279 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
280 $sTemplate = $this->replaceTablespace(
282 CONST_Tablespace_Address_Data,
286 $sTemplate = $this->replaceTablespace(
287 '{ts:address-index}',
288 CONST_Tablespace_Address_Index,
292 $sTemplate = $this->replaceTablespace(
294 CONST_Tablespace_Search_Data,
298 $sTemplate = $this->replaceTablespace(
300 CONST_Tablespace_Search_Index,
304 $sTemplate = $this->replaceTablespace(
306 CONST_Tablespace_Aux_Data,
310 $sTemplate = $this->replaceTablespace(
312 CONST_Tablespace_Aux_Index,
316 $this->pgsqlRunPartitionScript($sTemplate);
319 public function createPartitionFunctions()
321 info('Create Partition Functions');
323 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
324 $this->pgsqlRunPartitionScript($sTemplate);
327 public function importWikipediaArticles()
329 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
330 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
331 if (file_exists($sWikiArticlesFile)) {
332 info('Importing wikipedia articles');
333 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
335 warn('wikipedia article dump file not found - places will have default importance');
337 if (file_exists($sWikiRedirectsFile)) {
338 info('Importing wikipedia redirects');
339 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
341 warn('wikipedia redirect dump file not found - some place importance values may be missing');
345 public function loadData($bDisableTokenPrecalc)
347 info('Drop old Data');
349 if ($this->oDB == null) $this->oDB =& getDB();
351 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
353 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
355 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
357 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
359 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
361 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
363 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
365 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
367 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
369 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
372 $sSQL = 'select distinct partition from country_name';
373 $aPartitions = chksql($this->oDB->getCol($sSQL));
374 if (!$this->bNoPartitions) $aPartitions[] = 0;
375 foreach ($aPartitions as $sPartition) {
376 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
380 // used by getorcreate_word_id to ignore frequent partial words
381 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
382 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
383 if (!pg_query($this->oDB->connection, $sSQL)) {
384 fail(pg_last_error($this->oDB->connection));
388 // pre-create the word list
389 if (!$bDisableTokenPrecalc) {
390 info('Loading word list');
391 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
395 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
396 $aDBInstances = array();
397 $iLoadThreads = max(1, $this->iInstances - 1);
398 for ($i = 0; $i < $iLoadThreads; $i++) {
399 $aDBInstances[$i] =& getDB(true);
400 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
401 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
402 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
403 $sSQL .= ' and ST_IsValid(geometry)';
404 if ($this->sVerbose) echo "$sSQL\n";
405 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
406 fail(pg_last_error($aDBInstances[$i]->connection));
410 // last thread for interpolation lines
411 $aDBInstances[$iLoadThreads] =& getDB(true);
412 $sSQL = 'insert into location_property_osmline';
413 $sSQL .= ' (osm_id, address, linegeo)';
414 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
415 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
416 if ($this->sVerbose) echo "$sSQL\n";
417 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
418 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
422 for ($i = 0; $i <= $iLoadThreads; $i++) {
423 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
424 $resultStatus = pg_result_status($hPGresult);
425 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
426 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
427 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
428 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
429 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
430 $resultError = pg_result_error($hPGresult);
431 echo '-- error text ' . $i . ': ' . $resultError . "\n";
437 fail('SQL errors loading placex and/or location_property_osmline tables');
440 info('Reanalysing database');
441 $this->pgsqlRunScript('ANALYSE');
443 $sDatabaseDate = getDatabaseDate($this->oDB);
444 pg_query($this->oDB->connection, 'TRUNCATE import_status');
445 if ($sDatabaseDate === false) {
446 warn('could not determine database date.');
448 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
449 pg_query($this->oDB->connection, $sSQL);
450 echo "Latest data imported from $sDatabaseDate.\n";
454 public function importTigerData()
456 info('Import Tiger data');
458 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
459 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
460 $sTemplate = $this->replaceTablespace(
462 CONST_Tablespace_Aux_Data,
465 $sTemplate = $this->replaceTablespace(
467 CONST_Tablespace_Aux_Index,
470 $this->pgsqlRunScript($sTemplate, false);
472 $aDBInstances = array();
473 for ($i = 0; $i < $this->iInstances; $i++) {
474 $aDBInstances[$i] =& getDB(true);
477 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
479 $hFile = fopen($sFile, 'r');
480 $sSQL = fgets($hFile, 100000);
483 for ($i = 0; $i < $this->iInstances; $i++) {
484 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
485 while (pg_get_result($aDBInstances[$i]->connection));
486 $sSQL = fgets($hFile, 100000);
488 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
490 if ($iLines == 1000) {
503 for ($i = 0; $i < $this->iInstances; $i++) {
504 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
511 info('Creating indexes on Tiger data');
512 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
513 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
514 $sTemplate = $this->replaceTablespace(
516 CONST_Tablespace_Aux_Data,
519 $sTemplate = $this->replaceTablespace(
521 CONST_Tablespace_Aux_Index,
524 $this->pgsqlRunScript($sTemplate, false);
527 public function calculatePostcodes($bCMDResultAll)
529 info('Calculate Postcodes');
530 if ($this->oDB == null) $this->oDB =& getDB();
531 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
532 fail(pg_last_error($this->oDB->connection));
536 $sSQL = 'INSERT INTO location_postcode';
537 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
538 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
539 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
540 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
541 $sSQL .= ' FROM placex';
542 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
543 $sSQL .= ' AND geometry IS NOT null';
544 $sSQL .= ' GROUP BY country_code, pc';
546 if (!pg_query($this->oDB->connection, $sSQL)) {
547 fail(pg_last_error($this->oDB->connection));
550 if (CONST_Use_Extra_US_Postcodes) {
551 // only add postcodes that are not yet available in OSM
552 $sSQL = 'INSERT INTO location_postcode';
553 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
554 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
555 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
556 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
557 $sSQL .= ' (SELECT postcode FROM location_postcode';
558 $sSQL .= " WHERE country_code = 'us')";
559 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
562 // add missing postcodes for GB (if available)
563 $sSQL = 'INSERT INTO location_postcode';
564 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
565 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
566 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
567 $sSQL .= ' (SELECT postcode FROM location_postcode';
568 $sSQL .= " WHERE country_code = 'gb')";
569 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
571 if (!$bCMDResultAll) {
572 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
573 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
574 if (!pg_query($this->oDB->connection, $sSQL)) {
575 fail(pg_last_error($this->oDB->connection));
578 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
579 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
581 if (!pg_query($this->oDB->connection, $sSQL)) {
582 fail(pg_last_error($this->oDB->connection));
586 public function index($bIndexNoanalyse)
589 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
590 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
591 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
592 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
594 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
595 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
598 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
599 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
602 info('Index ranks 0 - 4');
603 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
605 fail('error status ' . $iStatus . ' running nominatim!');
607 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
608 info('Index ranks 5 - 25');
609 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
611 fail('error status ' . $iStatus . ' running nominatim!');
613 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
614 info('Index ranks 26 - 30');
615 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
617 fail('error status ' . $iStatus . ' running nominatim!');
619 info('Index postcodes');
620 if ($this->oDB == null) $this->oDB =& getDB();
621 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
622 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
625 public function createSearchIndices()
627 info('Create Search indices');
629 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
630 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
631 $sTemplate = $this->replaceTablespace(
632 '{ts:address-index}',
633 CONST_Tablespace_Address_Index,
636 $sTemplate = $this->replaceTablespace(
638 CONST_Tablespace_Search_Index,
641 $sTemplate = $this->replaceTablespace(
643 CONST_Tablespace_Aux_Index,
646 $this->pgsqlRunScript($sTemplate);
649 public function createCountryNames()
651 info('Create search index for default country names');
653 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
654 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
655 $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');
656 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
657 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
658 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
659 if (CONST_Languages) {
662 foreach (explode(',', CONST_Languages) as $sLang) {
663 $sSQL .= $sDelim."'name:$sLang'";
668 // all include all simple name tags
669 $sSQL .= "like 'name:%'";
672 $this->pgsqlRunScript($sSQL);
675 public function drop()
677 info('Drop tables only required for updates');
679 // The implementation is potentially a bit dangerous because it uses
680 // a positive selection of tables to keep, and deletes everything else.
681 // Including any tables that the unsuspecting user might have manually
682 // created. USE AT YOUR OWN PERIL.
683 // tables we want to keep. everything else goes.
684 $aKeepTables = array(
690 'location_property*',
702 if ($this->oDB = null) $this->oDB =& getDB();
703 $aDropTables = array();
704 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
706 foreach ($aHaveTables as $sTable) {
708 foreach ($aKeepTables as $sKeep) {
709 if (fnmatch($sKeep, $sTable)) {
714 if (!$bFound) array_push($aDropTables, $sTable);
716 foreach ($aDropTables as $sDrop) {
717 if ($this->sVerbose) echo "dropping table $sDrop\n";
718 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
719 // ignore warnings/errors as they might be caused by a table having
720 // been deleted already by CASCADE
723 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
724 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
725 unlink(CONST_Osm2pgsql_Flatnode_File);
729 private function pgsqlRunDropAndRestore($sDumpFile)
731 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
732 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
733 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
734 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
736 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
737 $sCMD .= ' -U '.$this->aDSNInfo['username'];
740 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
741 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
743 $iReturn = runWithEnv($sCMD, $aProcEnv); // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
746 private function pgsqlRunScript($sScript, $bfatal = true)
756 private function createSqlFunctions()
758 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
759 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
760 if ($this->bEnableDiffUpdates) {
761 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
763 if ($this->bEnableDebugStatements) {
764 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
766 if (CONST_Limit_Reindexing) {
767 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
769 if (!CONST_Use_US_Tiger_Data) {
770 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
772 if (!CONST_Use_Aux_Location_data) {
773 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
775 $this->pgsqlRunScript($sTemplate);
778 private function pgsqlRunPartitionScript($sTemplate)
780 if ($this->oDB == null) $this->oDB =& getDB();
782 $sSQL = 'select distinct partition from country_name';
783 $aPartitions = chksql($this->oDB->getCol($sSQL));
784 if (!$this->bNoPartitions) $aPartitions[] = 0;
786 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
787 foreach ($aMatches as $aMatch) {
789 foreach ($aPartitions as $sPartitionName) {
790 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
792 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
795 $this->pgsqlRunScript($sTemplate);
798 private function pgsqlRunScriptFile($sFilename)
800 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
802 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
803 if (!$this->sVerbose) {
806 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
807 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
809 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
810 $sCMD .= ' -U '.$this->aDSNInfo['username'];
813 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
814 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
817 if (preg_match('/\\.gz$/', $sFilename)) {
818 $aDescriptors = array(
819 0 => array('pipe', 'r'),
820 1 => array('pipe', 'w'),
821 2 => array('file', '/dev/null', 'a')
823 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
824 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
825 $aReadPipe = $ahGzipPipes[1];
826 fclose($ahGzipPipes[0]);
828 $sCMD .= ' -f '.$sFilename;
829 $aReadPipe = array('pipe', 'r');
831 $aDescriptors = array(
833 1 => array('pipe', 'w'),
834 2 => array('file', '/dev/null', 'a')
837 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
838 if (!is_resource($hProcess)) fail('unable to start pgsql');
839 // TODO: error checking
840 while (!feof($ahPipes[1])) {
841 echo fread($ahPipes[1], 4096);
844 $iReturn = proc_close($hProcess);
846 fail("pgsql returned with error code ($iReturn)");
849 fclose($ahGzipPipes[1]);
850 proc_close($hGzipProcess);
854 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
857 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
859 $sSql = str_replace($sTemplate, '', $sSql);