3 namespace Nominatim\Setup;
5 require_once(CONST_LibDir.'/Shell.php');
13 protected $sIgnoreErrors;
14 protected $bEnableDiffUpdates;
15 protected $bEnableDebugStatements;
17 protected $oDB = null;
18 protected $oNominatimCmd;
20 public function __construct(array $aCMDResult)
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);
27 if ($this->iInstances < 1) {
28 $this->iInstances = 1;
29 warn('resetting threads to '.$this->iInstances);
32 // parse database string
33 $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
34 if (!isset($this->aDSNInfo['port'])) {
35 $this->aDSNInfo['port'] = 5432;
38 // setting member variables based on command line options stored in $aCMDResult
39 $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
40 $this->bVerbose = $aCMDResult['verbose'];
42 //setting default values which are not set by the update.php array
43 if (isset($aCMDResult['ignore-errors'])) {
44 $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
46 $this->sIgnoreErrors = false;
48 if (isset($aCMDResult['enable-debug-statements'])) {
49 $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
51 $this->bEnableDebugStatements = false;
53 if (isset($aCMDResult['enable-diff-updates'])) {
54 $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
56 $this->bEnableDiffUpdates = false;
59 $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
61 $this->oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
63 $this->oNominatimCmd->addParams('--quiet');
65 if ($this->bVerbose) {
66 $this->oNominatimCmd->addParams('--verbose');
70 public function calculatePostcodes($bCMDResultAll)
72 info('Calculate Postcodes');
73 $this->pgsqlRunScriptFile(CONST_SqlDir.'/postcode_tables.sql');
75 $sPostcodeFilename = CONST_InstallDir.'/gb_postcode_data.sql.gz';
76 if (file_exists($sPostcodeFilename)) {
77 $this->pgsqlRunScriptFile($sPostcodeFilename);
79 warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
82 $sPostcodeFilename = CONST_InstallDir.'/us_postcode_data.sql.gz';
83 if (file_exists($sPostcodeFilename)) {
84 $this->pgsqlRunScriptFile($sPostcodeFilename);
86 warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
90 $this->db()->exec('TRUNCATE location_postcode');
92 $sSQL = 'INSERT INTO location_postcode';
93 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
94 $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
95 $sSQL .= " upper(trim (both ' ' from address->'postcode')) as pc,";
96 $sSQL .= ' ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
97 $sSQL .= ' FROM placex';
98 $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
99 $sSQL .= ' AND geometry IS NOT null';
100 $sSQL .= ' GROUP BY country_code, pc';
101 $this->db()->exec($sSQL);
103 // only add postcodes that are not yet available in OSM
104 $sSQL = 'INSERT INTO location_postcode';
105 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
106 $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
107 $sSQL .= ' ST_SetSRID(ST_Point(x,y),4326)';
108 $sSQL .= ' FROM us_postcode WHERE postcode NOT IN';
109 $sSQL .= ' (SELECT postcode FROM location_postcode';
110 $sSQL .= " WHERE country_code = 'us')";
111 $this->db()->exec($sSQL);
113 // add missing postcodes for GB (if available)
114 $sSQL = 'INSERT INTO location_postcode';
115 $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
116 $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
117 $sSQL .= ' FROM gb_postcode WHERE postcode NOT IN';
118 $sSQL .= ' (SELECT postcode FROM location_postcode';
119 $sSQL .= " WHERE country_code = 'gb')";
120 $this->db()->exec($sSQL);
122 if (!$bCMDResultAll) {
123 $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
124 $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
125 $this->db()->exec($sSQL);
128 $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
129 $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
130 $this->db()->exec($sSQL);
133 public function createCountryNames()
135 info('Create search index for default country names');
137 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
138 $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
139 $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');
140 $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
141 $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
142 .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
143 $sLanguages = getSetting('LANGUAGES');
147 foreach (explode(',', $sLanguages) as $sLang) {
148 $sSQL .= $sDelim."'name:$sLang'";
153 // all include all simple name tags
154 $sSQL .= "like 'name:%'";
157 $this->pgsqlRunScript($sSQL);
161 * Return the connection to the database.
163 * @return Database object.
165 * Creates a new connection if none exists yet. Otherwise reuses the
166 * already established connection.
168 private function db()
170 if (is_null($this->oDB)) {
171 $this->oDB = new \Nominatim\DB();
172 $this->oDB->connect();
178 private function pgsqlRunScript($sScript, $bfatal = true)
188 public function createSqlFunctions()
190 $oCmd = (clone($this->oNominatimCmd))
191 ->addParams('refresh', '--functions');
193 if (!$this->bEnableDiffUpdates) {
194 $oCmd->addParams('--no-diff-updates');
197 if ($this->bEnableDebugStatements) {
198 $oCmd->addParams('--enable-debug-statements');
201 $oCmd->run(!$this->sIgnoreErrors);
204 private function pgsqlRunScriptFile($sFilename)
206 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
208 $oCmd = (new \Nominatim\Shell('psql'))
209 ->addParams('--port', $this->aDSNInfo['port'])
210 ->addParams('--dbname', $this->aDSNInfo['database']);
212 if (!$this->bVerbose) {
213 $oCmd->addParams('--quiet');
215 if (isset($this->aDSNInfo['hostspec'])) {
216 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
218 if (isset($this->aDSNInfo['username'])) {
219 $oCmd->addParams('--username', $this->aDSNInfo['username']);
221 if (isset($this->aDSNInfo['password'])) {
222 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
225 if (preg_match('/\\.gz$/', $sFilename)) {
226 $aDescriptors = array(
227 0 => array('pipe', 'r'),
228 1 => array('pipe', 'w'),
229 2 => array('file', '/dev/null', 'a')
231 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
233 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
234 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
235 $aReadPipe = $ahGzipPipes[1];
236 fclose($ahGzipPipes[0]);
238 $oCmd->addParams('--file', $sFilename);
239 $aReadPipe = array('pipe', 'r');
241 $aDescriptors = array(
243 1 => array('pipe', 'w'),
244 2 => array('file', '/dev/null', 'a')
248 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
249 if (!is_resource($hProcess)) fail('unable to start pgsql');
250 // TODO: error checking
251 while (!feof($ahPipes[1])) {
252 echo fread($ahPipes[1], 4096);
255 $iReturn = proc_close($hProcess);
257 fail("pgsql returned with error code ($iReturn)");
260 fclose($ahGzipPipes[1]);
261 proc_close($hGzipProcess);
265 private function replaceSqlPatterns($sSql)
267 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
270 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
271 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
272 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
273 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
274 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
275 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
278 foreach ($aPatterns as $sPattern => $sTablespace) {
280 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
282 $sSql = str_replace($sPattern, '', $sSql);