]> git.openstreetmap.org Git - nominatim.git/blob - lib/setup/SetupClass.php
simplify connection handling in setup script
[nominatim.git] / lib / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 class SetupFunctions
6 {
7     protected $iCacheMemory;
8     protected $iInstances;
9     protected $sModulePath;
10     protected $aDSNInfo;
11     protected $sVerbose;
12     protected $sIgnoreErrors;
13     protected $bEnableDiffUpdates;
14     protected $bEnableDebugStatements;
15     protected $bNoPartitions;
16     protected $oDB = null;
17
18     public function __construct(array $aCMDResult)
19     {
20         // by default, use all but one processor, but never more than 15.
21         $this->iInstances = isset($aCMDResult['threads'])
22             ? $aCMDResult['threads']
23             : (min(16, getProcessorCount()) - 1);
24
25         if ($this->iInstances < 1) {
26             $this->iInstances = 1;
27             warn('resetting threads to '.$this->iInstances);
28         }
29
30         // Assume we can steal all the cache memory in the box (unless told otherwise)
31         if (isset($aCMDResult['osm2pgsql-cache'])) {
32             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
33         } else {
34             $this->iCacheMemory = getCacheMemoryMB();
35         }
36
37         $this->sModulePath = CONST_Database_Module_Path;
38         info('module path: ' . $this->sModulePath);
39
40         // parse database string
41         $this->aDSNInfo = array_filter(\DB::parseDSN(CONST_Database_DSN));
42         if (!isset($this->aDSNInfo['port'])) {
43             $this->aDSNInfo['port'] = 5432;
44         }
45
46         // setting member variables based on command line options stored in $aCMDResult
47         $this->sVerbose = $aCMDResult['verbose'];
48
49         //setting default values which are not set by the update.php array
50         if (isset($aCMDResult['ignore-errors'])) {
51             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
52         } else {
53             $this->sIgnoreErrors = false;
54         }
55         if (isset($aCMDResult['enable-debug-statements'])) {
56             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
57         } else {
58             $this->bEnableDebugStatements = false;
59         }
60         if (isset($aCMDResult['no-partitions'])) {
61             $this->bNoPartitions = $aCMDResult['no-partitions'];
62         } else {
63             $this->bNoPartitions = false;
64         }
65         if (isset($aCMDResult['enable-diff-updates'])) {
66             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
67         } else {
68             $this->bEnableDiffUpdates = false;
69         }
70     }
71
72     public function createDB()
73     {
74         info('Create DB');
75         $sDB = \DB::connect(CONST_Database_DSN, false);
76         if (!\PEAR::isError($sDB)) {
77             fail('database already exists ('.CONST_Database_DSN.')');
78         }
79
80         $sCreateDBCmd = 'createdb -E UTF-8 -p '.$this->aDSNInfo['port'].' '.$this->aDSNInfo['database'];
81         if (isset($this->aDSNInfo['username'])) {
82             $sCreateDBCmd .= ' -U '.$this->aDSNInfo['username'];
83         }
84
85         if (isset($this->aDSNInfo['hostspec'])) {
86             $sCreateDBCmd .= ' -h '.$this->aDSNInfo['hostspec'];
87         }
88
89         $result = $this->runWithPgEnv($sCreateDBCmd);
90         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
91     }
92
93     public function connect($sDatabaseDSN)
94     {
95         $this->oDB =& getDB();
96     }
97
98     public function setupDB()
99     {
100         info('Setup DB');
101
102         $fPostgresVersion = getPostgresVersion($this->oDB);
103         echo 'Postgres version found: '.$fPostgresVersion."\n";
104
105         if ($fPostgresVersion < 9.1) {
106             fail('Minimum supported version of Postgresql is 9.1.');
107         }
108
109         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
110         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
111
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'"));
116
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.');
120         }
121
122
123         $fPostgisVersion = getPostgisVersion($this->oDB);
124         echo 'Postgis version found: '.$fPostgisVersion."\n";
125
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');
130         }
131         if ($fPostgisVersion < 2.2) {
132             $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
133         }
134
135         $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
136         if ($i == 0) {
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";
139             exit(1);
140         }
141
142         // Try accessing the C module, so we know early if something is wrong
143         if (!checkModulePresence()) {
144             fail('error loading nominatim.so module');
145         }
146
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";
150             exit(1);
151         }
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');
156
157         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
158         if (file_exists($sPostcodeFilename)) {
159             $this->pgsqlRunScriptFile($sPostcodeFilename);
160         } else {
161             warn('optional external UK postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
162         }
163
164         if (CONST_Use_Extra_US_Postcodes) {
165             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
166         }
167
168         if ($this->bNoPartitions) {
169             $this->pgsqlRunScript('update country_name set partition = 0');
170         }
171
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);
178     }
179
180     public function importData($sOSMFile)
181     {
182         info('Import data');
183
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'");
189         }
190
191         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
193         }
194
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'])) {
207             $osm2pgsql .= ' -U '.$this->aDSNInfo['username'];
208         }
209         if (isset($this->aDSNInfo['hostspec'])) {
210             $osm2pgsql .= ' -H '.$this->aDSNInfo['hostspec'];
211         }
212         $osm2pgsql .= ' -d '.$this->aDSNInfo['database'].' '.$sOSMFile;
213
214         $this->runWithPgEnv($osm2pgsql);
215
216         if (!$this->sIgnoreErrors && !chksql($this->oDB->getRow('select * from place limit 1'))) {
217             fail('No Data');
218         }
219     }
220
221     public function createFunctions()
222     {
223         info('Create Functions');
224
225         // Try accessing the C module, so we know eif something is wrong
226         // update.php calls this function
227         if (!checkModulePresence()) {
228             fail('error loading nominatim.so module');
229         }
230         $this->createSqlFunctions();
231     }
232
233     public function createTables()
234     {
235         info('Create Tables');
236
237         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
238         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
239         $sTemplate = $this->replaceTablespace(
240             '{ts:address-data}',
241             CONST_Tablespace_Address_Data,
242             $sTemplate
243         );
244         $sTemplate = $this->replaceTablespace(
245             '{ts:address-index}',
246             CONST_Tablespace_Address_Index,
247             $sTemplate
248         );
249         $sTemplate = $this->replaceTablespace(
250             '{ts:search-data}',
251             CONST_Tablespace_Search_Data,
252             $sTemplate
253         );
254         $sTemplate = $this->replaceTablespace(
255             '{ts:search-index}',
256             CONST_Tablespace_Search_Index,
257             $sTemplate
258         );
259         $sTemplate = $this->replaceTablespace(
260             '{ts:aux-data}',
261             CONST_Tablespace_Aux_Data,
262             $sTemplate
263         );
264         $sTemplate = $this->replaceTablespace(
265             '{ts:aux-index}',
266             CONST_Tablespace_Aux_Index,
267             $sTemplate
268         );
269
270         $this->pgsqlRunScript($sTemplate, false);
271     }
272
273     public function createPartitionTables()
274     {
275         info('Create Partition Tables');
276
277         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
278         $sTemplate = $this->replaceTablespace(
279             '{ts:address-data}',
280             CONST_Tablespace_Address_Data,
281             $sTemplate
282         );
283
284         $sTemplate = $this->replaceTablespace(
285             '{ts:address-index}',
286             CONST_Tablespace_Address_Index,
287             $sTemplate
288         );
289
290         $sTemplate = $this->replaceTablespace(
291             '{ts:search-data}',
292             CONST_Tablespace_Search_Data,
293             $sTemplate
294         );
295
296         $sTemplate = $this->replaceTablespace(
297             '{ts:search-index}',
298             CONST_Tablespace_Search_Index,
299             $sTemplate
300         );
301
302         $sTemplate = $this->replaceTablespace(
303             '{ts:aux-data}',
304             CONST_Tablespace_Aux_Data,
305             $sTemplate
306         );
307
308         $sTemplate = $this->replaceTablespace(
309             '{ts:aux-index}',
310             CONST_Tablespace_Aux_Index,
311             $sTemplate
312         );
313
314         $this->pgsqlRunPartitionScript($sTemplate);
315     }
316
317     public function createPartitionFunctions()
318     {
319         info('Create Partition Functions');
320
321         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
322         $this->pgsqlRunPartitionScript($sTemplate);
323     }
324
325     public function importWikipediaArticles()
326     {
327         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikipedia_article.sql.bin';
328         $sWikiRedirectsFile = CONST_Wikipedia_Data_Path.'/wikipedia_redirect.sql.bin';
329         if (file_exists($sWikiArticlesFile)) {
330             info('Importing wikipedia articles');
331             $this->pgsqlRunDropAndRestore($sWikiArticlesFile);
332         } else {
333             warn('wikipedia article dump file not found - places will have default importance');
334         }
335         if (file_exists($sWikiRedirectsFile)) {
336             info('Importing wikipedia redirects');
337             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
338         } else {
339             warn('wikipedia redirect dump file not found - some place importance values may be missing');
340         }
341     }
342
343     public function loadData($bDisableTokenPrecalc)
344     {
345         info('Drop old Data');
346
347         if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
348         echo '.';
349         if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
350         echo '.';
351         if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
352         echo '.';
353         if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
354         echo '.';
355         if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
356         echo '.';
357         if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
358         echo '.';
359         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
360         echo '.';
361         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
362         echo '.';
363         if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
364         echo '.';
365         if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
366         echo '.';
367
368         $sSQL = 'select distinct partition from country_name';
369         $aPartitions = chksql($this->oDB->getCol($sSQL));
370         if (!$this->bNoPartitions) $aPartitions[] = 0;
371         foreach ($aPartitions as $sPartition) {
372             if (!pg_query($this->oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($this->oDB->connection));
373             echo '.';
374         }
375
376         // used by getorcreate_word_id to ignore frequent partial words
377         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
378         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
379         if (!pg_query($this->oDB->connection, $sSQL)) {
380             fail(pg_last_error($this->oDB->connection));
381         }
382         echo ".\n";
383
384         // pre-create the word list
385         if (!$bDisableTokenPrecalc) {
386             info('Loading word list');
387             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
388         }
389
390         info('Load Data');
391         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
392         $aDBInstances = array();
393         $iLoadThreads = max(1, $this->iInstances - 1);
394         for ($i = 0; $i < $iLoadThreads; $i++) {
395             $aDBInstances[$i] =& getDB(true);
396             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
397             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
398             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
399             $sSQL .= ' and ST_IsValid(geometry)';
400             if ($this->sVerbose) echo "$sSQL\n";
401             if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
402                 fail(pg_last_error($aDBInstances[$i]->connection));
403             }
404         }
405
406         // last thread for interpolation lines
407         $aDBInstances[$iLoadThreads] =& getDB(true);
408         $sSQL = 'insert into location_property_osmline';
409         $sSQL .= ' (osm_id, address, linegeo)';
410         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
411         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
412         if ($this->sVerbose) echo "$sSQL\n";
413         if (!pg_send_query($aDBInstances[$iLoadThreads]->connection, $sSQL)) {
414             fail(pg_last_error($aDBInstances[$iLoadThreads]->connection));
415         }
416
417         $bFailed = false;
418         for ($i = 0; $i <= $iLoadThreads; $i++) {
419             while (($hPGresult = pg_get_result($aDBInstances[$i]->connection)) !== false) {
420                 $resultStatus = pg_result_status($hPGresult);
421                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
422                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
423                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
424                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
425                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
426                     $resultError = pg_result_error($hPGresult);
427                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
428                     $bFailed = true;
429                 }
430             }
431         }
432         if ($bFailed) {
433             fail('SQL errors loading placex and/or location_property_osmline tables');
434         }
435         echo "\n";
436         info('Reanalysing database');
437         $this->pgsqlRunScript('ANALYSE');
438
439         $sDatabaseDate = getDatabaseDate($this->oDB);
440         pg_query($this->oDB->connection, 'TRUNCATE import_status');
441         if ($sDatabaseDate === false) {
442             warn('could not determine database date.');
443         } else {
444             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
445             pg_query($this->oDB->connection, $sSQL);
446             echo "Latest data imported from $sDatabaseDate.\n";
447         }
448     }
449
450     public function importTigerData()
451     {
452         info('Import Tiger data');
453
454         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
455         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
456         $sTemplate = $this->replaceTablespace(
457             '{ts:aux-data}',
458             CONST_Tablespace_Aux_Data,
459             $sTemplate
460         );
461         $sTemplate = $this->replaceTablespace(
462             '{ts:aux-index}',
463             CONST_Tablespace_Aux_Index,
464             $sTemplate
465         );
466         $this->pgsqlRunScript($sTemplate, false);
467
468         $aDBInstances = array();
469         for ($i = 0; $i < $this->iInstances; $i++) {
470             $aDBInstances[$i] =& getDB(true);
471         }
472
473         foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
474             echo $sFile.': ';
475             $hFile = fopen($sFile, 'r');
476             $sSQL = fgets($hFile, 100000);
477             $iLines = 0;
478             while (true) {
479                 for ($i = 0; $i < $this->iInstances; $i++) {
480                     if (!pg_connection_busy($aDBInstances[$i]->connection)) {
481                         while (pg_get_result($aDBInstances[$i]->connection));
482                         $sSQL = fgets($hFile, 100000);
483                         if (!$sSQL) break 2;
484                         if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
485                         $iLines++;
486                         if ($iLines == 1000) {
487                             echo '.';
488                             $iLines = 0;
489                         }
490                     }
491                 }
492                 usleep(10);
493             }
494             fclose($hFile);
495
496             $bAnyBusy = true;
497             while ($bAnyBusy) {
498                 $bAnyBusy = false;
499                 for ($i = 0; $i < $this->iInstances; $i++) {
500                     if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
501                 }
502                 usleep(10);
503             }
504             echo "\n";
505         }
506
507         info('Creating indexes on Tiger data');
508         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
509         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
510         $sTemplate = $this->replaceTablespace(
511             '{ts:aux-data}',
512             CONST_Tablespace_Aux_Data,
513             $sTemplate
514         );
515         $sTemplate = $this->replaceTablespace(
516             '{ts:aux-index}',
517             CONST_Tablespace_Aux_Index,
518             $sTemplate
519         );
520         $this->pgsqlRunScript($sTemplate, false);
521     }
522
523     public function calculatePostcodes($bCMDResultAll)
524     {
525         info('Calculate Postcodes');
526         if (!pg_query($this->oDB->connection, 'TRUNCATE location_postcode')) {
527             fail(pg_last_error($this->oDB->connection));
528         }
529
530
531         $sSQL  = 'INSERT INTO location_postcode';
532         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
533         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
534         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
535         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
536         $sSQL .= '  FROM placex';
537         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
538         $sSQL .= '       AND geometry IS NOT null';
539         $sSQL .= ' GROUP BY country_code, pc';
540
541         if (!pg_query($this->oDB->connection, $sSQL)) {
542             fail(pg_last_error($this->oDB->connection));
543         }
544
545         if (CONST_Use_Extra_US_Postcodes) {
546             // only add postcodes that are not yet available in OSM
547             $sSQL  = 'INSERT INTO location_postcode';
548             $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
549             $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
550             $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
551             $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
552             $sSQL .= '        (SELECT postcode FROM location_postcode';
553             $sSQL .= "          WHERE country_code = 'us')";
554             if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
555         }
556
557         // add missing postcodes for GB (if available)
558         $sSQL  = 'INSERT INTO location_postcode';
559         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
560         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
561         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
562         $sSQL .= '           (SELECT postcode FROM location_postcode';
563         $sSQL .= "             WHERE country_code = 'gb')";
564         if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
565
566         if (!$bCMDResultAll) {
567             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
568             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
569             if (!pg_query($this->oDB->connection, $sSQL)) {
570                 fail(pg_last_error($this->oDB->connection));
571             }
572         }
573         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
574         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
575
576         if (!pg_query($this->oDB->connection, $sSQL)) {
577             fail(pg_last_error($this->oDB->connection));
578         }
579     }
580
581     public function index($bIndexNoanalyse)
582     {
583         $sOutputFile = '';
584         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$this->aDSNInfo['database'].' -P '
585             .$this->aDSNInfo['port'].' -t '.$this->iInstances.$sOutputFile;
586         if (isset($this->aDSNInfo['hostspec'])) {
587             $sBaseCmd .= ' -H '.$this->aDSNInfo['hostspec'];
588         }
589         if (isset($this->aDSNInfo['username'])) {
590             $sBaseCmd .= ' -U '.$this->aDSNInfo['username'];
591         }
592
593         info('Index ranks 0 - 4');
594         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
595         if ($iStatus != 0) {
596             fail('error status ' . $iStatus . ' running nominatim!');
597         }
598         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
599         info('Index ranks 5 - 25');
600         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
601         if ($iStatus != 0) {
602             fail('error status ' . $iStatus . ' running nominatim!');
603         }
604         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
605         info('Index ranks 26 - 30');
606         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
607         if ($iStatus != 0) {
608             fail('error status ' . $iStatus . ' running nominatim!');
609         }
610         info('Index postcodes');
611         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
612         if (!pg_query($this->oDB->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
613     }
614
615     public function createSearchIndices()
616     {
617         info('Create Search indices');
618
619         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
620         $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
621         $sTemplate = $this->replaceTablespace(
622             '{ts:address-index}',
623             CONST_Tablespace_Address_Index,
624             $sTemplate
625         );
626         $sTemplate = $this->replaceTablespace(
627             '{ts:search-index}',
628             CONST_Tablespace_Search_Index,
629             $sTemplate
630         );
631         $sTemplate = $this->replaceTablespace(
632             '{ts:aux-index}',
633             CONST_Tablespace_Aux_Index,
634             $sTemplate
635         );
636         $this->pgsqlRunScript($sTemplate);
637     }
638
639     public function createCountryNames()
640     {
641         info('Create search index for default country names');
642
643         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
644         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
645         $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');
646         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
647         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
648             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
649         if (CONST_Languages) {
650             $sSQL .= 'in ';
651             $sDelim = '(';
652             foreach (explode(',', CONST_Languages) as $sLang) {
653                 $sSQL .= $sDelim."'name:$sLang'";
654                 $sDelim = ',';
655             }
656             $sSQL .= ')';
657         } else {
658             // all include all simple name tags
659             $sSQL .= "like 'name:%'";
660         }
661         $sSQL .= ') v';
662         $this->pgsqlRunScript($sSQL);
663     }
664
665     public function drop()
666     {
667         info('Drop tables only required for updates');
668
669         // The implementation is potentially a bit dangerous because it uses
670         // a positive selection of tables to keep, and deletes everything else.
671         // Including any tables that the unsuspecting user might have manually
672         // created. USE AT YOUR OWN PERIL.
673         // tables we want to keep. everything else goes.
674         $aKeepTables = array(
675                         '*columns',
676                         'import_polygon_*',
677                         'import_status',
678                         'place_addressline',
679                         'location_postcode',
680                         'location_property*',
681                         'placex',
682                         'search_name',
683                         'seq_*',
684                         'word',
685                         'query_log',
686                         'new_query_log',
687                         'spatial_ref_sys',
688                         'country_name',
689                         'place_classtype_*'
690                        );
691
692         $aDropTables = array();
693         $aHaveTables = chksql($this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
694
695         foreach ($aHaveTables as $sTable) {
696             $bFound = false;
697             foreach ($aKeepTables as $sKeep) {
698                 if (fnmatch($sKeep, $sTable)) {
699                     $bFound = true;
700                     break;
701                 }
702             }
703             if (!$bFound) array_push($aDropTables, $sTable);
704         }
705         foreach ($aDropTables as $sDrop) {
706             if ($this->sVerbose) echo "dropping table $sDrop\n";
707             @pg_query($this->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
710         }
711
712         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
713             if ($sVerbose) echo 'deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
714             unlink(CONST_Osm2pgsql_Flatnode_File);
715         }
716     }
717
718     private function pgsqlRunDropAndRestore($sDumpFile)
719     {
720         $sCMD = 'pg_restore -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
721         if (isset($this->aDSNInfo['hostspec'])) {
722             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
723         }
724         if (isset($this->aDSNInfo['username'])) {
725             $sCMD .= ' -U '.$this->aDSNInfo['username'];
726         }
727
728         $this->runWithPgEnv($sCMD);
729     }
730
731     private function pgsqlRunScript($sScript, $bfatal = true)
732     {
733         runSQLScript(
734             $sScript,
735             $bfatal,
736             $this->sVerbose,
737             $this->sIgnoreErrors
738         );
739     }
740
741     private function createSqlFunctions()
742     {
743         $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
744         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
745         if ($this->bEnableDiffUpdates) {
746             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
747         }
748         if ($this->bEnableDebugStatements) {
749             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
750         }
751         if (CONST_Limit_Reindexing) {
752             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
753         }
754         if (!CONST_Use_US_Tiger_Data) {
755             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
756         }
757         if (!CONST_Use_Aux_Location_data) {
758             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
759         }
760         $this->pgsqlRunScript($sTemplate);
761     }
762
763     private function pgsqlRunPartitionScript($sTemplate)
764     {
765         $sSQL = 'select distinct partition from country_name';
766         $aPartitions = chksql($this->oDB->getCol($sSQL));
767         if (!$this->bNoPartitions) $aPartitions[] = 0;
768
769         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
770         foreach ($aMatches as $aMatch) {
771             $sResult = '';
772             foreach ($aPartitions as $sPartitionName) {
773                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
774             }
775             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
776         }
777
778         $this->pgsqlRunScript($sTemplate);
779     }
780
781     private function pgsqlRunScriptFile($sFilename)
782     {
783         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
784
785         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
786         if (!$this->sVerbose) {
787             $sCMD .= ' -q';
788         }
789         if (isset($this->aDSNInfo['hostspec'])) {
790             $sCMD .= ' -h '.$this->aDSNInfo['hostspec'];
791         }
792         if (isset($this->aDSNInfo['username'])) {
793             $sCMD .= ' -U '.$this->aDSNInfo['username'];
794         }
795         $aProcEnv = null;
796         if (isset($this->aDSNInfo['password'])) {
797             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
798         }
799         $ahGzipPipes = null;
800         if (preg_match('/\\.gz$/', $sFilename)) {
801             $aDescriptors = array(
802                              0 => array('pipe', 'r'),
803                              1 => array('pipe', 'w'),
804                              2 => array('file', '/dev/null', 'a')
805                             );
806             $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
807             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
808             $aReadPipe = $ahGzipPipes[1];
809             fclose($ahGzipPipes[0]);
810         } else {
811             $sCMD .= ' -f '.$sFilename;
812             $aReadPipe = array('pipe', 'r');
813         }
814         $aDescriptors = array(
815                          0 => $aReadPipe,
816                          1 => array('pipe', 'w'),
817                          2 => array('file', '/dev/null', 'a')
818                         );
819         $ahPipes = null;
820         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
821         if (!is_resource($hProcess)) fail('unable to start pgsql');
822         // TODO: error checking
823         while (!feof($ahPipes[1])) {
824             echo fread($ahPipes[1], 4096);
825         }
826         fclose($ahPipes[1]);
827         $iReturn = proc_close($hProcess);
828         if ($iReturn > 0) {
829             fail("pgsql returned with error code ($iReturn)");
830         }
831         if ($ahGzipPipes) {
832             fclose($ahGzipPipes[1]);
833             proc_close($hGzipProcess);
834         }
835     }
836
837     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
838     {
839         if ($sTablespace) {
840             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
841         } else {
842             $sSql = str_replace($sTemplate, '', $sSql);
843         }
844         return $sSql;
845     }
846
847     private function runWithPgEnv($sCmd)
848     {
849         $aProcEnv = null;
850
851         if (isset($this->aDSNInfo['password'])) {
852             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
853         }
854
855         return runWithEnv($sCmd, $aProcEnv);
856     }
857 }