【问题标题】:What's the point of disabling transactions (in ActiveRecord CodeIgniter)?禁用事务有什么意义(在 ActiveRecord CodeIgniter 中)?
【发布时间】:2014-04-09 06:52:06
【问题描述】:

禁用事务有什么意义? http://ellislab.com/codeigniter/user-guide/database/transactions.html

$this->db->trans_off()

我看不到用法。是为了测试目的吗?

“当事务被禁用时,你的查询将被自动提交,就像在没有事务的情况下运行查询一样。”

我有一个名为user 的表,其中存在一个列nameOfUsernameOfUser2 - 列存在。

测试1 此代码将尝试使用 普通事务 进行 2 次插入:

$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
$this->db->trans_complete();    

但是因为nameOfUser2-column 在第二次插入中不存在列而被回滚(没有插入任何内容)。

测试2 此代码将尝试在 transaction disabled

的情况下进行 2 次插入
$this->db->trans_off();
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
$this->db->trans_complete();    

上面会将 testCVVCOOL 字符串插入到user-table 中,即使第二次插入有错误 ($this->db->insert('user', array('nameOfUser2' => 'test2'));)

您什么时候需要以这种方式禁用事务?

【问题讨论】:

  • 我不确定,但我相信这更像是交易状态的休息,因为在您执行 trans_start() 之后,如果您有任何疑问,您可能需要将交易模式重置为关闭交易结束后执行。

标签: codeigniter activerecord transactions


【解决方案1】:

您什么时候需要以这种方式禁用事务?

我的理解是,如果出现问题(如您的第一个示例中所示),事务不允许在同一线程中进行更多交互。因此,如果您想在提交之前和回滚之前在数据库中做其他事情,您将无法做到。

伪例子:

//will not work
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
//more likely this would be a condition that makes sense 
//perhaps using a query result from earlier in function
if(1===1){
    $this->db->query('INSERT INTO errors (db) values (1)');//nogo
}
$this->db->trans_complete(); 

-

//will work
$this->db->trans_off();
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
//more likely this would be a condition that makes sense 
//perhaps using a query result from earlier in function
if(1===1){
    $this->db->query('INSERT INTO errors (db) values (1)');//OK
}
$this->db->trans_complete(); 

【讨论】:

  • 您的意思是(基本上)记录错误?
  • 这只是一种可能的用例。我认为允许它的重点是灵活性——如果出于某种原因(错误、强制写入等)需要该功能,那么该功能就在那里。
  • 但这似乎是一种奇怪的错误处理方式? (例如)。在文档 (ellislab.com/codeigniter/user-guide/database/transactions.html) 中,它说您可以使用 $this->db->trans_status() 获取事务状态,然后进行一些日志记录。这是我的观点。我可以找出任何关闭交易的好理由,因为有更好的选择?
  • 好点。你知道,老实说,我不确定。查看该库,它似乎只是一个挂钩到各个数据库的事务控制(自动提交等)。这确实是关于数据库的问题,而不是 CodeIgniter。这个stackoverflow.com/q/39583/183254 似乎表明事务对资源的要求很高,因此不适合高流量/高 IO 应用程序,这是有道理的。所以我猜答案是“关闭事务的一个很好的理由是高吞吐量应用程序或应用程序的一部分”。
  • 还有其他方法可以确保正确性,例如使用 ORM。我不确定您还在寻找什么答案;您问为什么有人要这样做,答案是性能原因。如果你买不起更好的硬件或缓存怎么办?您可以关闭交易;)
【解决方案2】:

这完全取决于我们使用事务的场景 -

需要交易时:

需要一套完整的操作,即如果有人在线订购产品,并且订单确认涉及一些步骤,那么如果任何步骤失败则恢复整个订单交易。

需要关闭事务时:

如果我正在尝试一些对我来说任何类型的信息都值得的东西。然后我们可以使用事务关闭功能。无论发生什么错误,保存符合条件的数据。

【讨论】:

  • 我真的不明白。你能举个例子详细说明一下吗?
猜你喜欢
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2021-07-23
  • 2021-08-16
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2020-07-06
相关资源
最近更新 更多