Files
camelia-orm/src/Exception/DatabaseException.php
T
dgarcia 66e93e3070 feat: initial commit of camelia/orm
Attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.

- Attribute-driven metadata: TableName, PrimaryKey, AutoIncrement, Column,
  Guarded, Ignore, Required, Enum, Nullable, Length, Precision, Unique,
  UniqueGroup, Index, MaxLength.
- Relationship mapping: BelongsTo, HasOne, HasMany, BelongsToMany with
  batched eager loading and a 3-level depth limit.
- Orm entry point with fromArray, fromPdo, fromEnv and nested transactions.
- Immutable Query with Cond operators and GroupCond grouping.
- Repository read and write API, pagination, and typed exception hierarchy.
- Declares PHP >=8.3; Mago and PHPStan pin the parser to 8.3.
- MIT license.
2026-11-15 10:14:22 -03:00

73 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
use PDOException;
/**
* Wraps a PDO failure and preserves the SQL and parameters that produced it.
*/
class DatabaseException extends OrmException
{
/**
* @param list<mixed> $params
*/
public function __construct(
string $message,
private readonly string $sql = '',
private readonly array $params = [],
private readonly string $context = '',
?\Throwable $previous = null,
) {
parent::__construct($message, 0, $previous);
}
/**
* Maps a PDOException to the narrowest exception type the SQLSTATE allows.
*
* @param list<mixed> $params
*/
public static function fromPdoException(
PDOException $exception,
string $context,
string $sql = '',
array $params = [],
): self {
$sqlState = (string) $exception->getCode();
$driverCode = (int) ($exception->errorInfo[1] ?? 0);
$message = sprintf('Database error during %s: %s', $context, $exception->getMessage());
if ($sqlState === '23000' && in_array($driverCode, [1062, 1555, 1586], true)) {
return new DuplicateKeyException($message, $sql, $params, $context, $exception);
}
if ($sqlState === '23000' && in_array($driverCode, [1451, 1452], true)) {
return new ForeignKeyViolationException($message, $sql, $params, $context, $exception);
}
if ($sqlState === 'HY000' && in_array($driverCode, [1205, 1213], true)) {
return new LockTimeoutException($message, $sql, $params, $context, $exception);
}
return new self($message, $sql, $params, $context, $exception);
}
public function sql(): string
{
return $this->sql;
}
/** @return list<mixed> */
public function params(): array
{
return $this->params;
}
public function context(): string
{
return $this->context;
}
}