Skip to content

Instantly share code, notes, and snippets.

@swvitaliy
Created August 21, 2013 15:20
Show Gist options
  • Save swvitaliy/6295850 to your computer and use it in GitHub Desktop.
Save swvitaliy/6295850 to your computer and use it in GitHub Desktop.
generation a bucket table
$lnk = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ('Not connected: ' . mysql_error());
mysql_select_db(DB_NAME, $lnk) or die ('Can\'t use foo: ' . mysql_error());
mysql_query("SET NAMES 'cp1251'", $lnk);
create_bucket_table($_SERVER['argv'][1], $lnk);
function Q($sql, $lnk) {
$res = mysql_query($sql, $lnk);
if (mysql_errno($lnk)) { die('> ' . $sql . PHP_EOL . PHP_EOL
. 'mysql error #' . mysql_errno($lnk) . ' with message: ' . mysql_error($lnk) . PHP_EOL); }
return $res;
}
function sql_bucket($table, $lnk) {
$res = Q("show create table `" . $table . "`", $lnk);
$row = mysql_fetch_assoc($res);
$create_table = $row['Create Table'];
$npos = strpos($create_table, "\n");
$first_line = substr($create_table, 0, $npos);
return preg_replace_callback('/\`(?P<table>[^\`]+)\`/',
function($m) {
return '`' . make_bucket_name($m['table']) . '`';
}, $first_line)
. "\n"
. substr($create_table, $npos+1);
}
function make_bucket_name($table) {
static $prefixes = array('generator_', 'mm_', 'agency_', 'office_',);
foreach ($prefixes as $v)
if (strpos($table, $v)===0) {
return $v . 'remove_' . substr($table, strlen($v));
}
return 'remove_' . $table;
}
function column_list($columns) {
return implode(',', array_map(function($v) { return '`' . $v . '`'; }, $columns));
}
function create_bucket_table($table, $lnk) {
$bucket_table = make_bucket_name($table);
$sql = sql_bucket($table, $lnk);
preg_match_all('/^\s*`(?P<columns>[^`]+)`/m', $sql, $m);
$columns = $m['columns'];
preg_match('/^\s*PRIMARY KEY \(`(?P<column>[^`]+)`\)/m', $sql, $m);
$pk = $m['column'];
Q('drop table if exists `'. $bucket_table.'`',$lnk);
Q($sql, $lnk);
Q('alter table `'.$bucket_table.'` add column date_remove timestamp not null default CURRENT_TIMESTAMP;', $lnk);
Q('DROP TRIGGER if exists `'.$table.'_before_belete`', $lnk);
Q('CREATE TRIGGER `'.$table.'_before_belete` BEFORE DELETE ON `'.$table.'` FOR EACH ROW ' . PHP_EOL
. ' insert into `'.$bucket_table.'` ' . PHP_EOL
. ' ('.column_list($columns).', `date_remove`) ' . PHP_EOL
. ' select '.column_list($columns).', now() ' . PHP_EOL
. ' from `'.$table.'` gi where gi.'.$pk.' = OLD.'.$pk.';', $lnk);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment