在MySQL中模拟DELETE CASCADE?

时间:2011-05-17 10:10:07

标签: mysql cascading-deletes

是否可以自动预测DELETE CASCADE后面的操作?在我的软件中,我想向用户发出警告,其中包含有关将被删除的数据的详细信息。

3 个答案:

答案 0 :(得分:3)

您可以复制数据库并在after delete

上添加触发器
DELIMITER $$

CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (null                 /*autoinc id*/
        , 'table1'                             /*tablename*/
        , old.id                               /*tableid*/
        , concat_ws(',',old.field1,old.field2  /*CSV's of fields*/
        , NOW()                                /*timestamp*/
        , 'delete');                           /*what action*/


  REPLACE INTO restore_table1 VALUES (old.id,
        , old.field1
        , old.field2
        , ... );

END $$

DELIMITER ;

日志表只是一个包含以下字段的表:

id            integer autoincrement primary key
tablename     varchar(45)
table_id      integer
fields        varchar(6000)
delete_time   timestamp
action        enum('insert','update','delete')

如果您在副本上的删除级联之前执行SELECT @last_id:= max(id) FROM log 然后你可以做SELECT * FROM log WHERE id > @last_id
并获取将在级联中删除的所有行。

之后,您可以使用restore_table1重新创建复制数据库中级联中删除的行。

答案 1 :(得分:1)

我认为您可以将Johan的触发器解决方案与您回滚的事务结合使用。这样既可以避免使用第二个数据库,也可以手动恢复已删除的条目。

  • 添加触发器和日志表
  • 每次尝试删除都会启动一个事务并删除条目
  • 将日志中的信息提供给您的用户以供审批
  • 如果用户同意提交事务,否则回滚

答案 2 :(得分:0)

我写了一篇非常快速的黑客文章,它完全符合您在PHP中的需求,因为我想做同样的事情并且没有在网上找到任何资源。

对你来说可能为时已晚,但它可能有助于其他人。

function get_referencing_foreign_keys ($database, $table) {
    $query = 'SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = "'.$database.'" AND REFERENCED_TABLE_NAME = '.esc($table);
    $result = rquery($query);
    $foreign_keys = array();
    while ($row = mysql_fetch_row($result)) {
        $foreign_keys[] = array('database' => $row[0], 'table' => $row[1], 'column' => $row[2], 'reference_column' => $row[3]);
    }

    return $foreign_keys;
}

function get_foreign_key_deleted_data_html ($database, $table, $where) {
    $data = get_foreign_key_deleted_data ($database, $table, $where);

    $html = '';
    foreach ($data as $key => $this_data) {
        $html .= "<h2>$key</h2>\n";

        $html .= "<table>\n";
        $i = 0;
        foreach ($this_data as $value) {
            if($i == 0) {
                $html .= "\t<tr>\n";
                foreach ($value as $column => $column_value) {
                    $html .= "\t\t<th>".htmlentities($column)."</th>\n";
                }
                $html .= "\t</tr>\n";
            }
            $html .= "\t<tr>\n";
            foreach ($value as $column => $column_value) {
                $html .= "\t\t<td>".htmlentities($column_value)."</td>\n";
            }
            $html .= "\t</tr>\n";
            $i++;
        }
        $html .= "</table>\n";
    }

    return $html;
}

function get_foreign_key_deleted_data ($database, $table, $where) {
    $GLOBALS['get_data_that_would_be_deleted'] = array();
    $data = get_data_that_would_be_deleted($database, $table, $where);
    $GLOBALS['get_data_that_would_be_deleted'] = array();
    return $data;
}

function get_data_that_would_be_deleted ($database, $table, $where, $recursion = 100) {
    if($recursion <= 0) {
        die("Deep recursion!");
    }

    if($recursion == 100) {
        $GLOBALS['get_data_that_would_be_deleted'] = array();
    }

    if($table) {
        if(is_array($where)) {
            $foreign_keys = get_referencing_foreign_keys($database, $table);
            $data = array();

            $query = 'SELECT * FROM `'.$table.'`';
            if(count($where)) {
                $query .= ' WHERE 1';
                foreach ($where as $name => $value) {
                    $query .= " AND `$name` = ".esc($value);
                }
            }
            $result = rquery($query);

            $to_check = array();

            while ($row = mysql_fetch_row($result)) {
                $new_row = array();
                $i = 0;
                foreach ($row as $this_row) {
                    $field_info = mysql_fetch_field($result, $i);
                    $new_row[$field_info->name] = $this_row;
                    foreach ($foreign_keys as $this_foreign_key) {
                        if($this_foreign_key['reference_column'] == $field_info->name) {
                            $to_check[] = array('value' => $this_row, 'foreign_key' => array('table' => $this_foreign_key['table'], 'column' => $this_foreign_key['column'], 'database' => $this_foreign_key['database']));
                        }
                    }
                    $i++;
                }
                $GLOBALS['get_data_that_would_be_deleted'][$table][] = $new_row;
            }
            foreach ($to_check as $this_to_check) {
                if(isset($this_to_check['value']) && !is_null($this_to_check['value'])) {
                    get_data_that_would_be_deleted($database, $this_to_check['foreign_key']['table'], array($this_to_check['foreign_key']['column'] => $this_to_check['value']), $recursion - 1);;
                }
            }

            $data = $GLOBALS['get_data_that_would_be_deleted'];

            return $data;
        } else {
            die("\$where needs to be an array with column_name => value pairs");
        }
    } else {
        die("\$table was not defined!");
    }
}

想象一下,我在数据库“db”中有一个名为“table”的表,我想删除一个id为180的表,然后我会调用:

print(get_foreign_key_deleted_data_html('db', 'table', array('id' => 180)));

并打印一个包含所有行以及将删除的所有值的完整表。

但正如我所说,这是一个非常非常快速和肮脏的黑客行为。我很高兴任何错误报告(肯定有很多错误报告!)。