3 function checkInFile($aCMDResult)
5 if ($aCMDResult['import-data'] || $aCMDResult['all']) {
6 if (!isset($aCMDResult['osm-file'])) {
7 fail('missing --osm-file for data import');
10 if (!file_exists($aCMDResult['osm-file'])) {
11 fail('the path supplied to --osm-file does not exist');
14 if (!is_readable($aCMDResult['osm-file'])) {
15 fail('osm-file "'.$aCMDResult['osm-file'].'" not readable');
20 function prepSystem($aCMDResult)
22 // by default, use all but one processor, but never more than 15.
23 $iInstances = isset($aCMDResult['threads'])
24 ? $aCMDResult['threads']
25 : (min(16, getProcessorCount()) - 1);
27 if ($iInstances < 1) {
29 warn("resetting threads to $iInstances");
32 // Assume we can steal all the cache memory in the box (unless told otherwise)
33 if (isset($aCMDResult['osm2pgsql-cache'])) {
34 $iCacheMemory = $aCMDResult['osm2pgsql-cache'];
36 $iCacheMemory = getCacheMemoryMB();
39 $sModulePath = CONST_Database_Module_Path;
40 info('module path: ' . $sModulePath);
42 return array($iCacheMemory,$iInstances);
45 function prepDB($aCMDResult)
47 $sModulePath = CONST_Database_Module_Path;
48 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
49 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
51 if ($aCMDResult['create-db'] || $aCMDResult['all']) {
53 $bDidSomething = true;
54 $oDB = DB::connect(CONST_Database_DSN, false);
55 if (!PEAR::isError($oDB)) {
56 fail('database already exists ('.CONST_Database_DSN.')');
59 $sCreateDBCmd = 'createdb -E UTF-8 -p '.$aDSNInfo['port'].' '.$aDSNInfo['database'];
60 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
61 $sCreateDBCmd .= ' -U ' . $aDSNInfo['username'];
63 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
64 $sCreateDBCmd .= ' -h ' . $aDSNInfo['hostspec'];
68 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
69 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
72 $result = runWithEnv($sCreateDBCmd, $aProcEnv);
73 if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
76 if ($aCMDResult['setup-db'] || $aCMDResult['all']) {
78 $bDidSomething = true;
82 $fPostgresVersion = getPostgresVersion($oDB);
83 echo 'Postgres version found: '.$fPostgresVersion."\n";
85 if ($fPostgresVersion < 9.1) {
86 fail('Minimum supported version of Postgresql is 9.1.');
89 pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
90 pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
92 // For extratags and namedetails the hstore_to_json converter is
93 // needed which is only available from Postgresql 9.3+. For older
94 // versions add a dummy function that returns nothing.
95 $iNumFunc = chksql($oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
98 pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
99 warn('Postgresql is too old. extratags and namedetails API not available.');
102 $fPostgisVersion = getPostgisVersion($oDB);
103 echo 'Postgis version found: '.$fPostgisVersion."\n";
105 if ($fPostgisVersion < 2.1) {
106 // Functions were renamed in 2.1 and throw an annoying deprecation warning
107 pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
108 pgsqlRunScript('ALTER FUNCTION ST_Line_Locate_Point(geometry, geometry) RENAME TO ST_LineLocatePoint');
110 if ($fPostgisVersion < 2.2) {
111 pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
114 $i = chksql($oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
116 echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
117 echo "\n createuser ".CONST_Database_Web_User."\n\n";
121 if (!checkModulePresence()) {
122 fail('error loading nominatim.so module');
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 pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
131 pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
132 pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql.gz');
133 pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
136 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
137 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 pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
146 if ($aCMDResult['no-partitions']) {
147 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 create_tables.
152 // Create dummies here that will be overwritten by the proper
153 // versions in create-tables.
154 pgsqlRunScript('CREATE TABLE IF NOT EXISTS place_boundingbox ()');
155 pgsqlRunScript('CREATE TYPE wikipedia_article_match AS ()', false);
160 function import_data($aCMDResult, $iCacheMemory,$aDSNInfo)
164 $osm2pgsql = CONST_Osm2pgsql_Binary;
165 if (!file_exists($osm2pgsql)) {
166 echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
167 echo "Normally you should not need to set this manually.\n";
168 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;
174 if (CONST_Tablespace_Osm2pgsql_Data)
175 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
176 if (CONST_Tablespace_Osm2pgsql_Index)
177 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
178 if (CONST_Tablespace_Place_Data)
179 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
180 if (CONST_Tablespace_Place_Index)
181 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
182 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
183 $osm2pgsql .= ' -C '.$iCacheMemory;
184 $osm2pgsql .= ' -P '.$aDSNInfo['port'];
185 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
186 $osm2pgsql .= ' -U ' . $aDSNInfo['username'];
188 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
189 $osm2pgsql .= ' -H ' . $aDSNInfo['hostspec'];
193 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
194 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
197 $osm2pgsql .= ' -d '.$aDSNInfo['database'].' '.$aCMDResult['osm-file'];
198 runWithEnv($osm2pgsql, $aProcEnv);
201 if (!$aCMDResult['ignore-errors'] && !chksql($oDB->getRow('select * from place limit 1'))) {
206 function create_functions($aCMDResult)
208 info('Create Functions');
210 if (!checkModulePresence()) {
211 fail('error loading nominatim.so module');
214 create_sql_functions($aCMDResult);
217 function create_tables($aCMDResult)
219 info('Create Tables');
221 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
222 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
223 $sTemplate = replace_tablespace(
225 CONST_Tablespace_Address_Data,
228 $sTemplate = replace_tablespace(
229 '{ts:address-index}',
230 CONST_Tablespace_Address_Index,
233 $sTemplate = replace_tablespace(
235 CONST_Tablespace_Search_Data,
238 $sTemplate = replace_tablespace(
240 CONST_Tablespace_Search_Index,
243 $sTemplate = replace_tablespace(
245 CONST_Tablespace_Aux_Data,
248 $sTemplate = replace_tablespace(
250 CONST_Tablespace_Aux_Index,
253 pgsqlRunScript($sTemplate, false);
255 // re-run the functions
256 info('Recreate Functions');
257 create_sql_functions($aCMDResult);
260 function create_partition_tables($aCMDResult)
262 info('Create Partition Tables');
264 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
265 $sTemplate = replace_tablespace(
267 CONST_Tablespace_Address_Data,
270 $sTemplate = replace_tablespace(
271 '{ts:address-index}',
272 CONST_Tablespace_Address_Index,
275 $sTemplate = replace_tablespace(
277 CONST_Tablespace_Search_Data,
280 $sTemplate = replace_tablespace(
282 CONST_Tablespace_Search_Index,
285 $sTemplate = replace_tablespace(
287 CONST_Tablespace_Aux_Data,
290 $sTemplate = replace_tablespace(
292 CONST_Tablespace_Aux_Index,
296 pgsqlRunPartitionScript($sTemplate);
299 function create_partition_functions()
301 info('Create Partition Functions');
303 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
305 pgsqlRunPartitionScript($sTemplate);
308 function import_wikipedia_articles()
310 $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
311 $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
312 if (file_exists($sWikiArticlesFile)) {
313 info('Importing wikipedia articles');
314 pgsqlRunDropAndRestore($sWikiArticlesFile);
316 warn('wikipedia article dump file not found - places will have default importance');
318 if (file_exists($sWikiRedirectsFile)) {
319 info('Importing wikipedia redirects');
320 pgsqlRunDropAndRestore($sWikiRedirectsFile);
322 warn('wikipedia redirect dump file not found - some place importance values may be missing');
326 function load_data($aCMDResult, $iInstances)
328 info('Drop old Data');
331 if (!pg_query($oDB->connection, 'TRUNCATE word')) fail(pg_last_error($oDB->connection));
333 if (!pg_query($oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($oDB->connection));
335 if (!pg_query($oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($oDB->connection));
337 if (!pg_query($oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($oDB->connection));
339 if (!pg_query($oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($oDB->connection));
341 if (!pg_query($oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($oDB->connection));
343 if (!pg_query($oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($oDB->connection));
345 if (!pg_query($oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($oDB->connection));
347 if (!pg_query($oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($oDB->connection));
349 if (!pg_query($oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($oDB->connection));
352 $sSQL = 'select distinct partition from country_name';
353 $aPartitions = chksql($oDB->getCol($sSQL));
354 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
355 foreach ($aPartitions as $sPartition) {
356 if (!pg_query($oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($oDB->connection));
360 // used by getorcreate_word_id to ignore frequent partial words
361 $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
362 $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
363 if (!pg_query($oDB->connection, $sSQL)) {
364 fail(pg_last_error($oDB->connection));
368 // pre-create the word list
369 if (!$aCMDResult['disable-token-precalc']) {
370 info('Loading word list');
371 pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
375 $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
377 $aDBInstances = array();
378 $iLoadThreads = max(1, $iInstances - 1);
379 for ($i = 0; $i < $iLoadThreads; $i++) {
380 $aDBInstances[$i] =& getDB(true);
381 $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
382 $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
383 $sSQL .= " and ST_GeometryType(geometry) = 'ST_LineString')";
384 $sSQL .= ' and ST_IsValid(geometry)';
385 if ($aCMDResult['verbose']) echo "$sSQL\n";
386 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
387 fail(pg_last_error($aDBInstances[$i]->connection));
390 // last thread for interpolation lines
391 $aDBInstances[$iLoadThreads] =& getDB(true);
392 $sSQL = 'insert into location_property_osmline';
393 $sSQL .= ' (osm_id, address, linegeo)';
394 $sSQL .= ' SELECT osm_id, address, geometry from place where ';
395 $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
396 if ($aCMDResult['verbose']) echo "$sSQL\n";
397 if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
398 fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
402 for ($i = 0; $i <= $iLoadThreads; $i++) {
403 while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
404 $resultStatus = pg_result_status($hPGresult);
405 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
406 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
407 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
408 echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
409 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
410 $resultError = pg_result_error($hPGresult);
411 echo '-- error text ' . $i . ': ' . $resultError . "\n";
417 fail('SQL errors loading placex and/or location_property_osmline tables');
420 info('Reanalysing database');
421 pgsqlRunScript('ANALYSE');
423 $sDatabaseDate = getDatabaseDate($oDB);
424 pg_query($oDB->connection, 'TRUNCATE import_status');
425 if ($sDatabaseDate === false) {
426 warn('could not determine database date.');
428 $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
429 pg_query($oDB->connection, $sSQL);
430 echo "Latest data imported from $sDatabaseDate.\n";
434 function import_tiger_data($iInstances)
436 info('Import Tiger data');
438 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
439 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
440 $sTemplate = replace_tablespace(
442 CONST_Tablespace_Aux_Data,
445 $sTemplate = replace_tablespace(
447 CONST_Tablespace_Aux_Index,
450 pgsqlRunScript($sTemplate, false);
452 $aDBInstances = array();
453 for ($i = 0; $i < $iInstances; $i++) {
454 $aDBInstances[$i] =& getDB(true);
457 foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
459 $hFile = fopen($sFile, 'r');
460 $sSQL = fgets($hFile, 100000);
464 for ($i = 0; $i < $iInstances; $i++) {
465 if (!pg_connection_busy($aDBInstances[$i]->connection)) {
466 while (pg_get_result($aDBInstances[$i]->connection));
467 $sSQL = fgets($hFile, 100000);
469 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
471 if ($iLines == 1000) {
485 for ($i = 0; $i < $iInstances; $i++) {
486 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
493 info('Creating indexes on Tiger data');
494 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
495 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
496 $sTemplate = replace_tablespace(
498 CONST_Tablespace_Aux_Data,
501 $sTemplate = replace_tablespace(
503 CONST_Tablespace_Aux_Index,
506 pgsqlRunScript($sTemplate, false);
509 function calculate_postcodes($aCMDResult)
511 info('Calculate Postcodes');
513 if (!pg_query($oDB->connection, 'TRUNCATE location_postcode')) {
514 fail(pg_last_error($oDB->connection));
517 $sSQL = 'INSERT INTO location_postcode';
518 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
519 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
520 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
521 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
522 $sSQL .= ' FROM placex';
523 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
524 $sSQL .= ' AND geometry IS NOT null';
525 $sSQL .= ' GROUP BY country_code, pc';
527 if (!pg_query($oDB->connection, $sSQL)) {
528 fail(pg_last_error($oDB->connection));
531 if (CONST_Use_Extra_US_Postcodes) {
532 // only add postcodes that are not yet available in OSM
533 $sSQL = 'INSERT INTO location_postcode';
534 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
535 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
536 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
537 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
538 $sSQL .= ' (SELECT postcode FROM location_postcode';
539 $sSQL .= " WHERE country_code = 'us')";
540 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
543 // add missing postcodes for GB (if available)
544 $sSQL = 'INSERT INTO location_postcode';
545 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
546 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
547 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
548 $sSQL .= ' (SELECT postcode FROM location_postcode';
549 $sSQL .= " WHERE country_code = 'gb')";
550 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
552 if (!$aCMDResult['all']) {
553 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
554 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
555 if (!pg_query($oDB->connection, $sSQL)) {
556 fail(pg_last_error($oDB->connection));
559 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
560 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
562 if (!pg_query($oDB->connection, $sSQL)) {
563 fail(pg_last_error($oDB->connection));
567 function osmosis_init()
569 echo "Command 'osmosis-init' no longer available, please use utils/update.php --init-updates.\n";
572 function index($aCMDResult, $aDSNInfo, $iInstances)
575 $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$iInstances.$sOutputFile;
576 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
577 $sBaseCmd .= ' -H ' . $aDSNInfo['hostspec'];
579 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
580 $sBaseCmd .= ' -U ' . $aDSNInfo['username'];
583 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
584 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
587 info('Index ranks 0 - 4');
588 $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
590 fail('error status ' . $iStatus . ' running nominatim!');
592 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
593 info('Index ranks 5 - 25');
594 $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
596 fail('error status ' . $iStatus . ' running nominatim!');
598 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
599 info('Index ranks 26 - 30');
600 $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
602 fail('error status ' . $iStatus . ' running nominatim!');
605 info('Index postcodes');
607 $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
608 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
611 function create_search_indices($aCMDResult)
613 info('Create Search indices');
615 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
616 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
617 $sTemplate = replace_tablespace(
618 '{ts:address-index}',
619 CONST_Tablespace_Address_Index,
622 $sTemplate = replace_tablespace(
624 CONST_Tablespace_Search_Index,
627 $sTemplate = replace_tablespace(
629 CONST_Tablespace_Aux_Index,
633 pgsqlRunScript($sTemplate);
636 function create_country_names()
638 info('Create search index for default country names');
640 pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
641 pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
642 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');
643 pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
645 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v), country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
646 if (CONST_Languages) {
649 foreach (explode(',', CONST_Languages) as $sLang) {
650 $sSQL .= $sDelim."'name:$sLang'";
655 // all include all simple name tags
656 $sSQL .= "like 'name:%'";
659 pgsqlRunScript($sSQL);
662 function drop($aCMDResult)
664 info('Drop tables only required for updates');
665 // The implementation is potentially a bit dangerous because it uses
666 // a positive selection of tables to keep, and deletes everything else.
667 // Including any tables that the unsuspecting user might have manually
668 // created. USE AT YOUR OWN PERIL.
671 // tables we want to keep. everything else goes.
672 $aKeepTables = array(
678 'location_property*',
691 $aDropTables = array();
692 $aHaveTables = chksql($oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
694 foreach ($aHaveTables as $sTable) {
696 foreach ($aKeepTables as $sKeep) {
697 if (fnmatch($sKeep, $sTable)) {
702 if (!$bFound) array_push($aDropTables, $sTable);
705 foreach ($aDropTables as $sDrop) {
706 if ($aCMDResult['verbose']) echo "dropping table $sDrop\n";
707 @pg_query($oDB->connection, "DROP TABLE $sDrop CASCADE");
708 // ignore warnings/errors as they might be caused by a table having
709 // been deleted already by CASCADE
712 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
713 if ($aCMDResult['verbose']) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
714 unlink(CONST_Osm2pgsql_Flatnode_File);
718 function didsomething($bDidSomething)
720 if (!$bDidSomething) {
721 showUsage($aCMDOptions, true);
723 echo "Summary of warnings:\n\n";
726 info('Setup finished.');
730 // *********************************
732 function pgsqlRunScriptFile($sFilename)
735 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
736 // Convert database DSN to psql parameters
737 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
738 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
739 $sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'];
740 if (!$aCMDResult['verbose']) {
743 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
744 $sCMD .= ' -h ' . $aDSNInfo['hostspec'];
746 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
747 $sCMD .= ' -U ' . $aDSNInfo['username'];
750 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
751 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
754 if (preg_match('/\\.gz$/', $sFilename)) {
755 $aDescriptors = array(
756 0 => array('pipe', 'r'),
757 1 => array('pipe', 'w'),
758 2 => array('file', '/dev/null', 'a')
760 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
761 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
762 $aReadPipe = $ahGzipPipes[1];
763 fclose($ahGzipPipes[0]);
765 $sCMD .= ' -f '.$sFilename;
766 $aReadPipe = array('pipe', 'r');
768 $aDescriptors = array(
770 1 => array('pipe', 'w'),
771 2 => array('file', '/dev/null', 'a')
774 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
775 if (!is_resource($hProcess)) fail('unable to start pgsql');
776 // TODO: error checking
777 while (!feof($ahPipes[1])) {
778 echo fread($ahPipes[1], 4096);
781 $iReturn = proc_close($hProcess);
783 fail("pgsql returned with error code ($iReturn)");
786 fclose($ahGzipPipes[1]);
787 proc_close($hGzipProcess);
791 function pgsqlRunScript($sScript, $bfatal = true)
797 $aCMDResult['verbose'],
798 $aCMDResult['ignore-errors']
802 function pgsqlRunPartitionScript($sTemplate)
807 $sSQL = 'select distinct partition from country_name';
808 $aPartitions = chksql($oDB->getCol($sSQL));
809 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
811 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
812 foreach ($aMatches as $aMatch) {
814 foreach ($aPartitions as $sPartitionName) {
815 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
817 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
820 pgsqlRunScript($sTemplate);
823 function pgsqlRunRestoreData($sDumpFile)
825 // Convert database DSN to psql parameters
826 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
827 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
828 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc -a '.$sDumpFile;
830 $aDescriptors = array(
831 0 => array('pipe', 'r'),
832 1 => array('pipe', 'w'),
833 2 => array('file', '/dev/null', 'a')
836 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
837 if (!is_resource($hProcess)) fail('unable to start pg_restore');
841 // TODO: error checking
842 while (!feof($ahPipes[1])) {
843 echo fread($ahPipes[1], 4096);
847 $iReturn = proc_close($hProcess);
850 function pgsqlRunDropAndRestore($sDumpFile)
852 // Convert database DSN to psql parameters
853 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
854 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
855 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
856 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
857 $sCMD .= ' -h ' . $aDSNInfo['hostspec'];
859 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
860 $sCMD .= ' -U ' . $aDSNInfo['username'];
863 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
864 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
867 $iReturn = runWithEnv($sCMD, $aProcEnv);
870 function passthpassthruCheckReturn($sCmd)
873 passthru($sCmd, $iResult);
876 function replace_tablespace($sTemplate, $sTablespace, $sSql)
879 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
881 $sSql = str_replace($sTemplate, '', $sSql);
887 function create_sql_functions($aCMDResult)
889 $sModulePath = CONST_Database_Module_Path;
890 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
891 $sTemplate = str_replace('{modulepath}', $sModulePath, $sTemplate);
892 if ($aCMDResult['enable-diff-updates']) {
893 $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
895 if ($aCMDResult['enable-debug-statements']) {
896 $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
898 if (CONST_Limit_Reindexing) {
899 $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
901 if (!CONST_Use_US_Tiger_Data) {
902 $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
904 if (!CONST_Use_Aux_Location_data) {
905 $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
907 pgsqlRunScript($sTemplate);
910 function checkModulePresence()
912 // Try accessing the C module, so we know early if something is wrong
913 // and can simply error out.
914 $sModulePath = CONST_Database_Module_Path;
915 $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
916 $sSQL .= $sModulePath."/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
917 $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
920 $oResult = $oDB->query($sSQL);
924 if (PEAR::isError($oResult)) {
925 echo "\nERROR: Failed to load nominatim module. Reason:\n";
926 echo $oResult->userinfo."\n\n";