使用LOCK TABLES回滚事务

时间:2011-01-31 09:34:23

标签: mysql transactions locking innodb

我有一个PHP / 5.2驱动的应用程序,它使用MySQL / 5.1下的事务,因此如果满足错误条件,它可以回滚多个插入。我有不同的可重用功能来插入不同类型的项目。到目前为止一切都很好。

现在我需要对某些插入使用表锁定。正如官方手册所示,我使用的是SET autocommit=0而不是START TRANSACTION,因此LOCK TABLES不会发出隐式提交。并且,如文档所述,解锁表隐式提交任何活动事务:

问题在于:如果我只是避免UNLOCK TABLES,那么第二次调用LOCK TABLES就会提交挂起的更改!

似乎唯一的方法是在一个语句中执行所有必要的LOCK TABLES。这是一个主要的噩梦。

这个问题是否有明智的解决方法?

这是一个小测试脚本:

DROP TABLE IF EXISTS test;

CREATE TABLE test (
    test_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    random_number INT(10) UNSIGNED NOT NULL,
    PRIMARY KEY (test_id)
)
COLLATE='utf8_spanish_ci'
ENGINE=InnoDB;


-- No table locking: everything's fine
START TRANSACTION;
INSERT INTO test (random_number) VALUES (ROUND(10000* RAND()));
SELECT * FROM TEST ORDER BY test_id;
ROLLBACK;
SELECT * FROM TEST ORDER BY test_id;



-- Table locking: everything's fine if I avoid START TRANSACTION
SET autocommit=0;
INSERT INTO test (random_number) VALUES (ROUND(10000* RAND()));
SELECT * FROM TEST ORDER BY test_id;
ROLLBACK;
SELECT * FROM TEST ORDER BY test_id;
SET autocommit=1;



-- Table locking: I cannot nest LOCK/UNLOCK blocks
SET autocommit=0;
LOCK TABLES test WRITE;
INSERT INTO test (random_number) VALUES (ROUND(10000* RAND()));
SELECT * FROM TEST ORDER BY test_id;
ROLLBACK;
UNLOCK TABLES; -- Implicit commit
SELECT * FROM TEST ORDER BY test_id;
SET autocommit=1;


-- Table locking: I cannot chain LOCK calls ether
SET autocommit=0;
LOCK TABLES test WRITE;
INSERT INTO test (random_number) VALUES (ROUND(10000* RAND()));
SELECT * FROM TEST ORDER BY test_id;
-- UNLOCK TABLES;
LOCK TABLES test WRITE; -- Implicit commit
INSERT INTO test (random_number) VALUES (ROUND(10000* RAND()));
SELECT * FROM TEST ORDER BY test_id;
-- UNLOCK TABLES;
ROLLBACK;
SELECT * FROM TEST ORDER BY test_id;
SET autocommit=1;

1 个答案:

答案 0 :(得分:4)

显然,LOCK TABLES无法修复以适应交易。解决方法是将其替换为SELECT .... FOR UPDATE。您不需要任何特殊语法(您可以使用常规START TRANSACTION),它可以按预期工作:

START TRANSACTION;
SELECT COUNT(*) FROM foo FOR UPDATE; -- Lock issued
INSERT INTO foo (foo_name) VALUES ('John');
SELECT COUNT(*) FROM bar FOR UPDATE; -- Lock issued, no side effects
ROLLBACK; -- Rollback works as expected

请注意,COUNT(*)只是一个示例,您通常可以使用SELECT语句来获取实际需要的数据; - )

(此信息由Frank Heikens提供。)