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