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 $argv = $_SERVER['argv'];
71 $opts = explode(',', 'table==,where==,dump-dir==,dump-dir==,debug=');
72 require_once 'Console/Getopt.php';
73 $go = Console_Getopt::getopt2($argv, '', $opts );
78 foreach($go[0] as $ar) {
79 $args[substr($ar[0],2)] = $ar[1];
82 foreach($opts as $req) {
83 if (substr($req,-2, 2) != '==') { // skip optional arguments
86 if (empty($args[substr($req,0, -2)])) {
87 $errs[] = "--".substr($req,0, -2) . ' is required';
91 die(print_R($errs,true));
93 if (!empty($args['debug'])) {
94 DB_DataObject::debugLevel($args['debug']);
98 $this->discoverChildren($this->args['table'], $this->args['where'], true);
99 //print_R($this->deletes);
100 //print_r($this->dumps);
103 $this->discover($this->args['table'], $this->args['where'], true);
106 if (!file_exists($args['dump-dir'])) {
107 mkdir($args['dump-dir'], 0777, true);
110 $this->generateInsert();
111 $this->generateDelete();
112 $this->generateShell();
115 foreach($this->deletes as $tbl => $ar) {
116 if (empty($ar)) { continue; }
117 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
120 foreach($this->dumps as $tbl => $ar) {
121 if (empty($ar)) { continue; }
122 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
124 echo "GENERATED FILES:\n";
126 echo " ". implode("\n ", $this->out). "\n";
135 var $deletes = array(); // TABLE => [key] => TRUE|FALSE
136 var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
137 var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
138 var $childfiles = array(); // array of [ 'sourcedirectory' , 'subdirectory(s) and filename' ]
139 var $childthumbs = array(); // array of [ 'filename', 'filename' ,......]
142 * a) what depends on it (eg. child elements) - which will be deleted.
143 * b) what it depends on it (eg. parent elements) - which will be dumped..
146 function discover($table, $where, $is_delete = false )
149 if (!isset($this->dumps[$table])) {
150 $this->dumps[$table] = array();
152 if ($is_delete && !isset($this->deletes[$table])) {
153 $this->deletes[$table] = array();
155 //DB_DataObject::debugLevel(1);
156 $x = DB_DataObject::factory($table);
157 if (PEAR::isError($x)) {
158 if (isset($this->dumps[$table])) {
159 unset($this->dumps[$table]); // links to non-existant tables..
166 if (is_array( $where)) {
167 $x->whereAddIn($keys[0] , $where, 'int');
170 $x->whereAdd($where);
173 // a) id's of elements in this table
174 // b) columns which point to other tables..
175 $links = $x->links();
176 $cols = array_keys($links);
178 array_push($cols, $keys[0]);
182 $x->selectAdd('`'. implode('`,`', $cols) . '`');
184 //DB_DataObject::debugLevel(0);
185 while ($x->fetch()) {
186 foreach($cols as $k) {
187 if (empty($x->$k)) { // skip blanks.
190 if (isset($links[$k])) {
192 $kv = explode(':', $links[$k]);
193 if (!isset($this->dumps[$kv[0]])) {
194 $this->dumps[$kv[0]] = array();
196 if (!isset($this->dumps[$kv[0]][$x->$k])) {
197 $this->dumps[$kv[0]][$x->$k] = 0; // not checked yet..
201 // assume it's the key..
202 if (empty($this->dumps[$table][$x->$k])) {
203 $this->dumps[$table][$x->$k] = 1; // we have checked this one...
205 //if ($is_delete && !isset($this->deletes[$table][$x->$k])) {
207 // $this->deletes[$table][$x->$k] = 0 ; // not checked yet..
215 // flag as checked if we where given an array.. - as some links might have been broken.
216 if (is_array($where)) {
217 foreach($where as $k) {
218 $this->dumps[$table][$k] = 1;
223 // itterate through dumps to find what needs discovering
224 foreach($this->dumps as $k=>$v) {
226 foreach($v as $id => $fetched) {
232 $this->discover($k, $ar,false);
244 function discoverChildren($table, $where, $col=false )
246 echo "discoverChildren:$table:$col:". (is_array($where) ? (count($where) . " children" ): $where ). "\n";
247 global $_DB_DATAOBJECT;
248 $do = DB_DataObject::factory($table);
249 if (PEAR::isError($do)) {
250 if (isset($this->dumps[$table])) {
251 unset($this->dumps[$table]); // links to non-existant tables..
253 echo "SKIPPING invalid table $table\n";
256 if (!isset($this->dumps[$table])) {
257 $this->dumps[$table] = array();
259 if (!isset($this->deletes[$table])) {
260 $this->deletes[$table] = array();
266 if (is_array( $where)) {
267 $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
270 $do->whereAdd($where);
273 static $children = array();
275 if (!isset($children[$table])) {
276 $children[$table] = array();
277 // force load of linsk
279 foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
280 // hack.. - we should get rid of this hack..
281 if ($tbl == 'database__render') {
284 //if ($tbl == $tn) { // skip same table
287 foreach ($links as $tk => $kv) {
290 list($k,$v) = explode(':', $kv);
294 $add = implode(':', array($tbl, $tk));
295 //echo "ADD $tbl $tk=>$kv : $add\n";
296 $children[$table][$add] = true;
306 $do->selectAdd($key);
307 echo "GOT ". $do->find() ." results\n";
308 //DB_DataObject::debugLevel(0);
309 while ($do->fetch()) {
310 $this->dumps[$table][$do->$key] = 0;
311 if (!isset($this->deletes[$table][$do->$key])) {
312 $this->deletes[$table][$do->$key] = 0;
315 foreach($children[$table] as $kv=>$t) {
316 if (!isset($this->dscan[$kv])) {
317 $this->dscan[$kv] = array();
319 if (!isset($this->dscan[$kv][$do->$key])) {
320 $this->dscan[$kv][$do->$key]= 0; // unscanned.
326 // now iterate throught dependants. and scan them.
329 foreach($this->dscan as $kv => $ids) {
331 foreach($ids as $id => $checked) {
333 $this->dscan[$kv][$id] = 1; // flag it as checked.
342 list($k, $v) = explode(':', $kv);
343 $this->discoverChildren($k, $ar, $v);
352 function generateDelete() {
353 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
354 $this->out[] = $target;
355 $fh = fopen($target, 'w');
359 foreach($this->deletes as $tbl=>$ar) {
361 $do = DB_DataObject::factory($tbl);
362 $tbl = $do->tableName();
365 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
367 $archivePaths = method_exists($do,'archivePaths');
368 $listThumbs = method_exists($do,'listThumbs');
369 while ($do->fetch()) {
372 $ct = $do->archivePaths();
374 $this->childfiles[] = $ct;
378 $ct = $do->listThumbs();
380 $this->childthumbs[] = $ct;
385 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
391 function generateShell() {
393 if (empty($this->childfiles) && empty($this->childthumbs)) {
396 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
397 $this->out[] = $target;
398 $fh = fopen($target, 'w');
400 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
401 $this->out[] = $target;
402 $fh2 = fopen($target, 'w');
404 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
405 $this->out[] = $target;
406 $fh3 = fopen($target, 'w');
409 foreach($this->childfiles as $v) {
410 fwrite($fh,"mkdir -p " . escapeshellarg(dirname($args['dump-dir'] .'/'.$v[1])) ."\n" );
411 fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($args['dump-dir'] .'/'.$v[1]) ."\n" );
413 fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
414 fwrite($fh3,"cp " . escapeshellarg($args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
416 fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
419 fclose($fh3); // restore does not need to bother with thumbnails.
423 foreach($this->childthumbs as $v) {
425 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
431 function generateInsert()
433 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
434 $this->out[] = $target;
435 $fh = fopen($target,'w');
439 foreach($this->dumps as $tbl => $ar) {
443 $do = DB_DataObject::factory($tbl);
447 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
449 while ($do->fetch()) {
450 fwrite($fh,$this->toInsert($do));
463 * toInsert - does not handle NULLS...
465 function toInsert($do)
467 $kcol = array_shift($do->keys());
469 // for auto_inc column we need to use a 'set argument'...
470 $items = $do->table();
477 $table = $do->tableName();
480 foreach( $items as $k=>$v)
487 $leftq .= '`' . $k . '`';
492 if ($v & DB_DATAOBJECT_STR) {
493 $rightq .= $do->_quote((string) (
494 ($v & DB_DATAOBJECT_BOOL) ?
495 // this is thanks to the braindead idea of postgres to
496 // use t/f for boolean.
497 (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :
502 if (is_numeric($do->$k)) {
503 $rightq .=" {$do->$k} ";
506 $rightq .= ' ' . intval($do->$k) . ' ';
509 return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";