Commit ca23cd8a by Alexander Makarov

Implemented throwing \yii\db\IntegrityException on DB integrity errors

parent b86f5a14
......@@ -284,13 +284,7 @@ class Command extends \yii\base\Component
return $n;
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
if ($e instanceof Exception) {
throw $e;
} else {
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception($message, $errorInfo, (int) $e->getCode(), $e);
}
$this->handleError($e, $rawSql);
}
}
......@@ -423,13 +417,7 @@ class Command extends \yii\base\Component
return $result;
} catch (\Exception $e) {
Yii::endProfile($token, 'yii\db\Command::query');
if ($e instanceof Exception) {
throw $e;
} else {
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception($message, $errorInfo, (int) $e->getCode(), $e);
}
$this->handleError($e, $rawSql);
}
}
......@@ -779,4 +767,30 @@ class Command extends \yii\base\Component
return $this->setSql($sql);
}
/**
* Handles database error
*
* @param \Exception $e
* @param string $rawSql SQL that produced exception
* @throws Exception
*/
protected function handleError(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
throw $e;
} else {
$exceptionClass = '\yii\db\Exception';
$errorMap = $this->db->getSchema()->errorMap;
foreach ($errorMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
}
}
}
......@@ -73,6 +73,13 @@ abstract class Schema extends Object
private $_builder;
/**
* @var array map of DB errors and corresponding exceptions
*/
public $errorMap = [
'SQLSTATE[23' => '\yii\db\IntegrityException',
];
/**
* Loads the metadata for the specified table.
* @param string $name table name
* @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
......
<?php
namespace yii\tests\unit\framework\db\pgsql;
use yiiunit\framework\db\CommandTest;
class PostgreSQLCommandTest extends CommandTest
{
public $driverName = 'pgsql';
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment