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->sIgnoreErrors = $aCMDResult['ignore-errors'];
49 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
50 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
51 $this->bNoPartitions = $aCMDResult['no-partitions'];
54 public function createDB()
57 $sDB = \DB::connect(CONST_Database_DSN, false);
58 if (!\PEAR::isError($sDB)) {
59 fail('database already exists ('.CONST_Database_DSN.')');
62 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
63 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
64 $sCreateDBCmd .= ' -U ' . $this->aDSNInfo['username'];
67 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
68 $sCreateDBCmd .= ' -h ' . $this->aDSNInfo['hostspec'];
72 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
73 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
76 $result = runWithEnv($sCreateDBCmd, $aProcEnv);
77 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
80 public function setupDB()
83 $this->oDB =& getDB();
85 $fPostgresVersion = getPostgresVersion($this->oDB);
86 echo 'Postgres version found: '.$fPostgresVersion."\n";
88 if ($fPostgresVersion < 9.1) {
89 fail('Minimum supported version of Postgresql is 9.1.');
92 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
93 $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
95 // For extratags and namedetails the hstore_to_json converter is
96 // needed which is only available from Postgresql 9.3+. For older
97 // versions add a dummy function that returns nothing.
98 $iNumFunc = chksql($this->oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
100 if ($iNumFunc == 0) {
101 $this->pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
102 warn('Postgresql is too old. extratags and namedetails API not available.');
106 $fPostgisVersion = getPostgisVersion($this->oDB);
107 echo 'Postgis version found: '.$fPostgisVersion."\n";
109 if ($fPostgisVersion < 2.1) {
110 // Functions were renamed in 2.1 and throw an annoying deprecation warning
111 $this->pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
112 $this->pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
114 if ($fPostgisVersion < 2.2) {
115 $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
118 $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
120 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
121 echo "\n createuser ".CONST_Database_Web_User."\n\n";
125 if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
126 echo 'Error: you need to download the country_osm_grid first:';
127 echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
130 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
131 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
132 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
133 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
136 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
137 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
139 warn('external UK postcode table not found.');
142 if (CONST_Use_Extra_US_Postcodes) {
143 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
146 if ($this->bNoPartitions) {
147 $this->pgsqlRunScript('update country_name set partition = 0');
150 // the following will be needed by create_functions later but
151 // is only defined in the subsequently called T
152 // Create dummies here that will be overwritten by the proper
153 // versions in create-tables.
154 $this->pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
155 $this->pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
158 public function importData($sOSMFile)
162 $osm2pgsql = CONST_Osm2pgsql_Binary;
163 if (!file_exists($osm2pgsql)) {
164 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
165 echo "Normally you should not need to set this manually.\n";
166 fail("osm2pgsql not found in '$osm2pgsql'");
171 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
172 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
175 if (CONST_Tablespace_Osm2pgsql_Data)
176 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
177 if (CONST_Tablespace_Osm2pgsql_Index)
178 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
179 if (CONST_Tablespace_Place_Data)
180 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
181 if (CONST_Tablespace_Place_Index)
182 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
183 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
184 $osm2pgsql .= ' -C '.$this->iCacheMemory;
185 $osm2pgsql .= ' -P '.$this->aDSNInfo['port'];
186 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
187 $osm2pgsql .= ' -U ' . $this->aDSNInfo['username'];
189 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
190 $osm2pgsql .= ' -H ' . $this->aDSNInfo['hostspec'];
193 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
194 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
196 $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
197 runWithEnv($osm2pgsql, $aProcEnv);
198 if ($this->oDB == null) $this->oDB =& getDB();
199 if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
204 public function createFunctions()
206 info('Create Functions');
208 $this->createSqlFunctions();
211 public function createTables()
213 info('Create Tables');
215 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
216 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
217 $sTemplate = $this->replaceTablespace(
219 CONST_Tablespace_Address_Data,
222 $sTemplate = $this->replaceTablespace(
223 '{ts:address-index}',
224 CONST_Tablespace_Address_Index,
227 $sTemplate = $this->replaceTablespace(
229 CONST_Tablespace_Search_Data,
232 $sTemplate = $this->replaceTablespace(
234 CONST_Tablespace_Search_Index,
237 $sTemplate = $this->replaceTablespace(
239 CONST_Tablespace_Aux_Data,
242 $sTemplate = $this->replaceTablespace(
244 CONST_Tablespace_Aux_Index,
248 $this->pgsqlRunScript($sTemplate, false);
251 public function createPartitionTables()
253 info('Create Partition Tables');
255 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
256 $sTemplate = $this->replaceTablespace(
258 CONST_Tablespace_Address_Data,
262 $sTemplate = $this->replaceTablespace(
263 '{ts:address-index}',
264 CONST_Tablespace_Address_Index,
268 $sTemplate = $this->replaceTablespace(
270 CONST_Tablespace_Search_Data,
274 $sTemplate = $this->replaceTablespace(
276 CONST_Tablespace_Search_Index,
280 $sTemplate = $this->replaceTablespace(
282 CONST_Tablespace_Aux_Data,
286 $sTemplate = $this->replaceTablespace(
288 CONST_Tablespace_Aux_Index,
292 $this->pgsqlRunPartitionScript($sTemplate);
295 public function createPartitionFunctions()
297 info('Create Partition Functions');
299 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
300 $this->pgsqlRunPartitionScript($sTemplate);
303 public function importWikipediaArticles()
305 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
306 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
307 if (file_exists($sWikiArticlesFile)) {
308 info('Importing wikipedia articles');
309 $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
311 warn('wikipedia article dump file not found - places will have default importance');
313 if (file_exists($sWikiRedirectsFile)) {
314 info('Importing wikipedia redirects');
315 $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
317 warn('wikipedia redirect dump file not found - some place importance values may be missing');
319 echo ' finish wikipedia';
322 public function loadData($bDisableTokenPrecalc)
324 info('Drop old Data');
326 if ($this->oDB == null) $this->oDB =& getDB();
328 if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
330 if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
332 if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
334 if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
336 if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
338 if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
340 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
342 if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
344 if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
346 if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
349 $sSQL = 'select distinct partition from country_name';
350 $aPartitions = chksql($this->oDB->getCol($sSQL));
351 if (!$this->bNoPartitions) $aPartitions[] = 0;
352 foreach ($aPartitions as $sPartition) {
353 if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
357 // used by getorcreate_word_id to ignore frequent partial words
358 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
359 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
360 if (!pg_query($this->oDB->connection, $sSQL)) {
361 fail(pg_last_error($this->oDB->connection));
365 // pre-create the word list
366 if (!$bDisableTokenPrecalc) {
367 info('Loading word list');
368 $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
372 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
373 $aDBInstances = array();
374 $iLoadThreads = max(1, $this->iInstances - 1);
375 for ($i = 0; $i < $iLoadThreads; $i++) {
376 $aDBInstances[$i] =& getDB(true);
377 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
378 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
379 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
380 $sSQL .= ' and ST_IsValid(geometry)';
381 if ($this->sVerbose) echo "$sSQL\n";
382 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
383 fail(pg_last_error($aDBInstances[$i]->connection));
387 // last thread for interpolation lines
388 $aDBInstances[$iLoadThreads] =& getDB(true);
389 $sSQL = 'insert into location_property_osmline';
390 $sSQL .= ' (osm_id, address, linegeo)';
391 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
392 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
393 if ($this->sVerbose) echo "$sSQL\n";
394 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
395 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
399 for ($i = 0; $i <= $iLoadThreads; $i++) {
400 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
401 $resultStatus = pg_result_status($hPGresult);
402 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
403 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
404 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
405 echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
406 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
407 $resultError = pg_result_error($hPGresult);
408 echo '-- error text ' . $i . ': ' . $resultError . "\n";
414 fail('SQL errors loading placex and/or location_property_osmline tables');
417 info('Reanalysing database');
418 $this->pgsqlRunScript('ANALYSE');
420 $sDatabaseDate = getDatabaseDate($this->oDB);
421 pg_query($this->oDB->connection, 'TRUNCATE import_status');
422 if ($sDatabaseDate === false) {
423 warn('could not determine database date.');
425 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
426 pg_query($this->oDB->connection, $sSQL);
427 echo "Latest data imported from $sDatabaseDate.\n";
431 public function importTigerData()
433 info('Import Tiger data');
435 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
436 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
437 $sTemplate = $this->replaceTablespace(
439 CONST_Tablespace_Aux_Data,
442 $sTemplate = $this->replaceTablespace(
444 CONST_Tablespace_Aux_Index,
447 $this->pgsqlRunScript($sTemplate, false);
449 $aDBInstances = array();
450 for ($i = 0; $i < $this->iInstances; $i++) {
451 $aDBInstances[$i] =& getDB(true);
454 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
456 $hFile = fopen($sFile, 'r');
457 $sSQL = fgets($hFile, 100000);
460 for ($i = 0; $i < $this->iInstances; $i++) {
461 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
462 while (pg_get_result($aDBInstances[$i]->connection));
463 $sSQL = fgets($hFile, 100000);
465 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
467 if ($iLines == 1000) {
480 for ($i = 0; $i < $this->iInstances; $i++) {
481 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
488 info('Creating indexes on Tiger data');
489 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
490 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
491 $sTemplate = $this->replaceTablespace(
493 CONST_Tablespace_Aux_Data,
496 $sTemplate = $this->replaceTablespace(
498 CONST_Tablespace_Aux_Index,
501 $this->pgsqlRunScript($sTemplate, false);
504 public function calculatePostcodes($bCMDResultAll)
506 info('Calculate Postcodes');
507 if ($this->oDB == null) $this->oDB =& getDB();
508 if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
509 fail(pg_last_error($this->oDB->connection));
513 $sSQL = 'INSERT INTO location_postcode';
514 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
515 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
516 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
517 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
518 $sSQL .= ' FROM placex';
519 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
520 $sSQL .= ' AND geometry IS NOT null';
521 $sSQL .= ' GROUP BY country_code, pc';
523 if (!pg_query($this->oDB->connection, $sSQL)) {
524 fail(pg_last_error($this->oDB->connection));
527 if (CONST_Use_Extra_US_Postcodes) {
528 // only add postcodes that are not yet available in OSM
529 $sSQL = 'INSERT INTO location_postcode';
530 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
531 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
532 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
533 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
534 $sSQL .= ' (SELECT postcode FROM location_postcode';
535 $sSQL .= " WHERE country_code = 'us')";
536 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
539 // add missing postcodes for GB (if available)
540 $sSQL = 'INSERT INTO location_postcode';
541 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
542 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
543 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
544 $sSQL .= ' (SELECT postcode FROM location_postcode';
545 $sSQL .= " WHERE country_code = 'gb')";
546 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
548 if (!$bCMDResultAll) {
549 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
550 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
551 if (!pg_query($this->oDB->connection, $sSQL)) {
552 fail(pg_last_error($this->oDB->connection));
555 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
556 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
558 if (!pg_query($this->oDB->connection, $sSQL)) {
559 fail(pg_last_error($this->oDB->connection));
563 public function index($bIndexNoanalyse)
566 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
567 .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
568 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
569 $sBaseCmd .= ' -H ' . $this->aDSNInfo['hostspec'];
571 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
572 $sBaseCmd .= ' -U ' . $this->aDSNInfo['username'];
575 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
576 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
579 info('Index ranks 0 - 4');
580 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
582 fail('error status ' . $iStatus . ' running nominatim!');
584 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
585 info('Index ranks 5 - 25');
586 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
588 fail('error status ' . $iStatus . ' running nominatim!');
590 if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
591 info('Index ranks 26 - 30');
592 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
594 fail('error status ' . $iStatus . ' running nominatim!');
596 info('Index postcodes');
597 if ($this->oDB == null) $this->oDB =& getDB();
598 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
599 if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
602 public function createSearchIndices()
604 info('Create Search indices');
606 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
607 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
608 $sTemplate = $this->replaceTablespace(
609 '{ts:address-index}',
610 CONST_Tablespace_Address_Index,
613 $sTemplate = $this->replaceTablespace(
615 CONST_Tablespace_Search_Index,
618 $sTemplate = $this->replaceTablespace(
620 CONST_Tablespace_Aux_Index,
623 $this->pgsqlRunScript($sTemplate);
626 public function createCountryNames()
628 info('Create search index for default country names');
630 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
631 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
632 $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');
633 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
634 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
635 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
636 if (CONST_Languages) {
639 foreach (explode(',', CONST_Languages) as $sLang) {
640 $sSQL .= $sDelim."'name:$sLang'";
645 // all include all simple name tags
646 $sSQL .= "like 'name:%'";
649 $this->pgsqlRunScript($sSQL);
652 public function drop()
654 info('Drop tables only required for updates');
656 // The implementation is potentially a bit dangerous because it uses
657 // a positive selection of tables to keep, and deletes everything else.
658 // Including any tables that the unsuspecting user might have manually
659 // created. USE AT YOUR OWN PERIL.
660 // tables we want to keep. everything else goes.
661 $aKeepTables = array(
667 'location_property*',
679 if ($this->oDB = null) $this->oDB =& getDB();
680 $aDropTables = array();
681 $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
683 foreach ($aHaveTables as $sTable) {
685 foreach ($aKeepTables as $sKeep) {
686 if (fnmatch($sKeep, $sTable)) {
691 if (!$bFound) array_push($aDropTables, $sTable);
693 foreach ($aDropTables as $sDrop) {
694 if ($this->sVerbose) echo "dropping table $sDrop\n";
695 @pg_query($this->oDB->connection, "DROP TABLE $sDrop CASCADE");
696 // ignore warnings/errors as they might be caused by a table having
697 // been deleted already by CASCADE
700 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
701 if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
702 unlink(CONST_Osm2pgsql_Flatnode_File);
706 private function pgsqlRunDropAndRestore($sDumpFile)
708 if (!isset($this->aDSNInfo['port']) || !$this->aDSNInfo['port']) $this->aDSNInfo['port'] = 5432;
709 $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
710 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
711 $sCMD .= ' -h ' . $this->aDSNInfo['hostspec'];
713 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
714 $sCMD .= ' -U ' . $this->aDSNInfo['username'];
717 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
718 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
720 $iReturn = runWithEnv($sCMD, $aProcEnv); // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
723 private function pgsqlRunScript($sScript, $bfatal = true)
733 private function createSqlFunctions()
735 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
736 $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
737 if ($this->bEnableDiffUpdates) {
738 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
740 if ($this->bEnableDebugStatements) {
741 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
743 if (CONST_Limit_Reindexing) {
744 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
746 if (!CONST_Use_US_Tiger_Data) {
747 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
749 if (!CONST_Use_Aux_Location_data) {
750 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
752 $this->pgsqlRunScript($sTemplate);
755 private function pgsqlRunPartitionScript($sTemplate)
757 if ($this->oDB == null) $this->oDB =& getDB();
759 $sSQL = 'select distinct partition from country_name';
760 $aPartitions = chksql($this->oDB->getCol($sSQL));
761 if (!$this->bNoPartitions) $aPartitions[] = 0;
763 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
764 foreach ($aMatches as $aMatch) {
766 foreach ($aPartitions as $sPartitionName) {
767 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
769 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
772 $this->pgsqlRunScript($sTemplate);
775 private function pgsqlRunScriptFile($sFilename)
777 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
779 $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
780 if (!$this->sVerbose) {
783 if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
784 $sCMD .= ' -h ' . $this->aDSNInfo['hostspec'];
786 if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
787 $sCMD .= ' -U ' . $this->aDSNInfo['username'];
790 if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
791 $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
794 if (preg_match('/\\.gz$/', $sFilename)) {
795 $aDescriptors = array(
796 0 => array('pipe', 'r'),
797 1 => array('pipe', 'w'),
798 2 => array('file', '/dev/null', 'a')
800 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
801 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
802 $aReadPipe = $ahGzipPipes[1];
803 fclose($ahGzipPipes[0]);
805 $sCMD .= ' -f '.$sFilename;
806 $aReadPipe = array('pipe', 'r');
808 $aDescriptors = array(
810 1 => array('pipe', 'w'),
811 2 => array('file', '/dev/null', 'a')
814 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
815 if (!is_resource($hProcess)) fail('unable to start pgsql');
816 // TODO: error checking
817 while (!feof($ahPipes[1])) {
818 echo fread($ahPipes[1], 4096);
821 $iReturn = proc_close($hProcess);
823 fail("pgsql returned with error code ($iReturn)");
826 fclose($ahGzipPipes[1]);
827 proc_close($hGzipProcess);
831 private function replaceTablespace($sTemplate, $sTablespace, $sSql)
834 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
836 $sSql = str_replace($sTemplate, '', $sSql);