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(array $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);
26 if ($this->iInstances < 1) {
27 $this->iInstances = 1;
28 warn('resetting threads to '.$this->iInstances);
31 // Assume we can steal all the cache memory in the box (unless told otherwise)
32 if (isset($aCMDResult['osm2pgsql-cache'])) {
33 $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
35 $this->iCacheMemory = getCacheMemoryMB();
38 $this->sModulePath = CONST_Database_Module_Path;
39 info('module path: ' . $this->sModulePath);
41 // prepares DB for import or update, sets the Data Source Name
42 $this->aDSNInfo = \DB::parseDSN(CONST_Database_DSN);
43 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
45 // setting member variables based on command line options stored in $aCMDResult
46 $this->sVerbose = $aCMDResult['verbose'];
48 //setting default values which are not set by the update.php array
49 if (isset($aCMDResult['ignore-errors'])) {
50 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
52 $this->sIgnoreErrors = false;
54 if (isset($aCMDResult['enable-debug-statements'])) {
55 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
57 $this->bEnableDebugStatements = false;
59 if (isset($aCMDResult['no-partitions'])) {
60 $this->bNoPartitions = $aCMDResult['no-partitions'];
62 $this->bNoPartitions = false;
64 if (isset($aCMDResult['enable-diff-updates'])) {
65 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
67 $this->bEnableDiffUpdates = false;
71 public function createDB()
74 $sDB = \DB::connect(CONST_Database_DSN, false);
75 if (!\PEAR::isError($sDB)) {
76 fail('database already exists ('.CONST_Database_DSN.')');
79 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
80 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
81 $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
84 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
85 $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
89 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
90 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
93 $result = runWithEnv($sCreateDBCmd, $aProcEnv);
94 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
97 public function setupDB()
100 $this->oDB =& getDB();
102 $fPostgresVersion = getPostgresVersion($this->oDB);
103 echo 'Postgres version found: '.$fPostgresVersion."\n";
105 if ($fPostgresVersion < 9.1) {
106 fail('Minimum supported version of Postgresql is 9.1.');
109 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
110 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
112 // For extratags and namedetails the hstore_to_json converter is
113 // needed which is only available from Postgresql 9.3+. For older
114 // versions add a dummy function that returns nothing.
115 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
117 if ($iNumFunc == 0) {
118 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
119 warn('Postgresql is too old. extratags and namedetails API not available.');
123 $fPostgisVersion = getPostgisVersion($this->oDB);
124 echo 'Postgis version found: '.$fPostgisVersion."\n";
126 if ($fPostgisVersion < 2.1) {
127 // Functions were renamed in 2.1 and throw an annoying deprecation warning
128 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
129 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
131 if ($fPostgisVersion < 2.2) {
132 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
135 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
137 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
138 echo "\n createuser ".CONST_Database_Web_User."\n\n";
142 // Try accessing the C module, so we know early if something is wrong
143 if (!checkModulePresence()) {
144 fail('error loading nominatim.so module');
147 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
148 echo 'Error: you need to download the country_osm_grid first:';
149 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
152 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
153 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
154 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
155 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
157 $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
158 if (file_exists($sPostcodeFilename)) {
159 $this->pgsqlRunScriptFile($sPostcodeFilename);
161 warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
164 if (CONST_Use_Extra_US_Postcodes) {
165 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
168 if ($this->bNoPartitions) {
169 $this->pgsqlRunScript('update country_name set partition = 0');
172 // the following will be needed by createFunctions later but
173 // is only defined in the subsequently called createTables
174 // Create dummies here that will be overwritten by the proper
175 // versions in create-tables.
176 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
177 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
180 public function importData($sOSMFile)
184 $osm2pgsql = CONST_Osm2pgsql_Binary;
185 if (!file_exists($osm2pgsql)) {
186 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
187 echo "Normally you should not need to set this manually.\n";
188 fail("osm2pgsql not found in '$osm2pgsql'");
191 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
195 if (CONST_Tablespace_Osm2pgsql_Data)
196 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
197 if (CONST_Tablespace_Osm2pgsql_Index)
198 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
199 if (CONST_Tablespace_Place_Data)
200 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
201 if (CONST_Tablespace_Place_Index)
202 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
203 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
204 $osm2pgsql .= ' -C '.$this->iCacheMemory;
205 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
206 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
207 $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
209 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
210 $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
213 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
214 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
216 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
217 runWithEnv($osm2pgsql, $aProcEnv);
218 if ($this->oDB == null) $this->oDB =& getDB();
219 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
224 public function createFunctions()
226 info('Create Functions');
228 // Try accessing the C module, so we know eif something is wrong
229 // update.php calls this function
230 if (!checkModulePresence()) {
231 fail('error loading nominatim.so module');
233 $this->createSqlFunctions();
236 public function createTables()
238 info('Create Tables');
240 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
241 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
242 $sTemplate = $this->replaceTablespace(
244 CONST_Tablespace_Address_Data,
247 $sTemplate = $this->replaceTablespace(
248 '{ts:address-index}',
249 CONST_Tablespace_Address_Index,
252 $sTemplate = $this->replaceTablespace(
254 CONST_Tablespace_Search_Data,
257 $sTemplate = $this->replaceTablespace(
259 CONST_Tablespace_Search_Index,
262 $sTemplate = $this->replaceTablespace(
264 CONST_Tablespace_Aux_Data,
267 $sTemplate = $this->replaceTablespace(
269 CONST_Tablespace_Aux_Index,
273 $this->pgsqlRunScript($sTemplate, false);
276 public function createPartitionTables()
278 info('Create Partition Tables');
280 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
281 $sTemplate = $this->replaceTablespace(
283 CONST_Tablespace_Address_Data,
287 $sTemplate = $this->replaceTablespace(
288 '{ts:address-index}',
289 CONST_Tablespace_Address_Index,
293 $sTemplate = $this->replaceTablespace(
295 CONST_Tablespace_Search_Data,
299 $sTemplate = $this->replaceTablespace(
301 CONST_Tablespace_Search_Index,
305 $sTemplate = $this->replaceTablespace(
307 CONST_Tablespace_Aux_Data,
311 $sTemplate = $this->replaceTablespace(
313 CONST_Tablespace_Aux_Index,
317 $this->pgsqlRunPartitionScript($sTemplate);
320 public function createPartitionFunctions()
322 info('Create Partition Functions');
324 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
325 $this->pgsqlRunPartitionScript($sTemplate);
328 public function importWikipediaArticles()
330 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
331 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
332 if (file_exists($sWikiArticlesFile)) {
333 info('Importing wikipedia articles');
334 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
336 warn('wikipedia article dump file not found - places will have default importance');
338 if (file_exists($sWikiRedirectsFile)) {
339 info('Importing wikipedia redirects');
340 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
342 warn('wikipedia redirect dump file not found - some place importance values may be missing');
346 public function loadData($bDisableTokenPrecalc)
348 info('Drop old Data');
350 if ($this->oDB == null) $this->oDB =& getDB();
352 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
354 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
356 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
358 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
360 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
362 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
364 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
366 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
368 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
370 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
373 $sSQL = 'select distinct partition from country_name';
374 $aPartitions = chksql($this->oDB->getCol($sSQL));
375 if (!$this->bNoPartitions) $aPartitions[] = 0;
376 foreach ($aPartitions as $sPartition) {
377 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
381 // used by getorcreate_word_id to ignore frequent partial words
382 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
383 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
384 if (!pg_query($this->oDB->connection, $sSQL)) {
385 fail(pg_last_error($this->oDB->connection));
389 // pre-create the word list
390 if (!$bDisableTokenPrecalc) {
391 info('Loading word list');
392 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
396 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
397 $aDBInstances = array();
398 $iLoadThreads = max(1, $this->iInstances - 1);
399 for ($i = 0; $i < $iLoadThreads; $i++) {
400 $aDBInstances[$i] =& getDB(true);
401 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
402 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
403 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
404 $sSQL .= ' and ST_IsValid(geometry)';
405 if ($this->sVerbose) echo "$sSQL\n";
406 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
407 fail(pg_last_error($aDBInstances[$i]->connection));
411 // last thread for interpolation lines
412 $aDBInstances[$iLoadThreads] =& getDB(true);
413 $sSQL = 'insert into location_property_osmline';
414 $sSQL .= ' (osm_id, address, linegeo)';
415 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
416 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
417 if ($this->sVerbose) echo "$sSQL\n";
418 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
419 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
423 for ($i = 0; $i <= $iLoadThreads; $i++) {
424 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
425 $resultStatus = pg_result_status($hPGresult);
426 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
427 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
428 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
429 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
430 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
431 $resultError = pg_result_error($hPGresult);
432 echo '-- error text ' . $i . ': ' . $resultError . "\n";
438 fail('SQL errors loading placex and/or location_property_osmline tables');
441 info('Reanalysing database');
442 $this->pgsqlRunScript('ANALYSE');
444 $sDatabaseDate = getDatabaseDate($this->oDB);
445 pg_query($this->oDB->connection, 'TRUNCATE import_status');
446 if ($sDatabaseDate === false) {
447 warn('could not determine database date.');
449 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
450 pg_query($this->oDB->connection, $sSQL);
451 echo "Latest data imported from $sDatabaseDate.\n";
455 public function importTigerData()
457 info('Import Tiger data');
459 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
460 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
461 $sTemplate = $this->replaceTablespace(
463 CONST_Tablespace_Aux_Data,
466 $sTemplate = $this->replaceTablespace(
468 CONST_Tablespace_Aux_Index,
471 $this->pgsqlRunScript($sTemplate, false);
473 $aDBInstances = array();
474 for ($i = 0; $i < $this->iInstances; $i++) {
475 $aDBInstances[$i] =& getDB(true);
478 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
480 $hFile = fopen($sFile, 'r');
481 $sSQL = fgets($hFile, 100000);
484 for ($i = 0; $i < $this->iInstances; $i++) {
485 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
486 while (pg_get_result($aDBInstances[$i]->connection));
487 $sSQL = fgets($hFile, 100000);
489 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
491 if ($iLines == 1000) {
504 for ($i = 0; $i < $this->iInstances; $i++) {
505 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
512 info('Creating indexes on Tiger data');
513 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
514 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
515 $sTemplate = $this->replaceTablespace(
517 CONST_Tablespace_Aux_Data,
520 $sTemplate = $this->replaceTablespace(
522 CONST_Tablespace_Aux_Index,
525 $this->pgsqlRunScript($sTemplate, false);
528 public function calculatePostcodes($bCMDResultAll)
530 info('Calculate Postcodes');
531 if ($this->oDB == null) $this->oDB =& getDB();
532 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
533 fail(pg_last_error($this->oDB->connection));
537 $sSQL = 'INSERT INTO location_postcode';
538 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
539 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
540 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
541 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
542 $sSQL .= ' FROM placex';
543 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
544 $sSQL .= ' AND geometry IS NOT null';
545 $sSQL .= ' GROUP BY country_code, pc';
547 if (!pg_query($this->oDB->connection, $sSQL)) {
548 fail(pg_last_error($this->oDB->connection));
551 if (CONST_Use_Extra_US_Postcodes) {
552 // only add postcodes that are not yet available in OSM
553 $sSQL = 'INSERT INTO location_postcode';
554 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
555 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
556 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
557 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
558 $sSQL .= ' (SELECT postcode FROM location_postcode';
559 $sSQL .= " WHERE country_code = 'us')";
560 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
563 // add missing postcodes for GB (if available)
564 $sSQL = 'INSERT INTO location_postcode';
565 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
566 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
567 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
568 $sSQL .= ' (SELECT postcode FROM location_postcode';
569 $sSQL .= " WHERE country_code = 'gb')";
570 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
572 if (!$bCMDResultAll) {
573 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
574 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
575 if (!pg_query($this->oDB->connection, $sSQL)) {
576 fail(pg_last_error($this->oDB->connection));
579 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
580 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
582 if (!pg_query($this->oDB->connection, $sSQL)) {
583 fail(pg_last_error($this->oDB->connection));
587 public function index($bIndexNoanalyse)
590 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
591 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
592 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
593 $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
595 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
596 $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
599 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
600 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
603 info('Index ranks 0 - 4');
604 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
606 fail('error status ' . $iStatus . ' running nominatim!');
608 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
609 info('Index ranks 5 - 25');
610 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
612 fail('error status ' . $iStatus . ' running nominatim!');
614 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
615 info('Index ranks 26 - 30');
616 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
618 fail('error status ' . $iStatus . ' running nominatim!');
620 info('Index postcodes');
621 if ($this->oDB == null) $this->oDB =& getDB();
622 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
623 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
626 public function createSearchIndices()
628 info('Create Search indices');
630 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
631 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
632 $sTemplate = $this->replaceTablespace(
633 '{ts:address-index}',
634 CONST_Tablespace_Address_Index,
637 $sTemplate = $this->replaceTablespace(
639 CONST_Tablespace_Search_Index,
642 $sTemplate = $this->replaceTablespace(
644 CONST_Tablespace_Aux_Index,
647 $this->pgsqlRunScript($sTemplate);
650 public function createCountryNames()
652 info('Create search index for default country names');
654 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
655 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
656 $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');
657 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
658 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
659 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
660 if (CONST_Languages) {
663 foreach (explode(',', CONST_Languages) as $sLang) {
664 $sSQL .= $sDelim."'name:$sLang'";
669 // all include all simple name tags
670 $sSQL .= "like 'name:%'";
673 $this->pgsqlRunScript($sSQL);
676 public function drop()
678 info('Drop tables only required for updates');
680 // The implementation is potentially a bit dangerous because it uses
681 // a positive selection of tables to keep, and deletes everything else.
682 // Including any tables that the unsuspecting user might have manually
683 // created. USE AT YOUR OWN PERIL.
684 // tables we want to keep. everything else goes.
685 $aKeepTables = array(
691 'location_property*',
703 if ($this->oDB = null) $this->oDB =& getDB();
704 $aDropTables = array();
705 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
707 foreach ($aHaveTables as $sTable) {
709 foreach ($aKeepTables as $sKeep) {
710 if (fnmatch($sKeep, $sTable)) {
715 if (!$bFound) array_push($aDropTables, $sTable);
717 foreach ($aDropTables as $sDrop) {
718 if ($this->sVerbose) echo "dropping table $sDrop\n";
719 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
720 // ignore warnings/errors as they might be caused by a table having
721 // been deleted already by CASCADE
724 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
725 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
726 unlink(CONST_Osm2pgsql_Flatnode_File);
730 private function pgsqlRunDropAndRestore($sDumpFile)
732 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
733 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
734 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
735 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
737 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
738 $sCMD .= ' -U '.$this->aDSNInfo['username'];
741 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
742 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
744 $iReturn = runWithEnv($sCMD, $aProcEnv); // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
747 private function pgsqlRunScript($sScript, $bfatal = true)
757 private function createSqlFunctions()
759 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
760 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
761 if ($this->bEnableDiffUpdates) {
762 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
764 if ($this->bEnableDebugStatements) {
765 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
767 if (CONST_Limit_Reindexing) {
768 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
770 if (!CONST_Use_US_Tiger_Data) {
771 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
773 if (!CONST_Use_Aux_Location_data) {
774 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
776 $this->pgsqlRunScript($sTemplate);
779 private function pgsqlRunPartitionScript($sTemplate)
781 if ($this->oDB == null) $this->oDB =& getDB();
783 $sSQL = 'select distinct partition from country_name';
784 $aPartitions = chksql($this->oDB->getCol($sSQL));
785 if (!$this->bNoPartitions) $aPartitions[] = 0;
787 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
788 foreach ($aMatches as $aMatch) {
790 foreach ($aPartitions as $sPartitionName) {
791 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
793 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
796 $this->pgsqlRunScript($sTemplate);
799 private function pgsqlRunScriptFile($sFilename)
801 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
803 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
804 if (!$this->sVerbose) {
807 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
808 $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
810 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
811 $sCMD .= ' -U '.$this->aDSNInfo['username'];
814 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
815 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
818 if (preg_match('/\\.gz$/', $sFilename)) {
819 $aDescriptors = array(
820 0 => array('pipe', 'r'),
821 1 => array('pipe', 'w'),
822 2 => array('file', '/dev/null', 'a')
824 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
825 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
826 $aReadPipe = $ahGzipPipes[1];
827 fclose($ahGzipPipes[0]);
829 $sCMD .= ' -f '.$sFilename;
830 $aReadPipe = array('pipe', 'r');
832 $aDescriptors = array(
834 1 => array('pipe', 'w'),
835 2 => array('file', '/dev/null', 'a')
838 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
839 if (!is_resource($hProcess)) fail('unable to start pgsql');
840 // TODO: error checking
841 while (!feof($ahPipes[1])) {
842 echo fread($ahPipes[1], 4096);
845 $iReturn = proc_close($hProcess);
847 fail("pgsql returned with error code ($iReturn)");
850 fclose($ahGzipPipes[1]);
851 proc_close($hGzipProcess);
855 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
858 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
860 $sSql = str_replace($sTemplate, '', $sSql);