mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-16 22:39:52 +08:00
Fixes #226: atomic operations and transaction support in AR.
This commit is contained in:
@@ -446,3 +446,7 @@ $customers = Customer::find()->olderThan(50)->all();
|
||||
|
||||
The parameters should follow after the `$query` parameter when defining the scope method, and they
|
||||
can take default values like shown above.
|
||||
|
||||
### Atomic operations and scenarios
|
||||
|
||||
TBD
|
||||
|
||||
@@ -1,15 +1,50 @@
|
||||
ActiveRecord
|
||||
============
|
||||
|
||||
Scenarios
|
||||
---------
|
||||
|
||||
All possible scenario formats supported by ActiveRecord:
|
||||
|
||||
```php
|
||||
public function scenarios()
|
||||
{
|
||||
return array(
|
||||
// 1. attributes array
|
||||
'scenario1' => array('attribute1', 'attribute2'),
|
||||
|
||||
// 2. insert, update and delete operations won't be wrapped with transaction (default mode)
|
||||
'scenario2' => array(
|
||||
'attributes' => array('attribute1', 'attribute2'),
|
||||
'atomic' => array(), // default value
|
||||
),
|
||||
|
||||
// 3. all three operations (insert, update and delete) will be wrapped with transaction
|
||||
'scenario3' => array(
|
||||
'attributes' => array('attribute1', 'attribute2'),
|
||||
'atomic',
|
||||
),
|
||||
|
||||
// 4. insert and update operations will be wrapped with transaction, delete won't
|
||||
'scenario4' => array(
|
||||
'attributes' => array('attribute1', 'attribute2'),
|
||||
'atomic' => array(self::INSERT, self::UPDATE),
|
||||
),
|
||||
|
||||
// 5. insert and update operations won't be wrapped with transaction, delete will
|
||||
'scenario5' => array(
|
||||
'attributes' => array('attribute1', 'attribute2'),
|
||||
'atomic' => array(self::DELETE),
|
||||
),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Query
|
||||
-----
|
||||
|
||||
### Basic Queries
|
||||
|
||||
|
||||
|
||||
### Relational Queries
|
||||
|
||||
### Scopes
|
||||
|
||||
|
||||
|
||||
@@ -590,42 +590,49 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
|
||||
|
||||
/**
|
||||
* Returns the attribute names that are safe to be massively assigned in the current scenario.
|
||||
* @return array safe attribute names
|
||||
* @return string[] safe attribute names
|
||||
*/
|
||||
public function safeAttributes()
|
||||
{
|
||||
$scenario = $this->getScenario();
|
||||
$scenarios = $this->scenarios();
|
||||
if (!isset($scenarios[$scenario])) {
|
||||
return array();
|
||||
}
|
||||
$attributes = array();
|
||||
if (isset($scenarios[$scenario])) {
|
||||
if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) {
|
||||
$scenarios[$scenario] = $scenarios[$scenario]['attributes'];
|
||||
}
|
||||
foreach ($scenarios[$scenario] as $attribute) {
|
||||
if ($attribute[0] !== '!') {
|
||||
$attributes[] = $attribute;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attribute names that are subject to validation in the current scenario.
|
||||
* @return array safe attribute names
|
||||
* @return string[] safe attribute names
|
||||
*/
|
||||
public function activeAttributes()
|
||||
{
|
||||
$scenario = $this->getScenario();
|
||||
$scenarios = $this->scenarios();
|
||||
if (isset($scenarios[$scenario])) {
|
||||
$attributes = $scenarios[$this->getScenario()];
|
||||
if (!isset($scenarios[$scenario])) {
|
||||
return array();
|
||||
}
|
||||
if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) {
|
||||
$attributes = $scenarios[$scenario]['attributes'];
|
||||
} else {
|
||||
$attributes = $scenarios[$scenario];
|
||||
}
|
||||
foreach ($attributes as $i => $attribute) {
|
||||
if ($attribute[0] === '!') {
|
||||
$attributes[$i] = substr($attribute, 1);
|
||||
}
|
||||
}
|
||||
return $attributes;
|
||||
} else {
|
||||
return array();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -73,6 +73,22 @@ class ActiveRecord extends Model
|
||||
*/
|
||||
const EVENT_AFTER_DELETE = 'afterDelete';
|
||||
|
||||
/**
|
||||
* Represents insert ActiveRecord operation. This constant is used for specifying set of atomic operations
|
||||
* for particular scenario in the [[scenarios()]] method.
|
||||
*/
|
||||
const OPERATION_INSERT = 'insert';
|
||||
/**
|
||||
* Represents update ActiveRecord operation. This constant is used for specifying set of atomic operations
|
||||
* for particular scenario in the [[scenarios()]] method.
|
||||
*/
|
||||
const OPERATION_UPDATE = 'update';
|
||||
/**
|
||||
* Represents delete ActiveRecord operation. This constant is used for specifying set of atomic operations
|
||||
* for particular scenario in the [[scenarios()]] method.
|
||||
*/
|
||||
const OPERATION_DELETE = 'delete';
|
||||
|
||||
/**
|
||||
* @var array attribute values indexed by attribute names
|
||||
*/
|
||||
@@ -664,10 +680,39 @@ class ActiveRecord extends Model
|
||||
* @param array $attributes list of attributes that need to be saved. Defaults to null,
|
||||
* meaning all attributes that are loaded from DB will be saved.
|
||||
* @return boolean whether the attributes are valid and the record is inserted successfully.
|
||||
* @throws \Exception in case insert failed.
|
||||
*/
|
||||
public function insert($runValidation = true, $attributes = null)
|
||||
{
|
||||
if ($runValidation && !$this->validate($attributes) || !$this->beforeSave(true)) {
|
||||
if ($runValidation && !$this->validate($attributes)) {
|
||||
return false;
|
||||
}
|
||||
$db = static::getDb();
|
||||
$transaction = $this->isOperationAtomic(self::OPERATION_INSERT) && null === $db->getTransaction() ? $db->beginTransaction() : null;
|
||||
try {
|
||||
$result = $this->internalInsert($attributes);
|
||||
if (null !== $transaction) {
|
||||
if (false === $result) {
|
||||
$transaction->rollback();
|
||||
} else {
|
||||
$transaction->commit();
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
if (null !== $transaction) {
|
||||
$transaction->rollback();
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see ActiveRecord::insert()
|
||||
*/
|
||||
private function internalInsert($attributes = null)
|
||||
{
|
||||
if (!$this->beforeSave(true)) {
|
||||
return false;
|
||||
}
|
||||
$values = $this->getDirtyAttributes($attributes);
|
||||
@@ -678,7 +723,9 @@ class ActiveRecord extends Model
|
||||
}
|
||||
$db = static::getDb();
|
||||
$command = $db->createCommand()->insert($this->tableName(), $values);
|
||||
if ($command->execute()) {
|
||||
if (!$command->execute()) {
|
||||
return false;
|
||||
}
|
||||
$table = $this->getTableSchema();
|
||||
if ($table->sequenceName !== null) {
|
||||
foreach ($table->primaryKey as $name) {
|
||||
@@ -694,7 +741,6 @@ class ActiveRecord extends Model
|
||||
$this->afterSave(true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the changes to this active record into the associated database table.
|
||||
@@ -744,14 +790,46 @@ class ActiveRecord extends Model
|
||||
* or [[beforeSave()]] stops the updating process.
|
||||
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
|
||||
* being updated is outdated.
|
||||
* @throws \Exception in case update failed.
|
||||
*/
|
||||
public function update($runValidation = true, $attributes = null)
|
||||
{
|
||||
if ($runValidation && !$this->validate($attributes) || !$this->beforeSave(false)) {
|
||||
if ($runValidation && !$this->validate($attributes)) {
|
||||
return false;
|
||||
}
|
||||
$db = static::getDb();
|
||||
$transaction = $this->isOperationAtomic(self::OPERATION_UPDATE) && null === $db->getTransaction() ? $db->beginTransaction() : null;
|
||||
try {
|
||||
$result = $this->internalUpdate($attributes);
|
||||
if (null !== $transaction) {
|
||||
if (false === $result) {
|
||||
$transaction->rollback();
|
||||
} else {
|
||||
$transaction->commit();
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
if (null !== $transaction) {
|
||||
$transaction->rollback();
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see CActiveRecord::update()
|
||||
* @throws StaleObjectException
|
||||
*/
|
||||
private function internalUpdate($attributes = null)
|
||||
{
|
||||
if (!$this->beforeSave(false)) {
|
||||
return false;
|
||||
}
|
||||
$values = $this->getDirtyAttributes($attributes);
|
||||
if (!empty($values)) {
|
||||
if (empty($values)) {
|
||||
return 0;
|
||||
}
|
||||
$condition = $this->getOldPrimaryKey(true);
|
||||
$lock = $this->optimisticLock();
|
||||
if ($lock !== null) {
|
||||
@@ -771,12 +849,8 @@ class ActiveRecord extends Model
|
||||
foreach ($values as $name => $value) {
|
||||
$this->_oldAttributes[$name] = $this->_attributes[$name];
|
||||
}
|
||||
|
||||
$this->afterSave(false);
|
||||
return $rows;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -826,27 +900,43 @@ class ActiveRecord extends Model
|
||||
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
|
||||
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
|
||||
* being deleted is outdated.
|
||||
* @throws \Exception in case delete failed.
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
$db = static::getDb();
|
||||
$transaction = $this->isOperationAtomic(self::OPERATION_DELETE) && null === $db->getTransaction() ? $db->beginTransaction() : null;
|
||||
try {
|
||||
$result = false;
|
||||
if ($this->beforeDelete()) {
|
||||
// we do not check the return value of deleteAll() because it's possible
|
||||
// the record is already deleted in the database and thus the method will return 0
|
||||
$condition = $this->getOldPrimaryKey(true);
|
||||
$lock = $this->optimisticLock();
|
||||
if ($lock !== null) {
|
||||
if (null !== $lock) {
|
||||
$condition[$lock] = $this->$lock;
|
||||
}
|
||||
$rows = $this->deleteAll($condition);
|
||||
if ($lock !== null && !$rows) {
|
||||
$result = $this->deleteAll($condition);
|
||||
if (null !== $lock && !$result) {
|
||||
throw new StaleObjectException('The object being deleted is outdated.');
|
||||
}
|
||||
$this->_oldAttributes = null;
|
||||
$this->afterDelete();
|
||||
return $rows;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (null !== $transaction) {
|
||||
if (false === $result) {
|
||||
$transaction->rollback();
|
||||
} else {
|
||||
$transaction->commit();
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
if (null !== $transaction) {
|
||||
$transaction->rollback();
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1336,4 +1426,19 @@ class ActiveRecord extends Model
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $operation possible values are ActiveRecord::INSERT, ActiveRecord::UPDATE and ActiveRecord::DELETE.
|
||||
* @return boolean whether given operation is atomic. Currently active scenario is taken into account.
|
||||
*/
|
||||
private function isOperationAtomic($operation)
|
||||
{
|
||||
$scenario = $this->getScenario();
|
||||
$scenarios = $this->scenarios();
|
||||
if (!isset($scenarios[$scenario]) || !isset($scenarios[$scenario]['attributes']) || !is_array($scenarios[$scenario]['attributes'])) {
|
||||
return false;
|
||||
}
|
||||
return in_array('atomic', $scenarios[$scenario]) ||
|
||||
isset($scenarios[$scenario]['atomic']) && is_array($scenarios[$scenario]['atomic']) && in_array($operation, $scenarios[$scenario]['atomic']);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user