]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/setup/SetupClass.php
move import-data option to native python
[nominatim.git] / lib-php / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 require_once(CONST_LibDir.'/Shell.php');
6
7 class SetupFunctions
8 {
9     protected $iCacheMemory;
10     protected $iInstances;
11     protected $aDSNInfo;
12     protected $bQuiet;
13     protected $bVerbose;
14     protected $sIgnoreErrors;
15     protected $bEnableDiffUpdates;
16     protected $bEnableDebugStatements;
17     protected $bNoPartitions;
18     protected $bDrop;
19     protected $oDB = null;
20     protected $oNominatimCmd;
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 (getSetting('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         // parse database string
45         $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
46         if (!isset($this->aDSNInfo['port'])) {
47             $this->aDSNInfo['port'] = 5432;
48         }
49
50         // setting member variables based on command line options stored in $aCMDResult
51         $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
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         $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
77
78         $this->oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
79         if ($this->bQuiet) {
80             $this->oNominatimCmd->addParams('--quiet');
81         }
82         if ($this->bVerbose) {
83             $this->oNominatimCmd->addParams('--verbose');
84         }
85     }
86
87     public function createFunctions()
88     {
89         info('Create Functions');
90
91         // Try accessing the C module, so we know early if something is wrong
92         $this->checkModulePresence(); // raises exception on failure
93
94         $this->createSqlFunctions();
95     }
96
97     public function createTables($bReverseOnly = false)
98     {
99         info('Create Tables');
100
101         $sTemplate = file_get_contents(CONST_SqlDir.'/tables.sql');
102         $sTemplate = $this->replaceSqlPatterns($sTemplate);
103
104         $this->pgsqlRunScript($sTemplate, false);
105
106         if ($bReverseOnly) {
107             $this->dropTable('search_name');
108         }
109
110         (clone($this->oNominatimCmd))->addParams('refresh', '--address-levels')->run();
111     }
112
113     public function createTableTriggers()
114     {
115         info('Create Tables');
116
117         $sTemplate = file_get_contents(CONST_SqlDir.'/table-triggers.sql');
118         $sTemplate = $this->replaceSqlPatterns($sTemplate);
119
120         $this->pgsqlRunScript($sTemplate, false);
121     }
122
123     public function createPartitionTables()
124     {
125         info('Create Partition Tables');
126
127         $sTemplate = file_get_contents(CONST_SqlDir.'/partition-tables.src.sql');
128         $sTemplate = $this->replaceSqlPatterns($sTemplate);
129
130         $this->pgsqlRunPartitionScript($sTemplate);
131     }
132
133     public function createPartitionFunctions()
134     {
135         info('Create Partition Functions');
136         $this->createSqlFunctions(); // also create partition functions
137     }
138
139     public function importWikipediaArticles()
140     {
141         $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_InstallDir);
142         $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
143         if (file_exists($sWikiArticlesFile)) {
144             info('Importing wikipedia articles and redirects');
145             $this->dropTable('wikipedia_article');
146             $this->dropTable('wikipedia_redirect');
147             $this->pgsqlRunScriptFile($sWikiArticlesFile);
148         } else {
149             warn('wikipedia importance dump file not found - places will have default importance');
150         }
151     }
152
153     public function loadData($bDisableTokenPrecalc)
154     {
155         info('Drop old Data');
156
157         $oDB = $this->db();
158
159         $oDB->exec('TRUNCATE word');
160         echo '.';
161         $oDB->exec('TRUNCATE placex');
162         echo '.';
163         $oDB->exec('TRUNCATE location_property_osmline');
164         echo '.';
165         $oDB->exec('TRUNCATE place_addressline');
166         echo '.';
167         $oDB->exec('TRUNCATE location_area');
168         echo '.';
169         if (!$this->dbReverseOnly()) {
170             $oDB->exec('TRUNCATE search_name');
171             echo '.';
172         }
173         $oDB->exec('TRUNCATE search_name_blank');
174         echo '.';
175         $oDB->exec('DROP SEQUENCE seq_place');
176         echo '.';
177         $oDB->exec('CREATE SEQUENCE seq_place start 100000');
178         echo '.';
179
180         $sSQL = 'select distinct partition from country_name';
181         $aPartitions = $oDB->getCol($sSQL);
182
183         if (!$this->bNoPartitions) $aPartitions[] = 0;
184         foreach ($aPartitions as $sPartition) {
185             $oDB->exec('TRUNCATE location_road_'.$sPartition);
186             echo '.';
187         }
188
189         // used by getorcreate_word_id to ignore frequent partial words
190         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
191         $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
192         $oDB->exec($sSQL);
193         echo ".\n";
194
195         // pre-create the word list
196         if (!$bDisableTokenPrecalc) {
197             info('Loading word list');
198             $this->pgsqlRunScriptFile(CONST_DataDir.'/words.sql');
199         }
200
201         info('Load Data');
202         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
203
204         $aDBInstances = array();
205         $iLoadThreads = max(1, $this->iInstances - 1);
206         for ($i = 0; $i < $iLoadThreads; $i++) {
207             // https://secure.php.net/manual/en/function.pg-connect.php
208             $DSN = getSetting('DATABASE_DSN');
209             $DSN = preg_replace('/^pgsql:/', '', $DSN);
210             $DSN = preg_replace('/;/', ' ', $DSN);
211             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
212             pg_ping($aDBInstances[$i]);
213         }
214
215         for ($i = 0; $i < $iLoadThreads; $i++) {
216             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
217             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
218             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
219             $sSQL .= ' and ST_IsValid(geometry)';
220             if ($this->bVerbose) echo "$sSQL\n";
221             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
222                 fail(pg_last_error($aDBInstances[$i]));
223             }
224         }
225
226         // last thread for interpolation lines
227         // https://secure.php.net/manual/en/function.pg-connect.php
228         $DSN = getSetting('DATABASE_DSN');
229         $DSN = preg_replace('/^pgsql:/', '', $DSN);
230         $DSN = preg_replace('/;/', ' ', $DSN);
231         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
232         pg_ping($aDBInstances[$iLoadThreads]);
233         $sSQL = 'insert into location_property_osmline';
234         $sSQL .= ' (osm_id, address, linegeo)';
235         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
236         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
237         if ($this->bVerbose) echo "$sSQL\n";
238         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
239             fail(pg_last_error($aDBInstances[$iLoadThreads]));
240         }
241
242         $bFailed = false;
243         for ($i = 0; $i <= $iLoadThreads; $i++) {
244             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
245                 $resultStatus = pg_result_status($hPGresult);
246                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
247                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
248                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
249                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
250                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
251                     $resultError = pg_result_error($hPGresult);
252                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
253                     $bFailed = true;
254                 }
255             }
256         }
257         if ($bFailed) {
258             fail('SQL errors loading placex and/or location_property_osmline tables');
259         }
260
261         for ($i = 0; $i < $this->iInstances; $i++) {
262             pg_close($aDBInstances[$i]);
263         }
264
265         echo "\n";
266         info('Reanalysing database');
267         $this->pgsqlRunScript('ANALYSE');
268
269         $sDatabaseDate = getDatabaseDate($oDB);
270         $oDB->exec('TRUNCATE import_status');
271         if (!$sDatabaseDate) {
272             warn('could not determine database date.');
273         } else {
274             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
275             $oDB->exec($sSQL);
276             echo "Latest data imported from $sDatabaseDate.\n";
277         }
278     }
279
280     public function importTigerData($sTigerPath)
281     {
282         info('Import Tiger data');
283
284         $aFilenames = glob($sTigerPath.'/*.sql');
285         info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
286         if (empty($aFilenames)) {
287             warn('Tiger data import selected but no files found in path '.$sTigerPath);
288             return;
289         }
290         $sTemplate = file_get_contents(CONST_SqlDir.'/tiger_import_start.sql');
291         $sTemplate = $this->replaceSqlPatterns($sTemplate);
292
293         $this->pgsqlRunScript($sTemplate, false);
294
295         $aDBInstances = array();
296         for ($i = 0; $i < $this->iInstances; $i++) {
297             // https://secure.php.net/manual/en/function.pg-connect.php
298             $DSN = getSetting('DATABASE_DSN');
299             $DSN = preg_replace('/^pgsql:/', '', $DSN);
300             $DSN = preg_replace('/;/', ' ', $DSN);
301             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
302             pg_ping($aDBInstances[$i]);
303         }
304
305         foreach ($aFilenames as $sFile) {
306             echo $sFile.': ';
307             $hFile = fopen($sFile, 'r');
308             $sSQL = fgets($hFile, 100000);
309             $iLines = 0;
310             while (true) {
311                 for ($i = 0; $i < $this->iInstances; $i++) {
312                     if (!pg_connection_busy($aDBInstances[$i])) {
313                         while (pg_get_result($aDBInstances[$i]));
314                         $sSQL = fgets($hFile, 100000);
315                         if (!$sSQL) break 2;
316                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
317                         $iLines++;
318                         if ($iLines == 1000) {
319                             echo '.';
320                             $iLines = 0;
321                         }
322                     }
323                 }
324                 usleep(10);
325             }
326             fclose($hFile);
327
328             $bAnyBusy = true;
329             while ($bAnyBusy) {
330                 $bAnyBusy = false;
331                 for ($i = 0; $i < $this->iInstances; $i++) {
332                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
333                 }
334                 usleep(10);
335             }
336             echo "\n";
337         }
338
339         for ($i = 0; $i < $this->iInstances; $i++) {
340             pg_close($aDBInstances[$i]);
341         }
342
343         info('Creating indexes on Tiger data');
344         $sTemplate = file_get_contents(CONST_SqlDir.'/tiger_import_finish.sql');
345         $sTemplate = $this->replaceSqlPatterns($sTemplate);
346
347         $this->pgsqlRunScript($sTemplate, false);
348     }
349
350     public function calculatePostcodes($bCMDResultAll)
351     {
352         info('Calculate Postcodes');
353         $this->pgsqlRunScriptFile(CONST_SqlDir.'/postcode_tables.sql');
354
355         $sPostcodeFilename = CONST_InstallDir.'/gb_postcode_data.sql.gz';
356         if (file_exists($sPostcodeFilename)) {
357             $this->pgsqlRunScriptFile($sPostcodeFilename);
358         } else {
359             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
360         }
361
362         $sPostcodeFilename = CONST_InstallDir.'/us_postcode_data.sql.gz';
363         if (file_exists($sPostcodeFilename)) {
364             $this->pgsqlRunScriptFile($sPostcodeFilename);
365         } else {
366             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
367         }
368
369
370         $this->db()->exec('TRUNCATE location_postcode');
371
372         $sSQL  = 'INSERT INTO location_postcode';
373         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
374         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
375         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
376         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
377         $sSQL .= '  FROM placex';
378         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
379         $sSQL .= '       AND geometry IS NOT null';
380         $sSQL .= ' GROUP BY country_code, pc';
381         $this->db()->exec($sSQL);
382
383         // only add postcodes that are not yet available in OSM
384         $sSQL  = 'INSERT INTO location_postcode';
385         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
386         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
387         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
388         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
389         $sSQL .= '        (SELECT postcode FROM location_postcode';
390         $sSQL .= "          WHERE country_code = 'us')";
391         $this->db()->exec($sSQL);
392
393         // add missing postcodes for GB (if available)
394         $sSQL  = 'INSERT INTO location_postcode';
395         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
396         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
397         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
398         $sSQL .= '           (SELECT postcode FROM location_postcode';
399         $sSQL .= "             WHERE country_code = 'gb')";
400         $this->db()->exec($sSQL);
401
402         if (!$bCMDResultAll) {
403             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
404             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
405             $this->db()->exec($sSQL);
406         }
407
408         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
409         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
410         $this->db()->exec($sSQL);
411     }
412
413     public function index($bIndexNoanalyse)
414     {
415         $this->checkModulePresence(); // raises exception on failure
416
417         $oBaseCmd = (clone $this->oNominatimCmd)->addParams('index');
418
419         info('Index ranks 0 - 4');
420         $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
421
422         $iStatus = $oCmd->run();
423         if ($iStatus != 0) {
424             fail('error status ' . $iStatus . ' running nominatim!');
425         }
426         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
427
428         info('Index administrative boundaries');
429         $oCmd = (clone $oBaseCmd)->addParams('--boundaries-only');
430         $iStatus = $oCmd->run();
431         if ($iStatus != 0) {
432             fail('error status ' . $iStatus . ' running nominatim!');
433         }
434
435         info('Index ranks 5 - 25');
436         $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 5, '--maxrank', 25);
437         $iStatus = $oCmd->run();
438         if ($iStatus != 0) {
439             fail('error status ' . $iStatus . ' running nominatim!');
440         }
441
442         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
443
444         info('Index ranks 26 - 30');
445         $oCmd = (clone $oBaseCmd)->addParams('--no-boundaries', '--minrank', 26);
446         $iStatus = $oCmd->run();
447         if ($iStatus != 0) {
448             fail('error status ' . $iStatus . ' running nominatim!');
449         }
450
451         info('Index postcodes');
452         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
453         $this->db()->exec($sSQL);
454     }
455
456     public function createSearchIndices()
457     {
458         info('Create Search indices');
459
460         $sSQL = 'SELECT relname FROM pg_class, pg_index ';
461         $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
462         $aInvalidIndices = $this->db()->getCol($sSQL);
463
464         foreach ($aInvalidIndices as $sIndexName) {
465             info("Cleaning up invalid index $sIndexName");
466             $this->db()->exec("DROP INDEX $sIndexName;");
467         }
468
469         $sTemplate = file_get_contents(CONST_SqlDir.'/indices.src.sql');
470         if (!$this->bDrop) {
471             $sTemplate .= file_get_contents(CONST_SqlDir.'/indices_updates.src.sql');
472         }
473         if (!$this->dbReverseOnly()) {
474             $sTemplate .= file_get_contents(CONST_SqlDir.'/indices_search.src.sql');
475         }
476         $sTemplate = $this->replaceSqlPatterns($sTemplate);
477
478         $this->pgsqlRunScript($sTemplate);
479     }
480
481     public function createCountryNames()
482     {
483         info('Create search index for default country names');
484
485         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
486         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
487         $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');
488         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
489         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
490             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
491         $sLanguages = getSetting('LANGUAGES');
492         if ($sLanguages) {
493             $sSQL .= 'in ';
494             $sDelim = '(';
495             foreach (explode(',', $sLanguages) as $sLang) {
496                 $sSQL .= $sDelim."'name:$sLang'";
497                 $sDelim = ',';
498             }
499             $sSQL .= ')';
500         } else {
501             // all include all simple name tags
502             $sSQL .= "like 'name:%'";
503         }
504         $sSQL .= ') v';
505         $this->pgsqlRunScript($sSQL);
506     }
507
508     public function drop()
509     {
510         (clone($this->oNominatimCmd))->addParams('freeze')->run();
511     }
512
513     /**
514      * Setup the directory for the API scripts.
515      *
516      * @return null
517      */
518     public function setupWebsite()
519     {
520         (clone($this->oNominatimCmd))->addParams('refresh', '--website')->run();
521     }
522
523     /**
524      * Return the connection to the database.
525      *
526      * @return Database object.
527      *
528      * Creates a new connection if none exists yet. Otherwise reuses the
529      * already established connection.
530      */
531     private function db()
532     {
533         if (is_null($this->oDB)) {
534             $this->oDB = new \Nominatim\DB();
535             $this->oDB->connect();
536         }
537
538         return $this->oDB;
539     }
540
541     private function removeFlatnodeFile()
542     {
543         $sFName = getSetting('FLATNODE_FILE');
544         if ($sFName && file_exists($sFName)) {
545             if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
546             unlink($sFName);
547         }
548     }
549
550     private function pgsqlRunScript($sScript, $bfatal = true)
551     {
552         runSQLScript(
553             $sScript,
554             $bfatal,
555             $this->bVerbose,
556             $this->sIgnoreErrors
557         );
558     }
559
560     private function createSqlFunctions()
561     {
562         $oCmd = (clone($this->oNominatimCmd))
563                 ->addParams('refresh', '--functions');
564
565         if (!$this->bEnableDiffUpdates) {
566             $oCmd->addParams('--no-diff-updates');
567         }
568
569         if ($this->bEnableDebugStatements) {
570             $oCmd->addParams('--enable-debug-statements');
571         }
572
573         $oCmd->run();
574     }
575
576     private function pgsqlRunPartitionScript($sTemplate)
577     {
578         $sSQL = 'select distinct partition from country_name';
579         $aPartitions = $this->db()->getCol($sSQL);
580         if (!$this->bNoPartitions) $aPartitions[] = 0;
581
582         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
583         foreach ($aMatches as $aMatch) {
584             $sResult = '';
585             foreach ($aPartitions as $sPartitionName) {
586                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
587             }
588             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
589         }
590
591         $this->pgsqlRunScript($sTemplate);
592     }
593
594     private function pgsqlRunScriptFile($sFilename)
595     {
596         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
597
598         $oCmd = (new \Nominatim\Shell('psql'))
599                 ->addParams('--port', $this->aDSNInfo['port'])
600                 ->addParams('--dbname', $this->aDSNInfo['database']);
601
602         if (!$this->bVerbose) {
603             $oCmd->addParams('--quiet');
604         }
605         if (isset($this->aDSNInfo['hostspec'])) {
606             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
607         }
608         if (isset($this->aDSNInfo['username'])) {
609             $oCmd->addParams('--username', $this->aDSNInfo['username']);
610         }
611         if (isset($this->aDSNInfo['password'])) {
612             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
613         }
614         $ahGzipPipes = null;
615         if (preg_match('/\\.gz$/', $sFilename)) {
616             $aDescriptors = array(
617                              0 => array('pipe', 'r'),
618                              1 => array('pipe', 'w'),
619                              2 => array('file', '/dev/null', 'a')
620                             );
621             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
622
623             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
624             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
625             $aReadPipe = $ahGzipPipes[1];
626             fclose($ahGzipPipes[0]);
627         } else {
628             $oCmd->addParams('--file', $sFilename);
629             $aReadPipe = array('pipe', 'r');
630         }
631         $aDescriptors = array(
632                          0 => $aReadPipe,
633                          1 => array('pipe', 'w'),
634                          2 => array('file', '/dev/null', 'a')
635                         );
636         $ahPipes = null;
637
638         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
639         if (!is_resource($hProcess)) fail('unable to start pgsql');
640         // TODO: error checking
641         while (!feof($ahPipes[1])) {
642             echo fread($ahPipes[1], 4096);
643         }
644         fclose($ahPipes[1]);
645         $iReturn = proc_close($hProcess);
646         if ($iReturn > 0) {
647             fail("pgsql returned with error code ($iReturn)");
648         }
649         if ($ahGzipPipes) {
650             fclose($ahGzipPipes[1]);
651             proc_close($hGzipProcess);
652         }
653     }
654
655     private function replaceSqlPatterns($sSql)
656     {
657         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
658
659         $aPatterns = array(
660                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
661                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
662                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
663                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
664                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
665                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
666         );
667
668         foreach ($aPatterns as $sPattern => $sTablespace) {
669             if ($sTablespace) {
670                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
671             } else {
672                 $sSql = str_replace($sPattern, '', $sSql);
673             }
674         }
675
676         return $sSql;
677     }
678
679     /**
680      * Drop table with the given name if it exists.
681      *
682      * @param string $sName Name of table to remove.
683      *
684      * @return null
685      */
686     private function dropTable($sName)
687     {
688         if ($this->bVerbose) echo "Dropping table $sName\n";
689         $this->db()->deleteTable($sName);
690     }
691
692     /**
693      * Check if the database is in reverse-only mode.
694      *
695      * @return True if there is no search_name table and infrastructure.
696      */
697     private function dbReverseOnly()
698     {
699         return !($this->db()->tableExists('search_name'));
700     }
701
702     /**
703      * Try accessing the C module, so we know early if something is wrong.
704      *
705      * Raises Nominatim\DatabaseError on failure
706      */
707     private function checkModulePresence()
708     {
709         $sModulePath = getSetting('DATABASE_MODULE_PATH', CONST_InstallDir.'/module');
710         $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
711         $sSQL .= $sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
712         $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
713
714         $oDB = new \Nominatim\DB();
715         $oDB->connect();
716         $oDB->exec($sSQL, null, 'Database server failed to load '.$sModulePath.'/nominatim.so module');
717     }
718 }