[英]Can I rollback transaction when database error exception is thrown?
I have a large data set that needs to be written to the database when posted to the server, but it's possible that a bug in the client editor is added extra records that trigger an "integrity constraint violation". 我有一个大型数据集,在发布到服务器时需要写入数据库,但是客户端编辑器中的错误可能会添加额外的记录,从而触发“完整性约束违规”。
My problem is that when I reach the point in the data where the error is trigger, then a lot of the previous data has already been updated in the database. 我的问题是,当我到达触发错误的数据点时,数据库中的许多先前数据已经更新。 I need to rollback and reject the posted data.
我需要回滚并拒绝发布的数据。
Here's my controller's action. 这是我的控制器的动作。
/**
* Handles saving data from the network editor.
*/
public function json_save()
{
if($this->request->is('post'))
{
$result = array();
$data = $this->request->input('json_decode');
if(isset($data->network_id) && !empty($data->network_id))
{
$dataSource = $this->Node->getDataSource();
$dataSource->begin();
$result['nodes'] = $this->updateModel($data->network_id, $this->Node, 'nodes', $data, array(
'ParamValue'
));
$result['connections'] = $this->updateModel($data->network_id, $this->Connection, 'connections', $data);
$dataSource->commit();
$this->viewClass = 'Json';
$this->set('result', $result);
$this->set('_serialize', array(
'result'
));
return;
}
}
throw new ErrorException('Posted data missing.');
}
My controller's updateModel
function performs a few deletes and updates to the models $this->Node
and $this->Connection
. 我的控制器的
updateModel
函数对模型$this->Node
和$this->Connection
执行一些删除和更新。
How do I roll back upon an "integrity constraint violation" which is usually thrown during updating of the $this->Connection
model. 如何回滚在更新
$this->Connection
模型期间通常抛出的“完整性约束违规”。
I'm not sure if it's a PHP exception that I can catch and then do a rollback, or if there is a different way to catch it. 我不确定它是否是一个PHP异常,我可以捕获然后进行回滚,或者是否有不同的方法来捕获它。
You can do a : 你可以这样做:
$dataSource->begin();
try {
// The queries here.
} catch (Exception $e) {
$dataSource->rollback();
throw $e;
}
$dataSource->commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.