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