]> git.openstreetmap.org Git - nominatim.git/blob - lib/SetupClass.php
more format changes for Mr. Travis
[nominatim.git] / lib / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 class SetupFunctions
6 {
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
18
19     public function __construct($aCMDResult)
20     {
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);
25
26
27         if ($this->iInstances < 1) {
28             $this->iInstances = 1;
29             warn('resetting threads to '.$this->iInstances);
30         }
31
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'];
35         } else {
36             $this->iCacheMemory = getCacheMemoryMB();
37         }
38
39         $this->sModulePath = CONST_Database_Module_Path;
40         info('module path: ' . $this->sModulePath);
41        
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;
45  
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'];
52     }
53
54     public function createDB()
55     {
56         info('Create DB');
57         $sDB = \DB::connect(CONST_Database_DSN, false);
58         if (!\PEAR::isError($sDB)) {
59             fail('database already exists ('.CONST_Database_DSN.')');
60         }
61
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'];
65         }
66
67         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
68             $sCreateDBCmd .= ' -h ' . $this->aDSNInfo['hostspec'];
69         }
70
71         $aProcEnv = null;
72         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
73             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
74         }
75
76         $result = runWithEnv($sCreateDBCmd, $aProcEnv);
77         if ($result != 0) fail('Error executing external command: '.$sCreateDBCmd);
78     }
79
80     public function setupDB()
81     {
82         info('Setup DB');
83         $this->oDB =& getDB();
84
85         $fPostgresVersion = getPostgresVersion($this->oDB);
86         echo 'Postgres version found: '.$fPostgresVersion."\n";
87
88         if ($fPostgresVersion < 9.1) {
89             fail('Minimum supported version of Postgresql is 9.1.');
90         }
91
92         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
93         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
94
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'"));
99
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.');
103         }
104
105
106         $fPostgisVersion = getPostgisVersion($this->oDB);
107         echo 'Postgis version found: '.$fPostgisVersion."\n";
108
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');
113         }
114         if ($fPostgisVersion < 2.2) {
115             $this->pgsqlRunScript('ALTER FUNCTION ST_Distance_Spheroid(geometry, geometry, spheroid) RENAME TO ST_DistanceSpheroid');
116         }
117
118         $i = chksql($this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'"));
119         if ($i == 0) {
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";
122             exit(1);
123         }
124
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";
128             exit(1);
129         }
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');
134
135
136         if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
137             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
138         } else {
139             warn('external UK postcode table not found.');
140         }
141
142         if (CONST_Use_Extra_US_Postcodes) {
143             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
144         }
145
146         if ($this->bNoPartitions) {
147             $this->pgsqlRunScript('update country_name set partition = 0');
148         }
149
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);
156     }
157
158     public function importData($sOSMFile)
159     {
160         info('Import data');
161
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'");
167         }
168
169
170
171         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
172             $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
173         }
174
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'];
188         }
189         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
190             $osm2pgsql .= ' -H ' . $this->aDSNInfo['hostspec'];
191         }
192         $aProcEnv = null;
193         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
194             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
195         }
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'))) {
200             fail('No Data');
201         }
202     }
203
204     public function createFunctions()
205     {
206         info('Create Functions');
207
208         $this->createSqlFunctions();
209     }
210
211     public function createTables()
212     {
213         info('Create Tables');
214
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(
218             '{ts:address-data}',
219             CONST_Tablespace_Address_Data,
220             $sTemplate
221         );
222         $sTemplate = $this->replaceTablespace(
223             '{ts:address-index}',
224             CONST_Tablespace_Address_Index,
225             $sTemplate
226         );
227         $sTemplate = $this->replaceTablespace(
228             '{ts:search-data}',
229             CONST_Tablespace_Search_Data,
230             $sTemplate
231         );
232         $sTemplate = $this->replaceTablespace(
233             '{ts:search-index}',
234             CONST_Tablespace_Search_Index,
235             $sTemplate
236         );
237         $sTemplate = $this->replaceTablespace(
238             '{ts:aux-data}',
239             CONST_Tablespace_Aux_Data,
240             $sTemplate
241         );
242         $sTemplate = $this->replaceTablespace(
243             '{ts:aux-index}',
244             CONST_Tablespace_Aux_Index,
245             $sTemplate
246         );
247
248         $this->pgsqlRunScript($sTemplate, false);
249     }
250
251     public function createPartitionTables()
252     {
253         info('Create Partition Tables');
254
255         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
256         $sTemplate = $this->replaceTablespace(
257             '{ts:address-data}',
258             CONST_Tablespace_Address_Data,
259             $sTemplate
260         );
261
262         $sTemplate = $this->replaceTablespace(
263             '{ts:address-index}',
264             CONST_Tablespace_Address_Index,
265             $sTemplate
266         );
267
268         $sTemplate = $this->replaceTablespace(
269             '{ts:search-data}',
270             CONST_Tablespace_Search_Data,
271             $sTemplate
272         );
273
274         $sTemplate = $this->replaceTablespace(
275             '{ts:search-index}',
276             CONST_Tablespace_Search_Index,
277             $sTemplate
278         );
279
280         $sTemplate = $this->replaceTablespace(
281             '{ts:aux-data}',
282             CONST_Tablespace_Aux_Data,
283             $sTemplate
284         );
285
286         $sTemplate = $this->replaceTablespace(
287             '{ts:aux-index}',
288             CONST_Tablespace_Aux_Index,
289             $sTemplate
290         );
291
292         $this->pgsqlRunPartitionScript($sTemplate);
293     }
294
295     public function createPartitionFunctions()
296     {
297         info('Create Partition Functions');
298
299         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
300         $this->pgsqlRunPartitionScript($sTemplate);
301     }
302
303     public function importWikipediaArticles()
304     {
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);
310         } else {
311             warn('wikipedia article dump file not found - places will have default importance');
312         }
313         if (file_exists($sWikiRedirectsFile)) {
314             info('Importing wikipedia redirects');
315             $this->pgsqlRunDropAndRestore($sWikiRedirectsFile);
316         } else {
317             warn('wikipedia redirect dump file not found - some place importance values may be missing');
318         }
319         echo ' finish wikipedia';
320     }
321
322     public function loadData($bDisableTokenPrecalc)
323     {
324         info('Drop old Data');
325
326         if ($this->oDB == null) $this->oDB =& getDB();
327
328         if (!pg_query($this->oDB->connection, 'TRUNCATE word')) fail(pg_last_error($this->oDB->connection));
329         echo '.';
330         if (!pg_query($this->oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($this->oDB->connection));
331         echo '.';
332         if (!pg_query($this->oDB->connection, 'TRUNCATE location_property_osmline')) fail(pg_last_error($this->oDB->connection));
333         echo '.';
334         if (!pg_query($this->oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($this->oDB->connection));
335         echo '.';
336         if (!pg_query($this->oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($this->oDB->connection));
337         echo '.';
338         if (!pg_query($this->oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($this->oDB->connection));
339         echo '.';
340         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($this->oDB->connection));
341         echo '.';
342         if (!pg_query($this->oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($this->oDB->connection));
343         echo '.';
344         if (!pg_query($this->oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($this->oDB->connection));
345         echo '.';
346         if (!pg_query($this->oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($this->oDB->connection));
347         echo '.';
348
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));
354             echo '.';
355         }
356
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));
362         }
363         echo ".\n";
364
365         // pre-create the word list
366         if (!$bDisableTokenPrecalc) {
367             info('Loading word list');
368             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
369         }
370
371         info('Load Data');
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));
384             }
385         }
386
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));
396         }
397
398         $bFailed = false;
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";
409                     $bFailed = true;
410                 }
411             }
412         }
413         if ($bFailed) {
414             fail('SQL errors loading placex and/or location_property_osmline tables');
415         }
416         echo "\n";
417         info('Reanalysing database');
418         $this->pgsqlRunScript('ANALYSE');
419
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.');
424         } else {
425             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
426             pg_query($this->oDB->connection, $sSQL);
427             echo "Latest data imported from $sDatabaseDate.\n";
428         }
429     }
430
431     public function importTigerData()
432     {
433         info('Import Tiger data');
434
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(
438             '{ts:aux-data}',
439             CONST_Tablespace_Aux_Data,
440             $sTemplate
441         );
442         $sTemplate = $this->replaceTablespace(
443             '{ts:aux-index}',
444             CONST_Tablespace_Aux_Index,
445             $sTemplate
446         );
447         $this->pgsqlRunScript($sTemplate, false);
448
449         $aDBInstances = array();
450         for ($i = 0; $i < $this->iInstances; $i++) {
451             $aDBInstances[$i] =& getDB(true);
452         }
453
454         foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
455             echo $sFile.': ';
456             $hFile = fopen($sFile, 'r');
457             $sSQL = fgets($hFile, 100000);
458             $iLines = 0;
459             while (true) {
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);
464                         if (!$sSQL) break 2;
465                         if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($this->oDB->connection));
466                         $iLines++;
467                         if ($iLines == 1000) {
468                             echo '.';
469                             $iLines = 0;
470                         }
471                     }
472                 }
473                 usleep(10);
474             }
475             fclose($hFile);
476
477             $bAnyBusy = true;
478             while ($bAnyBusy) {
479                 $bAnyBusy = false;
480                 for ($i = 0; $i < $this->iInstances; $i++) {
481                     if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
482                 }
483                 usleep(10);
484             }
485             echo "\n";
486         }
487
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(
492             '{ts:aux-data}',
493             CONST_Tablespace_Aux_Data,
494             $sTemplate
495         );
496         $sTemplate = $this->replaceTablespace(
497             '{ts:aux-index}',
498             CONST_Tablespace_Aux_Index,
499             $sTemplate
500         );
501         $this->pgsqlRunScript($sTemplate, false);
502     }
503
504     public function calculatePostcodes($bCMDResultAll)
505     {
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));
510         }
511
512
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';
522
523         if (!pg_query($this->oDB->connection, $sSQL)) {
524             fail(pg_last_error($this->oDB->connection));
525         }
526
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));
537         }
538
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));
547
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));
553             }
554         }
555         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
556         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
557
558         if (!pg_query($this->oDB->connection, $sSQL)) {
559             fail(pg_last_error($this->oDB->connection));
560         }
561     }
562
563     public function index($bIndexNoanalyse)
564     {
565         $sOutputFile = '';
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'];
570         }
571         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
572             $sBaseCmd .= ' -U ' . $this->aDSNInfo['username'];
573         }
574         $aProcEnv = null;
575         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
576             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
577         }
578
579         info('Index ranks 0 - 4');
580         $iStatus = runWithEnv($sBaseCmd.' -R 4', $aProcEnv);
581         if ($iStatus != 0) {
582             fail('error status ' . $iStatus . ' running nominatim!');
583         }
584         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
585         info('Index ranks 5 - 25');
586         $iStatus = runWithEnv($sBaseCmd.' -r 5 -R 25', $aProcEnv);
587         if ($iStatus != 0) {
588             fail('error status ' . $iStatus . ' running nominatim!');
589         }
590         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
591         info('Index ranks 26 - 30');
592         $iStatus = runWithEnv($sBaseCmd.' -r 26', $aProcEnv);
593         if ($iStatus != 0) {
594             fail('error status ' . $iStatus . ' running nominatim!');
595         }
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));
600     }
601
602     public function createSearchIndices()
603     {
604         info('Create Search indices');
605
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,
611             $sTemplate
612         );
613         $sTemplate = $this->replaceTablespace(
614             '{ts:search-index}',
615             CONST_Tablespace_Search_Index,
616             $sTemplate
617         );
618         $sTemplate = $this->replaceTablespace(
619             '{ts:aux-index}',
620             CONST_Tablespace_Aux_Index,
621             $sTemplate
622         );
623         $this->pgsqlRunScript($sTemplate);
624     }
625
626     public function createCountryNames()
627     {
628         info('Create search index for default country names');
629
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) {
637             $sSQL .= 'in ';
638             $sDelim = '(';
639             foreach (explode(',', CONST_Languages) as $sLang) {
640                 $sSQL .= $sDelim."'name:$sLang'";
641                 $sDelim = ',';
642             }
643             $sSQL .= ')';
644         } else {
645             // all include all simple name tags
646             $sSQL .= "like 'name:%'";
647         }
648         $sSQL .= ') v';
649         $this->pgsqlRunScript($sSQL);
650     }
651
652     public function drop()
653     {
654         info('Drop tables only required for updates');
655
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(
662                         '*columns',
663                         'import_polygon_*',
664                         'import_status',
665                         'place_addressline',
666                         'location_postcode',
667                         'location_property*',
668                         'placex',
669                         'search_name',
670                         'seq_*',
671                         'word',
672                         'query_log',
673                         'new_query_log',
674                         'spatial_ref_sys',
675                         'country_name',
676                         'place_classtype_*'
677                        );
678
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'"));
682
683         foreach ($aHaveTables as $sTable) {
684             $bFound = false;
685             foreach ($aKeepTables as $sKeep) {
686                 if (fnmatch($sKeep, $sTable)) {
687                     $bFound = true;
688                     break;
689                 }
690             }
691             if (!$bFound) array_push($aDropTables, $sTable);
692         }
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
698         }
699
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);
703         }
704     }
705
706     private function pgsqlRunDropAndRestore($sDumpFile)
707     {
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'];
712         }
713         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
714             $sCMD .= ' -U ' . $this->aDSNInfo['username'];
715         }
716         $aProcEnv = null;
717         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
718             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
719         }
720         $iReturn = runWithEnv($sCMD, $aProcEnv);    // /lib/cmd.php "function runWithEnv($sCmd, $aEnv)"
721     }
722                      
723     private function pgsqlRunScript($sScript, $bfatal = true)
724     {
725         runSQLScript(
726             $sScript,
727             $bfatal,
728             $this->sVerbose,
729             $this->sIgnoreErrors
730         );
731     }
732
733     private function createSqlFunctions()
734     {
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);
739         }
740         if ($this->bEnableDebugStatements) {
741             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
742         }
743         if (CONST_Limit_Reindexing) {
744             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
745         }
746         if (!CONST_Use_US_Tiger_Data) {
747             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
748         }
749         if (!CONST_Use_Aux_Location_data) {
750             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
751         }
752         $this->pgsqlRunScript($sTemplate);
753     }
754
755     private function pgsqlRunPartitionScript($sTemplate)
756     {
757         if ($this->oDB == null) $this->oDB =& getDB();
758
759         $sSQL = 'select distinct partition from country_name';
760         $aPartitions = chksql($this->oDB->getCol($sSQL));
761         if (!$this->bNoPartitions) $aPartitions[] = 0;
762
763         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
764         foreach ($aMatches as $aMatch) {
765             $sResult = '';
766             foreach ($aPartitions as $sPartitionName) {
767                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
768             }
769             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
770         }
771
772         $this->pgsqlRunScript($sTemplate);
773     }
774
775     private function pgsqlRunScriptFile($sFilename)
776     {
777         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
778
779         $sCMD = 'psql -p '.$this->aDSNInfo['port'].' -d '.$this->aDSNInfo['database'];
780         if (!$this->sVerbose) {
781             $sCMD .= ' -q';
782         }
783         if (isset($this->aDSNInfo['hostspec']) && $this->aDSNInfo['hostspec']) {
784             $sCMD .= ' -h ' . $this->aDSNInfo['hostspec'];
785         }
786         if (isset($this->aDSNInfo['username']) && $this->aDSNInfo['username']) {
787             $sCMD .= ' -U ' . $this->aDSNInfo['username'];
788         }
789         $aProcEnv = null;
790         if (isset($this->aDSNInfo['password']) && $this->aDSNInfo['password']) {
791             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
792         }
793         $ahGzipPipes = null;
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')
799                             );
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]);
804         } else {
805             $sCMD .= ' -f '.$sFilename;
806             $aReadPipe = array('pipe', 'r');
807         }
808         $aDescriptors = array(
809                          0 => $aReadPipe,
810                          1 => array('pipe', 'w'),
811                          2 => array('file', '/dev/null', 'a')
812                         );
813         $ahPipes = null;
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);
819         }
820         fclose($ahPipes[1]);
821         $iReturn = proc_close($hProcess);
822         if ($iReturn > 0) {
823             fail("pgsql returned with error code ($iReturn)");
824         }
825         if ($ahGzipPipes) {
826             fclose($ahGzipPipes[1]);
827             proc_close($hGzipProcess);
828         }
829     }
830
831     private function replaceTablespace($sTemplate, $sTablespace, $sSql)
832     {
833         if ($sTablespace) {
834             $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
835         } else {
836             $sSql = str_replace($sTemplate, '', $sSql);
837         }
838         return $sSql;
839     }
840 }