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==');
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 (empty($args[substr($req,0, -2)])) {
84 $errs[] = "--".substr($req,0, -2) . ' is required';
88 die(print_R($errs,true));
93 $this->discoverChildren($this->args['table'], $this->args['where'], true);
94 //print_R($this->deletes);
95 //print_r($this->dumps);
98 $this->discover($this->args['table'], $this->args['where'], true);
101 if (!file_exists($args['dump-dir'])) {
102 mkdir($args['dump-dir'], 0777, true);
105 $this->generateInsert();
106 $this->generateDelete();
107 $this->generateShell();
110 foreach($this->deletes as $tbl => $ar) {
111 if (empty($ar)) { continue; }
112 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
115 foreach($this->dumps as $tbl => $ar) {
116 if (empty($ar)) { continue; }
117 echo " " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
119 echo "GENERATED FILES:\n";
121 echo " ". implode("\n ", $this->out). "\n";
130 var $deletes = array(); // TABLE => [key] => TRUE|FALSE
131 var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
132 var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
135 * a) what depends on it (eg. child elements) - which will be deleted.
136 * b) what it depends on it (eg. parent elements) - which will be dumped..
139 function discover($table, $where, $is_delete = false )
142 if (!isset($this->dumps[$table])) {
143 $this->dumps[$table] = array();
145 if ($is_delete && !isset($this->deletes[$table])) {
146 $this->deletes[$table] = array();
148 //DB_DataObject::debugLevel(1);
149 $x = DB_DataObject::factory($table);
150 if (PEAR::isError($x)) {
151 if (isset($this->dumps[$table])) {
152 unset($this->dumps[$table]); // links to non-existant tables..
159 if (is_array( $where)) {
160 $x->whereAddIn($keys[0] , $where, 'int');
163 $x->whereAdd($where);
166 // a) id's of elements in this table
167 // b) columns which point to other tables..
168 $links = $x->links();
169 $cols = array_keys($links);
171 array_push($cols, $keys[0]);
175 $x->selectAdd('`'. implode('`,`', $cols) . '`');
177 //DB_DataObject::debugLevel(0);
178 while ($x->fetch()) {
179 foreach($cols as $k) {
180 if (empty($x->$k)) { // skip blanks.
183 if (isset($links[$k])) {
185 $kv = explode(':', $links[$k]);
186 if (!isset($this->dumps[$kv[0]])) {
187 $this->dumps[$kv[0]] = array();
189 if (!isset($this->dumps[$kv[0]][$x->$k])) {
190 $this->dumps[$kv[0]][$x->$k] = 0; // not checked yet..
194 // assume it's the key..
195 if (empty($this->dumps[$table][$x->$k])) {
196 $this->dumps[$table][$x->$k] = 1; // we have checked this one...
198 //if ($is_delete && !isset($this->deletes[$table][$x->$k])) {
200 // $this->deletes[$table][$x->$k] = 0 ; // not checked yet..
207 // flag as checked if we where given an array.. - as some links might have been broken.
208 if (is_array($where)) {
209 foreach($where as $k) {
210 $this->dumps[$table][$k] = 1;
215 // itterate through dumps to find what needs discovering
216 foreach($this->dumps as $k=>$v) {
218 foreach($v as $id => $fetched) {
224 $this->discover($k, $ar,false);
236 function discoverChildren($table, $where, $col=false )
238 global $_DB_DATAOBJECT;
239 $do = DB_DataObject::factory($table);
240 if (PEAR::isError($do)) {
241 if (isset($this->dumps[$table])) {
242 unset($this->dumps[$table]); // links to non-existant tables..
246 if (!isset($this->dumps[$table])) {
247 $this->dumps[$table] = array();
249 if (!isset($this->deletes[$table])) {
250 $this->deletes[$table] = array();
256 if (is_array( $where)) {
257 $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
260 $do->whereAdd($where);
263 static $children = array();
265 if (!isset($children[$table])) {
267 // force load of linsk
269 foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
270 // hack.. - we should get rid of this hack..
271 if ($tbl == 'database__render') {
274 //if ($tbl == $tn) { // skip same table
277 foreach ($links as $tk => $kv) {
280 list($k,$v) = explode(':', $kv);
284 $add = implode(':', array($tbl, $tk));
285 //echo "ADD $tbl $tk=>$kv : $add\n";
286 $children[$table][$add] = true;
292 if (empty($children[$table])) {
296 // DB_DataObject::debugLevel(1);
299 $do->selectAdd($key);
301 while ($do->fetch()) {
302 $this->dumps[$table][$do->$key] = 0;
303 if (!isset($this->deletes[$table][$do->$key])) {
304 $this->deletes[$table][$do->$key] = 0;
307 foreach($children[$table] as $kv=>$t) {
308 if (!isset($this->dscan[$kv])) {
309 $this->dscan[$kv] = array();
311 if (!isset($this->dscan[$kv][$do->$key])) {
312 $this->dscan[$kv][$do->$key]= 0; // unscanned.
318 // now iterate throught dependants. and scan them.
321 foreach($this->dscan as $kv => $ids) {
323 foreach($ids as $id => $checked) {
325 $this->dscan[$kv][$id] = 1; // flag it as checked.
334 list($k, $v) = explode(':', $kv);
335 $this->discoverChildren($k, $ar, $v);
344 function generateDelete() {
345 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
346 $this->out[] = $target;
347 $fh = fopen($target, 'w');
351 foreach($this->deletes as $tbl=>$ar) {
353 $do = DB_DataObject::factory($tbl);
354 $tbl = $do->tableName();
357 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
359 while ($do->fetch()) {
363 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
368 function generateShell() {
370 if (empty($this->childfiles)) {
373 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
374 $this->out[] = $target;
375 $fh = fopen($target, 'w');
377 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
378 $this->out[] = $target;
379 $fh2 = fopen($target, 'w');
381 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
382 $this->out[] = $target;
383 $fh3 = fopen($target, 'w');
386 foreach($this->childfiles as $s=>$v) {
387 fwrite($fh,"mkdir -p " . escapeshellarg(dirname($args['dump-dir'] .'/'.$v[1])) ."\n" );
388 fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($args['dump-dir'] .'/'.$v[1]) ."\n" );
390 fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
391 fwrite($fh3,"cp " . escapeshellarg($args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
393 fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
396 fclose($fh3); // restore does not need to bother with thumbnails.
400 foreach($this->childthumbs as $s=>$v) {
402 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
408 function generateInsert()
410 $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
411 $this->out[] = $target;
412 $fh = fopen($target,'w');
416 foreach($this->dumps as $tbl => $ar) {
420 $do = DB_DataObject::factory($tbl);
424 $do->whereAddIn($keys[0] , array_keys($ar), 'int');
426 while ($do->fetch()) {
427 fwrite($fh,$this->toInsert($do));
440 * toInsert - does not handle NULLS...
442 function toInsert($do)
444 $kcol = array_shift($do->keys());
446 // for auto_inc column we need to use a 'set argument'...
447 $items = $do->table();
454 $table = $do->tableName();
457 foreach( $items as $k=>$v)
464 $leftq .= '`' . $k . '`';
469 if ($v & DB_DATAOBJECT_STR) {
470 $rightq .= $do->_quote((string) (
471 ($v & DB_DATAOBJECT_BOOL) ?
472 // this is thanks to the braindead idea of postgres to
473 // use t/f for boolean.
474 (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :
479 if (is_numeric($do->$k)) {
480 $rightq .=" {$do->$k} ";
483 $rightq .= ' ' . intval($do->$k) . ' ';
486 return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";