]> git.openstreetmap.org Git - nominatim.git/blob - lib/setup/SetupClass.php
fix indent
[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 createTableTriggers()
239     {
240         info('Create Tables');
241
242         $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
243         $sTemplate = $this->replaceSqlPatterns($sTemplate);
244
245         $this->pgsqlRunScript($sTemplate, false);
246     }
247
248     public function createPartitionTables()
249     {
250         info('Create Partition Tables');
251
252         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
253         $sTemplate = $this->replaceSqlPatterns($sTemplate);
254
255         $this->pgsqlRunPartitionScript($sTemplate);
256     }
257
258     public function createPartitionFunctions()
259     {
260         info('Create Partition Functions');
261
262         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
263         $this->pgsqlRunPartitionScript($sTemplate);
264     }
265
266     public function importWikipediaArticles()
267     {
268         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
269         if (file_exists($sWikiArticlesFile)) {
270             info('Importing wikipedia articles and redirects');
271             $this->dropTable('wikipedia_article');
272             $this->dropTable('wikipedia_redirect');
273             $this->pgsqlRunScriptFile($sWikiArticlesFile);
274         } else {
275             warn('wikipedia importance dump file not found - places will have default importance');
276         }
277     }
278
279     public function loadData($bDisableTokenPrecalc)
280     {
281         info('Drop old Data');
282
283         $this->oDB->exec('TRUNCATE word');
284         echo '.';
285         $this->oDB->exec('TRUNCATE placex');
286         echo '.';
287         $this->oDB->exec('TRUNCATE location_property_osmline');
288         echo '.';
289         $this->oDB->exec('TRUNCATE place_addressline');
290         echo '.';
291         $this->oDB->exec('TRUNCATE location_area');
292         echo '.';
293         if (!$this->dbReverseOnly()) {
294             $this->oDB->exec('TRUNCATE search_name');
295             echo '.';
296         }
297         $this->oDB->exec('TRUNCATE search_name_blank');
298         echo '.';
299         $this->oDB->exec('DROP SEQUENCE seq_place');
300         echo '.';
301         $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
302         echo '.';
303
304         $sSQL = 'select distinct partition from country_name';
305         $aPartitions = $this->oDB->getCol($sSQL);
306
307         if (!$this->bNoPartitions) $aPartitions[] = 0;
308         foreach ($aPartitions as $sPartition) {
309             $this->oDB->exec('TRUNCATE location_road_'.$sPartition);
310             echo '.';
311         }
312
313         // used by getorcreate_word_id to ignore frequent partial words
314         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
315         $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
316         $this->oDB->exec($sSQL);
317         echo ".\n";
318
319         // pre-create the word list
320         if (!$bDisableTokenPrecalc) {
321             info('Loading word list');
322             $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
323         }
324
325         info('Load Data');
326         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
327
328         $aDBInstances = array();
329         $iLoadThreads = max(1, $this->iInstances - 1);
330         for ($i = 0; $i < $iLoadThreads; $i++) {
331             // https://secure.php.net/manual/en/function.pg-connect.php
332             $DSN = CONST_Database_DSN;
333             $DSN = preg_replace('/^pgsql:/', '', $DSN);
334             $DSN = preg_replace('/;/', ' ', $DSN);
335             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
336             pg_ping($aDBInstances[$i]);
337         }
338
339         for ($i = 0; $i < $iLoadThreads; $i++) {
340             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
341             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
342             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
343             $sSQL .= ' and ST_IsValid(geometry)';
344             if ($this->bVerbose) echo "$sSQL\n";
345             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
346                 fail(pg_last_error($aDBInstances[$i]));
347             }
348         }
349
350         // last thread for interpolation lines
351         // https://secure.php.net/manual/en/function.pg-connect.php
352         $DSN = CONST_Database_DSN;
353         $DSN = preg_replace('/^pgsql:/', '', $DSN);
354         $DSN = preg_replace('/;/', ' ', $DSN);
355         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
356         pg_ping($aDBInstances[$iLoadThreads]);
357         $sSQL = 'insert into location_property_osmline';
358         $sSQL .= ' (osm_id, address, linegeo)';
359         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
360         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
361         if ($this->bVerbose) echo "$sSQL\n";
362         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
363             fail(pg_last_error($aDBInstances[$iLoadThreads]));
364         }
365
366         $bFailed = false;
367         for ($i = 0; $i <= $iLoadThreads; $i++) {
368             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
369                 $resultStatus = pg_result_status($hPGresult);
370                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
371                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
372                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
373                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
374                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
375                     $resultError = pg_result_error($hPGresult);
376                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
377                     $bFailed = true;
378                 }
379             }
380         }
381         if ($bFailed) {
382             fail('SQL errors loading placex and/or location_property_osmline tables');
383         }
384
385         for ($i = 0; $i < $this->iInstances; $i++) {
386             pg_close($aDBInstances[$i]);
387         }
388
389         echo "\n";
390         info('Reanalysing database');
391         $this->pgsqlRunScript('ANALYSE');
392
393         $sDatabaseDate = getDatabaseDate($this->oDB);
394         $this->oDB->exec('TRUNCATE import_status');
395         if (!$sDatabaseDate) {
396             warn('could not determine database date.');
397         } else {
398             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
399             $this->oDB->exec($sSQL);
400             echo "Latest data imported from $sDatabaseDate.\n";
401         }
402     }
403
404     public function importTigerData()
405     {
406         info('Import Tiger data');
407
408         $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
409         info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
410         if (empty($aFilenames)) return;
411
412         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
413         $sTemplate = $this->replaceSqlPatterns($sTemplate);
414
415         $this->pgsqlRunScript($sTemplate, false);
416
417         $aDBInstances = array();
418         for ($i = 0; $i < $this->iInstances; $i++) {
419             // https://secure.php.net/manual/en/function.pg-connect.php
420             $DSN = CONST_Database_DSN;
421             $DSN = preg_replace('/^pgsql:/', '', $DSN);
422             $DSN = preg_replace('/;/', ' ', $DSN);
423             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
424             pg_ping($aDBInstances[$i]);
425         }
426
427         foreach ($aFilenames as $sFile) {
428             echo $sFile.': ';
429             $hFile = fopen($sFile, 'r');
430             $sSQL = fgets($hFile, 100000);
431             $iLines = 0;
432             while (true) {
433                 for ($i = 0; $i < $this->iInstances; $i++) {
434                     if (!pg_connection_busy($aDBInstances[$i])) {
435                         while (pg_get_result($aDBInstances[$i]));
436                         $sSQL = fgets($hFile, 100000);
437                         if (!$sSQL) break 2;
438                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
439                         $iLines++;
440                         if ($iLines == 1000) {
441                             echo '.';
442                             $iLines = 0;
443                         }
444                     }
445                 }
446                 usleep(10);
447             }
448             fclose($hFile);
449
450             $bAnyBusy = true;
451             while ($bAnyBusy) {
452                 $bAnyBusy = false;
453                 for ($i = 0; $i < $this->iInstances; $i++) {
454                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
455                 }
456                 usleep(10);
457             }
458             echo "\n";
459         }
460
461         for ($i = 0; $i < $this->iInstances; $i++) {
462             pg_close($aDBInstances[$i]);
463         }
464
465         info('Creating indexes on Tiger data');
466         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
467         $sTemplate = $this->replaceSqlPatterns($sTemplate);
468
469         $this->pgsqlRunScript($sTemplate, false);
470     }
471
472     public function calculatePostcodes($bCMDResultAll)
473     {
474         info('Calculate Postcodes');
475         $this->oDB->exec('TRUNCATE location_postcode');
476
477         $sSQL  = 'INSERT INTO location_postcode';
478         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
479         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
480         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
481         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
482         $sSQL .= '  FROM placex';
483         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
484         $sSQL .= '       AND geometry IS NOT null';
485         $sSQL .= ' GROUP BY country_code, pc';
486         $this->oDB->exec($sSQL);
487
488         // only add postcodes that are not yet available in OSM
489         $sSQL  = 'INSERT INTO location_postcode';
490         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
491         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
492         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
493         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
494         $sSQL .= '        (SELECT postcode FROM location_postcode';
495         $sSQL .= "          WHERE country_code = 'us')";
496         $this->oDB->exec($sSQL);
497
498         // add missing postcodes for GB (if available)
499         $sSQL  = 'INSERT INTO location_postcode';
500         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
501         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
502         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
503         $sSQL .= '           (SELECT postcode FROM location_postcode';
504         $sSQL .= "             WHERE country_code = 'gb')";
505         $this->oDB->exec($sSQL);
506
507         if (!$bCMDResultAll) {
508             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
509             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
510             $this->oDB->exec($sSQL);
511         }
512
513         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
514         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
515         $this->oDB->exec($sSQL);
516     }
517
518     public function index($bIndexNoanalyse)
519     {
520         $sOutputFile = '';
521         $sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i'
522             .' -d '.escapeshellarg($this->aDSNInfo['database'])
523             .' -P '.escapeshellarg($this->aDSNInfo['port'])
524             .' -t '.escapeshellarg($this->iInstances.$sOutputFile);
525         if (isset($this->aDSNInfo['hostspec'])) {
526             $sBaseCmd .= ' -H '.escapeshellarg($this->aDSNInfo['hostspec']);
527         }
528         if (isset($this->aDSNInfo['username'])) {
529             $sBaseCmd .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
530         }
531
532         info('Index ranks 0 - 4');
533         $iStatus = $this->runWithPgEnv($sBaseCmd.' -R 4');
534         if ($iStatus != 0) {
535             fail('error status ' . $iStatus . ' running nominatim!');
536         }
537         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
538
539         info('Index ranks 5 - 25');
540         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 5 -R 25');
541         if ($iStatus != 0) {
542             fail('error status ' . $iStatus . ' running nominatim!');
543         }
544         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
545
546         info('Index ranks 26 - 30');
547         $iStatus = $this->runWithPgEnv($sBaseCmd.' -r 26');
548         if ($iStatus != 0) {
549             fail('error status ' . $iStatus . ' running nominatim!');
550         }
551
552         info('Index postcodes');
553         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
554         $this->oDB->exec($sSQL);
555     }
556
557     public function createSearchIndices()
558     {
559         info('Create Search indices');
560
561         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
562         if (!$this->dbReverseOnly()) {
563             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
564         }
565         $sTemplate = $this->replaceSqlPatterns($sTemplate);
566
567         $this->pgsqlRunScript($sTemplate);
568     }
569
570     public function createCountryNames()
571     {
572         info('Create search index for default country names');
573
574         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
575         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
576         $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');
577         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
578         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
579             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
580         if (CONST_Languages) {
581             $sSQL .= 'in ';
582             $sDelim = '(';
583             foreach (explode(',', CONST_Languages) as $sLang) {
584                 $sSQL .= $sDelim."'name:$sLang'";
585                 $sDelim = ',';
586             }
587             $sSQL .= ')';
588         } else {
589             // all include all simple name tags
590             $sSQL .= "like 'name:%'";
591         }
592         $sSQL .= ') v';
593         $this->pgsqlRunScript($sSQL);
594     }
595
596     public function drop()
597     {
598         info('Drop tables only required for updates');
599
600         // The implementation is potentially a bit dangerous because it uses
601         // a positive selection of tables to keep, and deletes everything else.
602         // Including any tables that the unsuspecting user might have manually
603         // created. USE AT YOUR OWN PERIL.
604         // tables we want to keep. everything else goes.
605         $aKeepTables = array(
606                         '*columns',
607                         'import_polygon_*',
608                         'import_status',
609                         'place_addressline',
610                         'location_postcode',
611                         'location_property*',
612                         'placex',
613                         'search_name',
614                         'seq_*',
615                         'word',
616                         'query_log',
617                         'new_query_log',
618                         'spatial_ref_sys',
619                         'country_name',
620                         'place_classtype_*',
621                         'country_osm_grid'
622                        );
623
624         $aDropTables = array();
625         $aHaveTables = $this->oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
626
627         foreach ($aHaveTables as $sTable) {
628             $bFound = false;
629             foreach ($aKeepTables as $sKeep) {
630                 if (fnmatch($sKeep, $sTable)) {
631                     $bFound = true;
632                     break;
633                 }
634             }
635             if (!$bFound) array_push($aDropTables, $sTable);
636         }
637         foreach ($aDropTables as $sDrop) {
638             $this->dropTable($sDrop);
639         }
640
641         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
642             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
643                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
644                 unlink(CONST_Osm2pgsql_Flatnode_File);
645             }
646         }
647     }
648
649     private function pgsqlRunScript($sScript, $bfatal = true)
650     {
651         runSQLScript(
652             $sScript,
653             $bfatal,
654             $this->bVerbose,
655             $this->sIgnoreErrors
656         );
657     }
658
659     private function createSqlFunctions()
660     {
661         $sBasePath = CONST_BasePath.'/sql/functions/';
662         $sTemplate = file_get_contents($sBasePath.'utils.sql');
663         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
664         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
665         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
666         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
667         if ($this->oDB->tableExists('place')) {
668             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
669         }
670         if ($this->oDB->tableExists('placex')) {
671             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
672         }
673         if ($this->oDB->tableExists('location_postcode')) {
674             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
675         }
676         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
677         if ($this->bEnableDiffUpdates) {
678             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
679         }
680         if ($this->bEnableDebugStatements) {
681             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
682         }
683         if (CONST_Limit_Reindexing) {
684             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
685         }
686         if (!CONST_Use_US_Tiger_Data) {
687             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
688         }
689         if (!CONST_Use_Aux_Location_data) {
690             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
691         }
692
693         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
694         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
695
696         $this->pgsqlRunScript($sTemplate);
697     }
698
699     private function pgsqlRunPartitionScript($sTemplate)
700     {
701         $sSQL = 'select distinct partition from country_name';
702         $aPartitions = $this->oDB->getCol($sSQL);
703         if (!$this->bNoPartitions) $aPartitions[] = 0;
704
705         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
706         foreach ($aMatches as $aMatch) {
707             $sResult = '';
708             foreach ($aPartitions as $sPartitionName) {
709                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
710             }
711             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
712         }
713
714         $this->pgsqlRunScript($sTemplate);
715     }
716
717     private function pgsqlRunScriptFile($sFilename)
718     {
719         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
720
721         $sCMD = 'psql'
722             .' -p '.escapeshellarg($this->aDSNInfo['port'])
723             .' -d '.escapeshellarg($this->aDSNInfo['database']);
724         if (!$this->bVerbose) {
725             $sCMD .= ' -q';
726         }
727         if (isset($this->aDSNInfo['hostspec'])) {
728             $sCMD .= ' -h '.escapeshellarg($this->aDSNInfo['hostspec']);
729         }
730         if (isset($this->aDSNInfo['username'])) {
731             $sCMD .= ' -U '.escapeshellarg($this->aDSNInfo['username']);
732         }
733         $aProcEnv = null;
734         if (isset($this->aDSNInfo['password'])) {
735             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
736         }
737         $ahGzipPipes = null;
738         if (preg_match('/\\.gz$/', $sFilename)) {
739             $aDescriptors = array(
740                              0 => array('pipe', 'r'),
741                              1 => array('pipe', 'w'),
742                              2 => array('file', '/dev/null', 'a')
743                             );
744             $hGzipProcess = proc_open('zcat '.escapeshellarg($sFilename), $aDescriptors, $ahGzipPipes);
745             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
746             $aReadPipe = $ahGzipPipes[1];
747             fclose($ahGzipPipes[0]);
748         } else {
749             $sCMD .= ' -f '.escapeshellarg($sFilename);
750             $aReadPipe = array('pipe', 'r');
751         }
752         $aDescriptors = array(
753                          0 => $aReadPipe,
754                          1 => array('pipe', 'w'),
755                          2 => array('file', '/dev/null', 'a')
756                         );
757         $ahPipes = null;
758         $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes, null, $aProcEnv);
759         if (!is_resource($hProcess)) fail('unable to start pgsql');
760         // TODO: error checking
761         while (!feof($ahPipes[1])) {
762             echo fread($ahPipes[1], 4096);
763         }
764         fclose($ahPipes[1]);
765         $iReturn = proc_close($hProcess);
766         if ($iReturn > 0) {
767             fail("pgsql returned with error code ($iReturn)");
768         }
769         if ($ahGzipPipes) {
770             fclose($ahGzipPipes[1]);
771             proc_close($hGzipProcess);
772         }
773     }
774
775     private function replaceSqlPatterns($sSql)
776     {
777         $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
778
779         $aPatterns = array(
780                       '{ts:address-data}' => CONST_Tablespace_Address_Data,
781                       '{ts:address-index}' => CONST_Tablespace_Address_Index,
782                       '{ts:search-data}' => CONST_Tablespace_Search_Data,
783                       '{ts:search-index}' =>  CONST_Tablespace_Search_Index,
784                       '{ts:aux-data}' =>  CONST_Tablespace_Aux_Data,
785                       '{ts:aux-index}' =>  CONST_Tablespace_Aux_Index,
786         );
787
788         foreach ($aPatterns as $sPattern => $sTablespace) {
789             if ($sTablespace) {
790                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
791             } else {
792                 $sSql = str_replace($sPattern, '', $sSql);
793             }
794         }
795
796         return $sSql;
797     }
798
799     private function runWithPgEnv($sCmd)
800     {
801         if ($this->bVerbose) {
802             echo "Execute: $sCmd\n";
803         }
804
805         $aProcEnv = null;
806
807         if (isset($this->aDSNInfo['password'])) {
808             $aProcEnv = array_merge(array('PGPASSWORD' => $this->aDSNInfo['password']), $_ENV);
809         }
810
811         return runWithEnv($sCmd, $aProcEnv);
812     }
813
814     /**
815      * Drop table with the given name if it exists.
816      *
817      * @param string $sName Name of table to remove.
818      *
819      * @return null
820      *
821      * @pre connect() must have been called.
822      */
823     private function dropTable($sName)
824     {
825         if ($this->bVerbose) echo "Dropping table $sName\n";
826         $this->oDB->exec('DROP TABLE IF EXISTS '.$sName.' CASCADE');
827     }
828
829     /**
830      * Check if the database is in reverse-only mode.
831      *
832      * @return True if there is no search_name table and infrastructure.
833      */
834     private function dbReverseOnly()
835     {
836         return !($this->oDB->tableExists('search_name'));
837     }
838 }