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