5 * This should allow you to dump a series of data, so it could be restored later...
6 * The format will be an SQL file...
9 * php index.php Admin/Dump --table=Project --where="id=123"
10 * --dump-dir=/directory_to_put_sql+shell files
12 * outputs list of generated files.
15 * {DATE}.sql - the recreate sql including all dependancies, run with mysql DB -f < ....
16 * {DATE}.restore.sh - shell script to recreate files that where removed (excluding thumgs)
19 * {DATE}.copy.sh - shell script that backs up all the related files.
22 * {DATE}.delete.sql - the delete data sql.
23 * {DATE}.delete.sh - shell script to delete the files related to these records
26 * Basically it has to output all the records and their dependants. (parent and children)
28 * Then when deleting it deletes record + children..
31 * Each ouput is simple insert statement..
34 * TODO - handle Images table (or similar) where we use tablename=XXXX, tid=.... etc..
39 * DataObjects->archivePaths() - returns array ( sourcedirectory, remainder of path to dependant file )
40 * DataObjects->listThumbs() - returns array ( list of full path to thumbnail urls. )
49 require_once 'Pman.php';
51 class Pman_Admin_Dump extends Pman {
56 if (!HTML_FlexyFramework::get()->cli) {
57 die("Access only permitted from cli");
62 var $deps = array(); // list of dependants
63 var $out = array(); // list of created sql/shell scripts.
67 ini_set('memory_limit', '256M'); // we need alot of memory
70 $argv = $_SERVER['argv'];
74 $opts = explode(',', 'table==,where==,dump-dir==,dump-dir==,debug=');
75 require_once 'Console/Getopt.php';
76 $go = Console_Getopt::getopt2($argv, '', $opts );
81 foreach($go[0] as $ar) {
82 $args[substr($ar[0],2)] = $ar[1];
85 foreach($opts as $req) {
86 if (substr($req,-2, 2) != '==') { // skip optional arguments
89 if (empty($args[substr($req,0, -2)])) {
90 $errs[] = "--".substr($req,0, -2) . ' is required';
94 die(print_R($errs,true));
96 if (!empty($args['debug'])) {
97 DB_DataObject::debugLevel($args['debug']);
100 $this->out = array();
101 $this->discoverChildren($this->args['table'], $this->args['where'], true);
102 //print_R($this->deletes);
103 //print_r($this->dumps);
106 $this->discover($this->args['table'], $this->args['where'], true);
109 if (!file_exists($args['dump-dir'])) {
110 mkdir($args['dump-dir'], 0777, true);
113 $this->generateInsert();
114 $this->generateDelete();
115 $this->generateShell();
118 foreach($this->deletes as $tbl => $ar) {
119 if (empty($ar)) { continue; }
120 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
123 foreach($this->dumps as $tbl => $ar) {
124 if (empty($ar)) { continue; }
125 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
128 echo " Total : ". count($this->childfiles) . " using " . floor($this->filesize/1000000) . "Mb\n";
130 echo "GENERATED FILES:\n";
132 echo " ". implode("\n ", $this->out). "\n";
141 var $deletes = array(); // TABLE => [key] => TRUE|FALSE
142 var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
143 var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
144 var $childfiles = array(); // array of [ 'sourcedirectory' , 'subdirectory(s) and filename' ]
145 var $childthumbs = array(); // array of [ 'filename', 'filename' ,......]
146 var $filesize = 0; // size of files to be saved. (not total deletd..)
149 * a) what depends on it (eg. child elements) - which will be deleted.
150 * b) what it depends on it (eg. parent elements) - which will be dumped..
153 function discover($table, $where, $is_delete = false )
156 if (!isset($this->dumps[$table])) {
157 $this->dumps[$table] = array();
159 if ($is_delete && !isset($this->deletes[$table])) {
160 $this->deletes[$table] = array();
162 //DB_DataObject::debugLevel(1);
163 $x = DB_DataObject::factory($table);
164 if (PEAR::isError($x)) {
165 if (isset($this->dumps[$table])) {
166 unset($this->dumps[$table]); // links to non-existant tables..
173 if (is_array( $where)) {
174 $x->whereAddIn($keys[0] , $where, 'int');
177 $x->whereAdd($where);
180 // a) id's of elements in this table
181 // b) columns which point to other tables..
182 $links = $x->links();
183 $cols = array_keys($links);
185 array_push($cols, $keys[0]);
189 $x->selectAdd('`'. implode('`,`', $cols) . '`');
191 //DB_DataObject::debugLevel(0);
192 while ($x->fetch()) {
193 foreach($cols as $k) {
194 if (empty($x->$k)) { // skip blanks.
197 if (isset($links[$k])) {
199 $kv = explode(':', $links[$k]);
200 if (!isset($this->dumps[$kv[0]])) {
201 $this->dumps[$kv[0]] = array();
203 if (!isset($this->dumps[$kv[0]][$x->$k])) {
204 $this->dumps[$kv[0]][$x->$k] = 0; // not checked yet..
208 // assume it's the key..
209 if (empty($this->dumps[$table][$x->$k])) {
210 $this->dumps[$table][$x->$k] = 1; // we have checked this one...
212 //if ($is_delete && !isset($this->deletes[$table][$x->$k])) {
214 // $this->deletes[$table][$x->$k] = 0 ; // not checked yet..
222 // flag as checked if we where given an array.. - as some links might have been broken.
223 if (is_array($where)) {
224 foreach($where as $k) {
225 $this->dumps[$table][$k] = 1;
230 // itterate through dumps to find what needs discovering
231 foreach($this->dumps as $k=>$v) {
233 foreach($v as $id => $fetched) {
239 $this->discover($k, $ar,false);
251 function discoverChildren($table, $where, $col=false )
253 echo "discoverChildren:$table:$col:". (is_array($where) ? (count($where) . " children" ): $where ). "\n";
254 global $_DB_DATAOBJECT;
255 $do = DB_DataObject::factory($table);
256 if (PEAR::isError($do)) {
257 if (isset($this->dumps[$table])) {
258 unset($this->dumps[$table]); // links to non-existant tables..
260 echo "SKIPPING invalid table $table\n";
263 if (!isset($this->dumps[$table])) {
264 $this->dumps[$table] = array();
266 if (!isset($this->deletes[$table])) {
267 $this->deletes[$table] = array();
273 if (is_array( $where)) {
274 $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
277 $do->whereAdd($where);
280 static $children = array();
282 if (!isset($children[$table])) {
283 $children[$table] = array();
284 // force load of linsk
286 foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
287 // hack.. - we should get rid of this hack..
288 if ($tbl == 'database__render') {
291 //if ($tbl == $tn) { // skip same table
294 foreach ($links as $tk => $kv) {
297 list($k,$v) = explode(':', $kv);
301 $add = implode(':', array($tbl, $tk));
302 //echo "ADD $tbl $tk=>$kv : $add\n";
303 $children[$table][$add] = true;
313 $do->selectAdd($key);
314 echo "GOT ". $do->find() ." results\n";
315 //DB_DataObject::debugLevel(0);
316 while ($do->fetch()) {
317 $this->dumps[$table][$do->$key] = 0;
318 if (!isset($this->deletes[$table][$do->$key])) {
319 $this->deletes[$table][$do->$key] = 0;
322 foreach($children[$table] as $kv=>$t) {
323 if (!isset($this->dscan[$kv])) {
324 $this->dscan[$kv] = array();
326 if (!isset($this->dscan[$kv][$do->$key])) {
327 $this->dscan[$kv][$do->$key]= 0; // unscanned.
333 // now iterate throught dependants. and scan them.
336 foreach($this->dscan as $kv => $ids) {
338 foreach($ids as $id => $checked) {
340 $this->dscan[$kv][$id] = 1; // flag it as checked.
349 list($k, $v) = explode(':', $kv);
350 $this->discoverChildren($k, $ar, $v);
359 function generateDelete() {
360 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
361 $this->out[] = $target;
362 $fh = fopen($target, 'w');
366 foreach($this->deletes as $tbl=>$ar) {
368 $do = DB_DataObject::factory($tbl);
369 $tbl = $do->tableName();
372 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
374 $archivePaths = method_exists($do,'archivePaths');
375 $listThumbs = method_exists($do,'listThumbs');
376 while ($do->fetch()) {
379 $ct = $do->archivePaths();
381 $this->childfiles[] = $ct;
385 $ct = $do->listThumbs();
387 $this->childthumbs[] = $ct;
392 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
398 function generateShell() {
400 if (empty($this->childfiles) && empty($this->childthumbs)) {
403 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
404 $this->out[] = $target;
405 $fh = fopen($target, 'w');
407 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
408 $this->out[] = $target;
409 $fh2 = fopen($target, 'w');
411 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
412 $this->out[] = $target;
413 $fh3 = fopen($target, 'w');
416 foreach($this->childfiles as $v) {
417 $fs += filesize($v[0].'/'.$v[1]);
418 fwrite($fh,"mkdir -p " . escapeshellarg(dirname($this->args['dump-dir'] .'/'.$v[1])) ."\n" );
419 fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) ."\n" );
421 fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
422 fwrite($fh3,"cp " . escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
424 fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
427 fclose($fh3); // restore does not need to bother with thumbnails.
429 $this->filesize = $fs;
432 foreach($this->childthumbs as $v) {
434 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
440 function generateInsert()
442 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
443 $this->out[] = $target;
444 $fh = fopen($target,'w');
448 foreach($this->dumps as $tbl => $ar) {
452 $do = DB_DataObject::factory($tbl);
456 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
458 while ($do->fetch()) {
459 fwrite($fh,$this->toInsert($do));
472 * toInsert - does not handle NULLS...
474 function toInsert($do)
476 $kcol = array_shift($do->keys());
478 // for auto_inc column we need to use a 'set argument'...
479 $items = $do->table();
486 $table = $do->tableName();
489 foreach( $items as $k=>$v)
496 $leftq .= '`' . $k . '`';
501 if ($v & DB_DATAOBJECT_STR) {
502 $rightq .= $do->_quote((string) (
503 ($v & DB_DATAOBJECT_BOOL) ?
504 // this is thanks to the braindead idea of postgres to
505 // use t/f for boolean.
506 (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :
511 if (is_numeric($do->$k)) {
512 $rightq .=" {$do->$k} ";
515 $rightq .= ' ' . intval($do->$k) . ' ';
518 return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";