| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | namespace Atk4\Data\Persistence\Sql; |
| 6: | |
| 7: | use Atk4\Core\DiContainerTrait; |
| 8: | use Doctrine\DBAL\Configuration; |
| 9: | use Doctrine\DBAL\Connection as DbalConnection; |
| 10: | use Doctrine\DBAL\ConnectionException as DbalConnectionException; |
| 11: | use Doctrine\DBAL\Driver as DbalDriver; |
| 12: | use Doctrine\DBAL\Driver\Connection as DbalDriverConnection; |
| 13: | use Doctrine\DBAL\Driver\Middleware as DbalMiddleware; |
| 14: | use Doctrine\DBAL\DriverManager; |
| 15: | use Doctrine\DBAL\Platforms\AbstractPlatform; |
| 16: | use Doctrine\DBAL\Result as DbalResult; |
| 17: | use Doctrine\DBAL\Schema\AbstractSchemaManager; |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | abstract class Connection |
| 23: | { |
| 24: | use DiContainerTrait; |
| 25: | |
| 26: | |
| 27: | protected string $expressionClass; |
| 28: | |
| 29: | protected string $queryClass; |
| 30: | |
| 31: | |
| 32: | private $_connection; |
| 33: | |
| 34: | |
| 35: | protected static $connectionClassRegistry = [ |
| 36: | 'pdo_sqlite' => Sqlite\Connection::class, |
| 37: | 'pdo_mysql' => Mysql\Connection::class, |
| 38: | 'mysqli' => Mysql\Connection::class, |
| 39: | 'pdo_pgsql' => Postgresql\Connection::class, |
| 40: | 'pdo_sqlsrv' => Mssql\Connection::class, |
| 41: | 'pdo_oci' => Oracle\Connection::class, |
| 42: | 'oci8' => Oracle\Connection::class, |
| 43: | ]; |
| 44: | |
| 45: | |
| 46: | |
| 47: | |
| 48: | protected function __construct(array $defaults = []) |
| 49: | { |
| 50: | $this->setDefaults($defaults); |
| 51: | } |
| 52: | |
| 53: | public function __destruct() |
| 54: | { |
| 55: | |
| 56: | if ($this->_connection !== null) { |
| 57: | $this->getConnection()->close(); |
| 58: | } |
| 59: | } |
| 60: | |
| 61: | public function getConnection(): DbalConnection |
| 62: | { |
| 63: | return $this->_connection; |
| 64: | } |
| 65: | |
| 66: | |
| 67: | |
| 68: | |
| 69: | |
| 70: | |
| 71: | |
| 72: | |
| 73: | |
| 74: | |
| 75: | |
| 76: | |
| 77: | |
| 78: | public static function normalizeDsn($dsn, $user = null, $password = null) |
| 79: | { |
| 80: | |
| 81: | if (is_string($dsn)) { |
| 82: | $dsn = ['dsn' => $dsn]; |
| 83: | } |
| 84: | if (isset($dsn['dsn'])) { |
| 85: | if (str_contains($dsn['dsn'], '://')) { |
| 86: | |
| 87: | $parsed = array_filter(parse_url($dsn['dsn'])); |
| 88: | $dsn['dsn'] = str_replace('-', '_', $parsed['scheme']) . ':'; |
| 89: | unset($parsed['scheme']); |
| 90: | foreach ($parsed as $k => $v) { |
| 91: | if ($k === 'pass') { |
| 92: | unset($parsed[$k]); |
| 93: | $k = 'password'; |
| 94: | } elseif ($k === 'path') { |
| 95: | unset($parsed[$k]); |
| 96: | $k = 'dbname'; |
| 97: | $v = preg_replace('~^/~', '', $v); |
| 98: | } |
| 99: | $parsed[$k] = $k . '=' . $v; |
| 100: | } |
| 101: | $dsn['dsn'] .= implode(';', $parsed); |
| 102: | } |
| 103: | |
| 104: | $parts = explode(':', $dsn['dsn'], 2); |
| 105: | $dsn = ['driver' => strtolower($parts[0])]; |
| 106: | if ($dsn['driver'] === 'sqlite') { |
| 107: | if (trim($parts[1], ':') === 'memory') { |
| 108: | $dsn['memory'] = true; |
| 109: | } else { |
| 110: | $dsn['path'] = trim($parts[1], ':'); |
| 111: | } |
| 112: | } else { |
| 113: | foreach (explode(';', $parts[1] ?? '') as $part) { |
| 114: | [$k, $v] = str_contains($part, '=') ? explode('=', $part, 2) : [$part, null]; |
| 115: | if ($k === 'query' || str_contains($part, '[')) { |
| 116: | parse_str($k === 'query' ? $v : $part, $partRes); |
| 117: | foreach ($partRes as $pK => $pV) { |
| 118: | $dsn[$pK] = $pV; |
| 119: | } |
| 120: | } else { |
| 121: | $dsn[$k] = $v; |
| 122: | } |
| 123: | } |
| 124: | if (isset($dsn['host']) && str_contains($dsn['host'], ':')) { |
| 125: | [$dsn['host'], $port] = explode(':', $dsn['host'], 2); |
| 126: | $dsn['port'] = $port; |
| 127: | } |
| 128: | } |
| 129: | } |
| 130: | |
| 131: | if ($user !== null) { |
| 132: | $dsn['user'] = $user; |
| 133: | } |
| 134: | |
| 135: | if ($password !== null) { |
| 136: | $dsn['password'] = $password; |
| 137: | } |
| 138: | |
| 139: | |
| 140: | $dsn['driver'] = [ |
| 141: | 'sqlite' => 'pdo_sqlite', |
| 142: | 'mysql' => 'mysqli', |
| 143: | 'pgsql' => 'pdo_pgsql', |
| 144: | 'sqlsrv' => 'pdo_sqlsrv', |
| 145: | 'oci' => 'oci8', |
| 146: | ][$dsn['driver']] ?? $dsn['driver']; |
| 147: | |
| 148: | return $dsn; |
| 149: | } |
| 150: | |
| 151: | |
| 152: | |
| 153: | |
| 154: | |
| 155: | |
| 156: | |
| 157: | |
| 158: | |
| 159: | public static function registerConnectionClass(string $connectionClass, string $driverName): void |
| 160: | { |
| 161: | self::$connectionClassRegistry[$driverName] = $connectionClass; |
| 162: | } |
| 163: | |
| 164: | |
| 165: | |
| 166: | |
| 167: | |
| 168: | |
| 169: | public static function resolveConnectionClass(string $driverName): string |
| 170: | { |
| 171: | if (!isset(self::$connectionClassRegistry[$driverName])) { |
| 172: | throw (new Exception('Driver schema is not registered')) |
| 173: | ->addMoreInfo('driver_schema', $driverName); |
| 174: | } |
| 175: | |
| 176: | return self::$connectionClassRegistry[$driverName]; |
| 177: | } |
| 178: | |
| 179: | |
| 180: | |
| 181: | |
| 182: | |
| 183: | |
| 184: | |
| 185: | |
| 186: | |
| 187: | public static function connect($dsn, $user = null, $password = null, $defaults = []): self |
| 188: | { |
| 189: | if ($dsn instanceof DbalConnection) { |
| 190: | $driverName = self::getDriverNameFromDbalDriverConnection($dsn->getWrappedConnection()); |
| 191: | $connectionClass = self::resolveConnectionClass($driverName); |
| 192: | $dbalConnection = $dsn; |
| 193: | } elseif ($dsn instanceof DbalDriverConnection) { |
| 194: | $driverName = self::getDriverNameFromDbalDriverConnection($dsn); |
| 195: | $connectionClass = self::resolveConnectionClass($driverName); |
| 196: | $dbalConnection = $connectionClass::connectFromDbalDriverConnection($dsn); |
| 197: | } else { |
| 198: | $dsn = static::normalizeDsn($dsn, $user, $password); |
| 199: | $connectionClass = self::resolveConnectionClass($dsn['driver']); |
| 200: | $dbalDriverConnection = $connectionClass::connectFromDsn($dsn); |
| 201: | $dbalConnection = $connectionClass::connectFromDbalDriverConnection($dbalDriverConnection); |
| 202: | } |
| 203: | |
| 204: | $dbalConnection->setNestTransactionsWithSavepoints(true); |
| 205: | |
| 206: | $connection = new $connectionClass($defaults); |
| 207: | $connection->_connection = $dbalConnection; |
| 208: | |
| 209: | return $connection; |
| 210: | } |
| 211: | |
| 212: | |
| 213: | |
| 214: | |
| 215: | private static function getDriverNameFromDbalDriverConnection(DbalDriverConnection $connection): string |
| 216: | { |
| 217: | $driver = $connection->getNativeConnection(); |
| 218: | |
| 219: | if ($driver instanceof \PDO) { |
| 220: | return 'pdo_' . $driver->getAttribute(\PDO::ATTR_DRIVER_NAME); |
| 221: | } elseif ($driver instanceof \mysqli) { |
| 222: | return 'mysqli'; |
| 223: | } elseif (is_resource($driver) && get_resource_type($driver) === 'oci8 connection') { |
| 224: | return 'oci8'; |
| 225: | } |
| 226: | |
| 227: | return null; |
| 228: | } |
| 229: | |
| 230: | protected static function createDbalConfiguration(): Configuration |
| 231: | { |
| 232: | $configuration = new Configuration(); |
| 233: | $configuration->setMiddlewares([ |
| 234: | new class() implements DbalMiddleware { |
| 235: | #[\Override] |
| 236: | public function wrap(DbalDriver $driver): DbalDriver |
| 237: | { |
| 238: | return new DbalDriverMiddleware($driver); |
| 239: | } |
| 240: | }, |
| 241: | ]); |
| 242: | |
| 243: | return $configuration; |
| 244: | } |
| 245: | |
| 246: | |
| 247: | |
| 248: | |
| 249: | protected static function connectFromDsn(array $dsn): DbalDriverConnection |
| 250: | { |
| 251: | $dsn = static::normalizeDsn($dsn); |
| 252: | if ($dsn['driver'] === 'pdo_mysql' || $dsn['driver'] === 'mysqli') { |
| 253: | $dsn['charset'] = 'utf8mb4'; |
| 254: | } elseif ($dsn['driver'] === 'pdo_oci' || $dsn['driver'] === 'oci8') { |
| 255: | $dsn['charset'] = 'AL32UTF8'; |
| 256: | } |
| 257: | |
| 258: | $dbalConnection = DriverManager::getConnection( |
| 259: | $dsn, |
| 260: | (static::class)::createDbalConfiguration() |
| 261: | ); |
| 262: | |
| 263: | return $dbalConnection->getWrappedConnection(); |
| 264: | } |
| 265: | |
| 266: | protected static function connectFromDbalDriverConnection(DbalDriverConnection $dbalDriverConnection): DbalConnection |
| 267: | { |
| 268: | $dbalConnection = DriverManager::getConnection( |
| 269: | ['driver' => self::getDriverNameFromDbalDriverConnection($dbalDriverConnection)], |
| 270: | (static::class)::createDbalConfiguration() |
| 271: | ); |
| 272: | \Closure::bind(static function () use ($dbalConnection, $dbalDriverConnection): void { |
| 273: | $dbalConnection->_conn = $dbalDriverConnection; |
| 274: | }, null, \Doctrine\DBAL\Connection::class)(); |
| 275: | |
| 276: | return $dbalConnection; |
| 277: | } |
| 278: | |
| 279: | |
| 280: | |
| 281: | |
| 282: | |
| 283: | |
| 284: | |
| 285: | public function expr($template = [], array $arguments = []): Expression |
| 286: | { |
| 287: | $class = $this->expressionClass; |
| 288: | $e = new $class($template, $arguments); |
| 289: | $e->connection = $this; |
| 290: | |
| 291: | return $e; |
| 292: | } |
| 293: | |
| 294: | |
| 295: | |
| 296: | |
| 297: | |
| 298: | |
| 299: | public function dsql($defaults = []): Query |
| 300: | { |
| 301: | $class = $this->queryClass; |
| 302: | $q = new $class($defaults); |
| 303: | $q->connection = $this; |
| 304: | |
| 305: | return $q; |
| 306: | } |
| 307: | |
| 308: | |
| 309: | |
| 310: | |
| 311: | public function executeQuery(Expression $expr): DbalResult |
| 312: | { |
| 313: | if ($this->_connection === null) { |
| 314: | throw new Exception('DBAL connection is not set'); |
| 315: | } |
| 316: | |
| 317: | return $expr->executeQuery($this->getConnection()); |
| 318: | } |
| 319: | |
| 320: | |
| 321: | |
| 322: | |
| 323: | |
| 324: | |
| 325: | public function executeStatement(Expression $expr): int |
| 326: | { |
| 327: | if ($this->_connection === null) { |
| 328: | throw new Exception('DBAL connection is not set'); |
| 329: | } |
| 330: | |
| 331: | return $expr->executeStatement($this->getConnection()); |
| 332: | } |
| 333: | |
| 334: | |
| 335: | |
| 336: | |
| 337: | |
| 338: | |
| 339: | |
| 340: | |
| 341: | |
| 342: | |
| 343: | |
| 344: | |
| 345: | public function atomic(\Closure $fx) |
| 346: | { |
| 347: | $this->beginTransaction(); |
| 348: | try { |
| 349: | $res = $fx(); |
| 350: | $this->commit(); |
| 351: | |
| 352: | return $res; |
| 353: | } catch (\Throwable $e) { |
| 354: | $this->rollBack(); |
| 355: | |
| 356: | throw $e; |
| 357: | } |
| 358: | } |
| 359: | |
| 360: | |
| 361: | |
| 362: | |
| 363: | |
| 364: | |
| 365: | |
| 366: | |
| 367: | |
| 368: | |
| 369: | |
| 370: | |
| 371: | |
| 372: | |
| 373: | |
| 374: | |
| 375: | |
| 376: | public function beginTransaction(): void |
| 377: | { |
| 378: | try { |
| 379: | $this->getConnection()->beginTransaction(); |
| 380: | } catch (DbalConnectionException $e) { |
| 381: | throw new Exception('Begin transaction failed', 0, $e); |
| 382: | } |
| 383: | } |
| 384: | |
| 385: | |
| 386: | |
| 387: | |
| 388: | |
| 389: | |
| 390: | |
| 391: | public function inTransaction(): bool |
| 392: | { |
| 393: | return $this->getConnection()->isTransactionActive(); |
| 394: | } |
| 395: | |
| 396: | |
| 397: | |
| 398: | |
| 399: | |
| 400: | |
| 401: | |
| 402: | |
| 403: | public function commit(): void |
| 404: | { |
| 405: | try { |
| 406: | $this->getConnection()->commit(); |
| 407: | } catch (DbalConnectionException $e) { |
| 408: | throw new Exception('Commit failed', 0, $e); |
| 409: | } |
| 410: | } |
| 411: | |
| 412: | |
| 413: | |
| 414: | |
| 415: | public function rollBack(): void |
| 416: | { |
| 417: | try { |
| 418: | $this->getConnection()->rollBack(); |
| 419: | } catch (DbalConnectionException $e) { |
| 420: | throw new Exception('Rollback failed', 0, $e); |
| 421: | } |
| 422: | } |
| 423: | |
| 424: | |
| 425: | |
| 426: | |
| 427: | |
| 428: | |
| 429: | public function lastInsertId(string $sequence = null): string |
| 430: | { |
| 431: | $res = $this->getConnection()->lastInsertId($sequence); |
| 432: | |
| 433: | return is_int($res) ? (string) $res : $res; |
| 434: | } |
| 435: | |
| 436: | public function getDatabasePlatform(): AbstractPlatform |
| 437: | { |
| 438: | return $this->getConnection()->getDatabasePlatform(); |
| 439: | } |
| 440: | |
| 441: | |
| 442: | |
| 443: | |
| 444: | public function createSchemaManager(): AbstractSchemaManager |
| 445: | { |
| 446: | return $this->getConnection()->createSchemaManager(); |
| 447: | } |
| 448: | } |
| 449: | |