4 require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5 ini_set('memory_limit', '800M');
8 "Create and setup nominatim search system",
9 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
10 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
11 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
13 array('osm-file', '', 0, 1, 1, 1, 'realpath', 'File to import'),
14 array('threads', '', 0, 1, 1, 1, 'int', 'Number of threads (where possible)'),
16 array('all', '', 0, 1, 0, 0, 'bool', 'Do the complete process'),
18 array('create-db', '', 0, 1, 0, 0, 'bool', 'Create nominatim db'),
19 array('setup-db', '', 0, 1, 0, 0, 'bool', 'Build a blank nominatim db'),
20 array('import-data', '', 0, 1, 0, 0, 'bool', 'Import a osm file'),
21 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
22 array('create-functions', '', 0, 1, 0, 0, 'bool', 'Create functions'),
23 array('enable-diff-updates', '', 0, 1, 0, 0, 'bool', 'Turn on the code required to make diff updates work'),
24 array('enable-debug-statements', '', 0, 1, 0, 0, 'bool', 'Include debug warning statements in pgsql commands'),
25 array('create-minimal-tables', '', 0, 1, 0, 0, 'bool', 'Create minimal main tables'),
26 array('create-tables', '', 0, 1, 0, 0, 'bool', 'Create main tables'),
27 array('create-partitions', '', 0, 1, 0, 0, 'bool', 'Create required partition tables and triggers'),
28 array('import-wikipedia-articles', '', 0, 1, 0, 0, 'bool', 'Import wikipedia article dump'),
29 array('load-data', '', 0, 1, 0, 0, 'bool', 'Copy data to live tables from import table'),
30 array('disable-token-precalc', '', 0, 1, 0, 0, 'bool', 'Disable name precalculation (EXPERT)'),
31 array('import-tiger-data', '', 0, 1, 0, 0, 'bool', 'Import tiger data (not included in \'all\')'),
32 array('calculate-postcodes', '', 0, 1, 0, 0, 'bool', 'Calculate postcode centroids'),
33 array('create-roads', '', 0, 1, 0, 0, 'bool', 'Calculate postcode centroids'),
34 array('osmosis-init', '', 0, 1, 0, 0, 'bool', 'Generate default osmosis configuration'),
35 array('osmosis-init-date', '', 0, 1, 1, 1, 'string', 'Generate default osmosis configuration'),
36 array('index', '', 0, 1, 0, 0, 'bool', 'Index the data'),
37 array('index-noanalyse', '', 0, 1, 0, 0, 'bool', 'Do not perform analyse operations during index (EXPERT)'),
38 array('index-output', '', 0, 1, 1, 1, 'string', 'File to dump index information to'),
39 array('create-search-indices', '', 0, 1, 0, 0, 'bool', 'Create additional indices required for search and update'),
40 array('create-website', '', 0, 1, 1, 1, 'realpath', 'Create symlinks to setup web directory'),
42 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
44 $bDidSomething = false;
46 // Check if osm-file is set and points to a valid file if --all or --import-data is given
47 if ($aCMDResult['import-data'] || $aCMDResult['all'])
49 if (!isset($aCMDResult['osm-file']))
51 fail('missing --osm-file for data import');
54 if (!file_exists($aCMDResult['osm-file']))
56 fail('the path supplied to --osm-file does not exist');
59 if (!is_readable($aCMDResult['osm-file']))
61 fail('osm-file "'.$aCMDResult['osm-file'].'" not readable');
66 // This is a pretty hard core default - the number of processors in the box - 1
67 $iInstances = isset($aCMDResult['threads'])?$aCMDResult['threads']:(getProcessorCount()-1);
71 echo "WARNING: resetting threads to $iInstances\n";
73 if ($iInstances > getProcessorCount())
75 $iInstances = getProcessorCount();
76 echo "WARNING: resetting threads to $iInstances\n";
79 // Assume we can steal all the cache memory in the box (unless told otherwise)
80 $iCacheMemory = (isset($aCMDResult['osm2pgsql-cache'])?$aCMDResult['osm2pgsql-cache']:getCacheMemoryMB());
81 if ($iCacheMemory > getTotalMemoryMB())
83 $iCacheMemory = getCacheMemoryMB();
84 echo "WARNING: resetting cache memory to $iCacheMemory\n";
87 if (isset($aCMDResult['osm-file']) && !isset($aCMDResult['osmosis-init-date']))
89 $sBaseFile = basename($aCMDResult['osm-file']);
90 if (preg_match('#^planet-([0-9]{2})([0-9]{2})([0-9]{2})[.]#', $sBaseFile, $aMatch))
92 $iTime = mktime(0, 0, 0, $aMatch[2], $aMatch[3], '20'.$aMatch[1]);
94 $aCMDResult['osmosis-init-date'] = date('Y-m-d', $iTime).'T22:00:00Z';
97 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
98 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
100 if ($aCMDResult['create-db'] || $aCMDResult['all'])
103 $bDidSomething = true;
104 $oDB =& DB::connect(CONST_Database_DSN, false);
105 if (!PEAR::isError($oDB))
107 fail('database already exists ('.CONST_Database_DSN.')');
109 passthru('createdb -E UTF-8 '.$aDSNInfo['database']);
112 if ($aCMDResult['setup-db'] || $aCMDResult['all'])
115 $bDidSomething = true;
116 // TODO: path detection, detection memory, etc.
119 passthru('createlang plpgsql '.$aDSNInfo['database']);
120 $pgver = (float) CONST_Postgresql_Version;
122 pgsqlRunScriptFile(CONST_Path_Postgresql_Contrib.'/hstore.sql');
124 pgsqlRunScript('CREATE EXTENSION hstore');
126 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/postgis.sql');
127 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/spatial_ref_sys.sql');
128 pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
129 pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
130 pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql');
131 pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode.sql');
132 pgsqlRunScriptFile(CONST_BasePath.'/data/us_statecounty.sql');
133 pgsqlRunScriptFile(CONST_BasePath.'/data/us_state.sql');
134 pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
135 pgsqlRunScriptFile(CONST_BasePath.'/data/worldboundaries.sql');
138 if ($aCMDResult['import-data'] || $aCMDResult['all'])
141 $bDidSomething = true;
143 $osm2pgsql = CONST_Osm2pgsql_Binary;
144 if (!file_exists($osm2pgsql))
146 echo "Please download and build osm2pgsql.\nIf it is already installed, check the path in your local settings (settings/local.php) file.\n";
147 fail("osm2pgsql not found in '$osm2pgsql'");
149 $osm2pgsql .= ' -lsc -O gazetteer --hstore';
150 $osm2pgsql .= ' -C '.$iCacheMemory;
151 $osm2pgsql .= ' -d '.$aDSNInfo['database'].' '.$aCMDResult['osm-file'];
152 passthruCheckReturn($osm2pgsql);
155 $x = $oDB->getRow('select * from place limit 1');
156 if (PEAR::isError($x)) {
157 fail($x->getMessage());
159 if (!$x) fail('No Data');
162 if ($aCMDResult['create-functions'] || $aCMDResult['all'])
165 $bDidSomething = true;
166 if (!file_exists(CONST_BasePath.'/module/nominatim.so')) fail("nominatim module not built");
167 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
168 $sTemplate = str_replace('{modulepath}', CONST_BasePath.'/module', $sTemplate);
169 if ($aCMDResult['enable-diff-updates']) $sTemplate = str_replace('RETURN NEW; -- @DIFFUPDATES@', '--', $sTemplate);
170 if ($aCMDResult['enable-debug-statements']) $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
171 pgsqlRunScript($sTemplate);
174 if ($aCMDResult['create-minimal-tables'])
176 echo "Minimal Tables\n";
177 $bDidSomething = true;
178 pgsqlRunScriptFile(CONST_BasePath.'/sql/tables-minimal.sql');
182 // Backstop the import process - easliest possible import id
183 $sScript .= "insert into import_npi_log values (18022);\n";
185 $hFile = @fopen(CONST_BasePath.'/settings/partitionedtags.def', "r");
186 if (!$hFile) fail('unable to open list of partitions: '.CONST_BasePath.'/settings/partitionedtags.def');
188 while (($sLine = fgets($hFile, 4096)) !== false && $sLine && substr($sLine,0,1) !='#')
190 list($sClass, $sType) = explode(' ', trim($sLine));
191 $sScript .= "create table place_classtype_".$sClass."_".$sType." as ";
192 $sScript .= "select place_id as place_id,geometry as centroid from placex limit 0;\n";
194 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_centroid ";
195 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING GIST (centroid);\n";
197 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_place_id ";
198 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING btree(place_id);\n";
201 pgsqlRunScript($sScript);
204 if ($aCMDResult['create-tables'] || $aCMDResult['all'])
207 $bDidSomething = true;
208 pgsqlRunScriptFile(CONST_BasePath.'/sql/tables.sql');
210 // re-run the functions
211 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
212 $sTemplate = str_replace('{modulepath}',CONST_BasePath.'/module', $sTemplate);
213 pgsqlRunScript($sTemplate);
216 if ($aCMDResult['create-partitions'] || $aCMDResult['all'])
219 $bDidSomething = true;
221 $sSQL = 'select partition from country_name order by country_code';
222 $aPartitions = $oDB->getCol($sSQL);
223 if (PEAR::isError($aPartitions))
225 fail($aPartitions->getMessage());
229 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partitions.src.sql');
230 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
231 foreach($aMatches as $aMatch)
234 foreach($aPartitions as $sPartitionName)
236 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
238 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
241 pgsqlRunScript($sTemplate);
244 if ($aCMDResult['import-wikipedia-articles'] || $aCMDResult['all'])
246 $bDidSomething = true;
247 $sWikiArticlesFile = CONST_BasePath.'/data/wikipedia_article.sql.bin';
248 $sWikiRedirectsFile = CONST_BasePath.'/data/wikipedia_redirect.sql.bin';
249 if (file_exists($sWikiArticlesFile))
251 echo "Importing wikipedia articles...";
252 pgsqlRunDropAndRestore($sWikiArticlesFile);
257 echo "WARNING: wikipedia article dump file not found - places will have default importance\n";
259 if (file_exists($sWikiRedirectsFile))
261 echo "Importing wikipedia redirects...";
262 pgsqlRunDropAndRestore($sWikiRedirectsFile);
267 echo "WARNING: wikipedia redirect dump file not found - some place importance values may be missing\n";
272 if ($aCMDResult['load-data'] || $aCMDResult['all'])
275 $bDidSomething = true;
278 if (!pg_query($oDB->connection, 'TRUNCATE word')) fail(pg_last_error($oDB->connection));
280 if (!pg_query($oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($oDB->connection));
282 if (!pg_query($oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($oDB->connection));
284 if (!pg_query($oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($oDB->connection));
286 if (!pg_query($oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($oDB->connection));
288 if (!pg_query($oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($oDB->connection));
290 if (!pg_query($oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($oDB->connection));
292 if (!pg_query($oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($oDB->connection));
294 if (!pg_query($oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($oDB->connection));
297 $sSQL = 'select partition from country_name order by country_code';
298 $aPartitions = $oDB->getCol($sSQL);
299 if (PEAR::isError($aPartitions))
301 fail($aPartitions->getMessage());
304 foreach($aPartitions as $sPartition)
306 if (!pg_query($oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($oDB->connection));
310 // pre-create the word list
311 if (!$aCMDResult['disable-token-precalc'])
313 if (!pg_query($oDB->connection, 'select count(make_keywords(v)) from (select distinct svals(name) as v from place) as w where v is not null;')) fail(pg_last_error($oDB->connection));
315 if (!pg_query($oDB->connection, 'select count(make_keywords(v)) from (select distinct postcode as v from place) as w where v is not null;')) fail(pg_last_error($oDB->connection));
317 if (!pg_query($oDB->connection, 'select count(getorcreate_housenumber_id(v)) from (select distinct housenumber as v from place where housenumber is not null) as w;')) fail(pg_last_error($oDB->connection));
321 $aDBInstances = array();
322 for($i = 0; $i < $iInstances; $i++)
324 $aDBInstances[$i] =& getDB(true);
325 $sSQL = 'insert into placex (osm_type, osm_id, class, type, name, admin_level, ';
326 $sSQL .= 'housenumber, street, isin, postcode, country_code, extratags, ';
327 $sSQL .= 'geometry) select * from place where osm_id % '.$iInstances.' = '.$i;
328 if ($aCMDResult['verbose']) echo "$sSQL\n";
329 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
335 for($i = 0; $i < $iInstances; $i++)
337 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
343 echo "Reanalysing database...\n";
344 pgsqlRunScript('ANALYSE');
347 if ($aCMDResult['create-roads'])
349 $bDidSomething = true;
352 $aDBInstances = array();
353 for($i = 0; $i < $iInstances; $i++)
355 $aDBInstances[$i] =& getDB(true);
356 if (!pg_query($aDBInstances[$i]->connection, 'set enable_bitmapscan = off')) fail(pg_last_error($oDB->connection));
357 $sSQL = 'select count(*) from (select insertLocationRoad(partition, place_id, country_code, geometry) from ';
358 $sSQL .= 'placex where osm_id % '.$iInstances.' = '.$i.' and rank_search between 26 and 27 and class = \'highway\') as x ';
359 if ($aCMDResult['verbose']) echo "$sSQL\n";
360 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
366 for($i = 0; $i < $iInstances; $i++)
368 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
376 if ($aCMDResult['import-tiger-data'])
378 $bDidSomething = true;
380 pgsqlRunScriptFile(CONST_BasePath.'/sql/tiger_import_start.sql');
382 $aDBInstances = array();
383 for($i = 0; $i < $iInstances; $i++)
385 $aDBInstances[$i] =& getDB(true);
388 foreach(glob(CONST_BasePath.'/data/tiger2011/*.sql') as $sFile)
391 $hFile = fopen($sFile, "r");
392 $sSQL = fgets($hFile, 100000);
397 for($i = 0; $i < $iInstances; $i++)
399 if (!pg_connection_busy($aDBInstances[$i]->connection))
401 while(pg_get_result($aDBInstances[$i]->connection));
402 $sSQL = fgets($hFile, 100000);
404 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
422 for($i = 0; $i < $iInstances; $i++)
424 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
431 echo "Creating indexes\n";
432 pgsqlRunScriptFile(CONST_BasePath.'/sql/tiger_import_finish.sql');
435 if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all'])
437 $bDidSomething = true;
439 if (!pg_query($oDB->connection, 'DELETE from placex where osm_type=\'P\'')) fail(pg_last_error($oDB->connection));
440 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,country_code,geometry) ";
441 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,country_code,";
442 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from (select country_code,postcode,";
443 $sSQL .= "avg(st_x(st_centroid(geometry))) as x,avg(st_y(st_centroid(geometry))) as y ";
444 $sSQL .= "from placex where postcode is not null group by country_code,postcode) as x";
445 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
447 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,country_code,geometry) ";
448 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,'us',";
449 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from us_postcode";
450 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
453 if (($aCMDResult['osmosis-init'] || $aCMDResult['all']) && isset($aCMDResult['osmosis-init-date']))
455 $bDidSomething = true;
458 if (!file_exists(CONST_Osmosis_Binary)) fail("please download osmosis");
459 if (file_exists(CONST_BasePath.'/settings/configuration.txt')) echo "settings/configuration.txt already exists\n";
462 passthru(CONST_Osmosis_Binary.' --read-replication-interval-init '.CONST_BasePath.'/settings');
463 // server layout changed afer license change, fix path to minutely diffs
464 passthru("sed -i 's:minute-replicate:replication/minute:' ".CONST_BasePath.'/settings/configuration.txt');
467 $sDate = $aCMDResult['osmosis-init-date'];
468 $aDate = date_parse_from_format("Y-m-d\TH-i", $sDate);
469 $sURL = 'http://toolserver.org/~mazder/replicate-sequences/?';
470 $sURL .= 'Y='.$aDate['year'].'&m='.$aDate['month'].'&d='.$aDate['day'];
471 $sURL .= '&H='.$aDate['hour'].'&i='.$aDate['minute'].'&s=0';
472 $sURL .= '&stream=minute';
473 echo "Getting state file: $sURL\n";
474 $sStateFile = file_get_contents($sURL);
475 if (!$sStateFile || strlen($sStateFile) > 1000) fail("unable to obtain state file");
476 file_put_contents(CONST_BasePath.'/settings/state.txt', $sStateFile);
477 echo "Updating DB status\n";
478 pg_query($oDB->connection, 'TRUNCATE import_status');
479 $sSQL = "INSERT INTO import_status VALUES('".$sDate."')";
480 pg_query($oDB->connection, $sSQL);
484 if ($aCMDResult['index'] || $aCMDResult['all'])
486 $bDidSomething = true;
488 if (isset($aCMDResult['index-output'])) $sOutputFile = ' -F '.$aCMDResult['index-output'];
489 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -t '.$iInstances.$sOutputFile;
490 passthruCheckReturn($sBaseCmd.' -R 4');
491 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
492 passthruCheckReturn($sBaseCmd.' -r 5 -R 25');
493 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
494 passthruCheckReturn($sBaseCmd.' -r 26');
497 if ($aCMDResult['create-search-indices'] || $aCMDResult['all'])
499 echo "Search indices\n";
500 $bDidSomething = true;
502 $sSQL = 'select partition from country_name order by country_code';
503 $aPartitions = $oDB->getCol($sSQL);
504 if (PEAR::isError($aPartitions))
506 fail($aPartitions->getMessage());
510 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
511 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
512 foreach($aMatches as $aMatch)
515 foreach($aPartitions as $sPartitionName)
517 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
519 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
522 pgsqlRunScript($sTemplate);
525 if (isset($aCMDResult['create-website']))
527 $bDidSomething = true;
528 $sTargetDir = $aCMDResult['create-website'];
529 if (!is_dir($sTargetDir))
531 echo "You must create the website directory before calling this function.\n";
532 fail("Target directory does not exist.");
535 @symlink(CONST_BasePath.'/website/details.php', $sTargetDir.'/details.php');
536 @symlink(CONST_BasePath.'/website/reverse.php', $sTargetDir.'/reverse.php');
537 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/search.php');
538 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/index.php');
539 @symlink(CONST_BasePath.'/website/images', $sTargetDir.'/images');
540 @symlink(CONST_BasePath.'/website/js', $sTargetDir.'/js');
541 echo "Symlinks created\n";
546 showUsage($aCMDOptions, true);
549 function pgsqlRunScriptFile($sFilename)
551 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
553 // Convert database DSN to psql parameters
554 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
555 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
556 $sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -f '.$sFilename;
558 $aDescriptors = array(
559 0 => array('pipe', 'r'),
560 1 => array('pipe', 'w'),
561 2 => array('file', '/dev/null', 'a')
564 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
565 if (!is_resource($hProcess)) fail('unable to start pgsql');
569 // TODO: error checking
570 while(!feof($ahPipes[1]))
572 echo fread($ahPipes[1], 4096);
576 proc_close($hProcess);
579 function pgsqlRunScript($sScript)
581 // Convert database DSN to psql parameters
582 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
583 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
584 $sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'];
585 $aDescriptors = array(
586 0 => array('pipe', 'r'),
591 $hProcess = @proc_open($sCMD, $aDescriptors, $ahPipes);
592 if (!is_resource($hProcess)) fail('unable to start pgsql');
594 while(strlen($sScript))
596 $written = fwrite($ahPipes[0], $sScript);
597 $sScript = substr($sScript, $written);
600 proc_close($hProcess);
603 function pgsqlRunRestoreData($sDumpFile)
605 // Convert database DSN to psql parameters
606 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
607 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
608 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc -a '.$sDumpFile;
610 $aDescriptors = array(
611 0 => array('pipe', 'r'),
612 1 => array('pipe', 'w'),
613 2 => array('file', '/dev/null', 'a')
616 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
617 if (!is_resource($hProcess)) fail('unable to start pg_restore');
621 // TODO: error checking
622 while(!feof($ahPipes[1]))
624 echo fread($ahPipes[1], 4096);
628 proc_close($hProcess);
631 function pgsqlRunDropAndRestore($sDumpFile)
633 // Convert database DSN to psql parameters
634 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
635 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
636 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
638 $aDescriptors = array(
639 0 => array('pipe', 'r'),
640 1 => array('pipe', 'w'),
641 2 => array('file', '/dev/null', 'a')
644 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
645 if (!is_resource($hProcess)) fail('unable to start pg_restore');
649 // TODO: error checking
650 while(!feof($ahPipes[1]))
652 echo fread($ahPipes[1], 4096);
656 proc_close($hProcess);
659 function passthruCheckReturn($cmd)
662 passthru($cmd, $result);
663 if ($result != 0) fail('Error executing external command: '.$cmd);