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);
134 * Return the connection to the database.
136 * @return Database object.
138 * Creates a new connection if none exists yet. Otherwise reuses the
139 * already established connection.
141 private function db()
143 if (is_null($this->oDB)) {
144 $this->oDB = new \Nominatim\DB();
145 $this->oDB->connect();
151 private function pgsqlRunScript($sScript, $bfatal = true)
161 public function createSqlFunctions()
163 $oCmd = (clone($this->oNominatimCmd))
164 ->addParams('refresh', '--functions');
166 if (!$this->bEnableDiffUpdates) {
167 $oCmd->addParams('--no-diff-updates');
170 if ($this->bEnableDebugStatements) {
171 $oCmd->addParams('--enable-debug-statements');
174 $oCmd->run(!$this->sIgnoreErrors);
177 private function pgsqlRunScriptFile($sFilename)
179 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
181 $oCmd = (new \Nominatim\Shell('psql'))
182 ->addParams('--port', $this->aDSNInfo['port'])
183 ->addParams('--dbname', $this->aDSNInfo['database']);
185 if (!$this->bVerbose) {
186 $oCmd->addParams('--quiet');
188 if (isset($this->aDSNInfo['hostspec'])) {
189 $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
191 if (isset($this->aDSNInfo['username'])) {
192 $oCmd->addParams('--username', $this->aDSNInfo['username']);
194 if (isset($this->aDSNInfo['password'])) {
195 $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
198 if (preg_match('/\\.gz$/', $sFilename)) {
199 $aDescriptors = array(
200 0 => array('pipe', 'r'),
201 1 => array('pipe', 'w'),
202 2 => array('file', '/dev/null', 'a')
204 $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
206 $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
207 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
208 $aReadPipe = $ahGzipPipes[1];
209 fclose($ahGzipPipes[0]);
211 $oCmd->addParams('--file', $sFilename);
212 $aReadPipe = array('pipe', 'r');
214 $aDescriptors = array(
216 1 => array('pipe', 'w'),
217 2 => array('file', '/dev/null', 'a')
221 $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
222 if (!is_resource($hProcess)) fail('unable to start pgsql');
223 // TODO: error checking
224 while (!feof($ahPipes[1])) {
225 echo fread($ahPipes[1], 4096);
228 $iReturn = proc_close($hProcess);
230 fail("pgsql returned with error code ($iReturn)");
233 fclose($ahGzipPipes[1]);
234 proc_close($hGzipProcess);
238 private function replaceSqlPatterns($sSql)
240 $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
243 '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
244 '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
245 '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
246 '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
247 '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
248 '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
251 foreach ($aPatterns as $sPattern => $sTablespace) {
253 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
255 $sSql = str_replace($sPattern, '', $sSql);