diff --git a/composer.json b/composer.json index 0e7f49c7..8216a4e5 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ }, "extra": { "branch-alias": { - "dev-master": "5.1-dev" + "dev-master": "6.0-dev" } } } diff --git a/readme.md b/readme.md index 75b330b6..4319c7b8 100644 --- a/readme.md +++ b/readme.md @@ -34,7 +34,7 @@ Install Dibi via Composer: composer require dibi/dibi ``` -The Dibi 5.1 requires PHP version 8.2 and supports PHP up to 8.5. +The Dibi 6.0 requires PHP version 8.2 and supports PHP up to 8.5. Usage diff --git a/src/Dibi/Connection.php b/src/Dibi/Connection.php index b03e0e27..c7e24f5d 100644 --- a/src/Dibi/Connection.php +++ b/src/Dibi/Connection.php @@ -21,15 +21,28 @@ * @property-read int $affectedRows * @property-read int $insertId */ -class Connection implements IConnection +class Connection { + private const Drivers = [ + 'firebird' => Drivers\Ibase\Connection::class, + 'mysqli' => Drivers\MySQLi\Connection::class, + 'odbc' => Drivers\ODBC\Connection::class, + 'oracle' => Drivers\OCI8\Connection::class, + 'pdo' => Drivers\PDO\Connection::class, + 'postgre' => Drivers\PgSQL\Connection::class, + 'sqlite3' => Drivers\SQLite3\Connection::class, + 'sqlite' => Drivers\SQLite3\Connection::class, + 'sqlsrv' => Drivers\SQLSrv\Connection::class, + ]; + /** function (Event $event); Occurs after query is executed */ public ?array $onEvent = []; private array $config; /** @var string[] resultset formats */ private array $formats; - private ?Driver $driver = null; + private ?Drivers\Connection $driver = null; + private Drivers\Engine $engine; private ?Translator $translator = null; /** @var array */ @@ -122,17 +135,16 @@ public function __destruct() */ final public function connect(): void { - if ($this->config['driver'] instanceof Driver) { + if ($this->config['driver'] instanceof Drivers\Connection) { $this->driver = $this->config['driver']; $this->translator = new Translator($this); return; - } elseif (is_subclass_of($this->config['driver'], Driver::class)) { + } elseif (is_subclass_of($this->config['driver'], Drivers\Connection::class)) { $class = $this->config['driver']; } else { - $class = preg_replace(['#\W#', '#sql#'], ['_', 'Sql'], ucfirst(strtolower($this->config['driver']))); - $class = "Dibi\\Drivers\\{$class}Driver"; + $class = self::Drivers[strtolower($this->config['driver'])] ?? throw new Exception("Unknown driver '{$this->config['driver']}'."); if (!class_exists($class)) { throw new Exception("Unable to create instance of Dibi driver '$class'."); } @@ -198,7 +210,7 @@ final public function getConfig(?string $key = null, $default = null): mixed /** * Returns the driver and connects to a database in lazy mode. */ - final public function getDriver(): Driver + final public function getDriver(): Drivers\Connection { if (!$this->driver) { $this->connect(); @@ -286,7 +298,7 @@ final public function nativeQuery(#[Language('SQL')] string $sql): Result throw $e; } - $res = $this->createResultSet($res ?: new Drivers\NoDataResult(max(0, $this->driver->getAffectedRows()))); + $res = $this->createResultSet($res ?: new Drivers\Dummy\Result(max(0, $this->driver->getAffectedRows()))); if ($event) { $this->onEvent($event->done($res)); } @@ -450,7 +462,7 @@ public function transaction(callable $callback): mixed /** * Result set factory. */ - public function createResultSet(ResultDriver $resultDriver): Result + public function createResultSet(Drivers\Result $resultDriver): Result { return (new Result($resultDriver, $this->config['result']['normalize'] ?? true)) ->setFormats($this->formats); @@ -659,6 +671,15 @@ public function loadFile(string $file, ?callable $onProgress = null): int } + public function getDatabaseEngine(): Drivers\Engine + { + if (!$this->driver) { // TODO + $this->connect(); + } + return $this->engine ??= $this->driver->getReflector(); + } + + /** * Gets a information about the current database. */ @@ -668,7 +689,7 @@ public function getDatabaseInfo(): Reflection\Database $this->connect(); } - return new Reflection\Database($this->driver->getReflector(), $this->config['database'] ?? null); + return new Reflection\Database($this->getDatabaseEngine(), $this->config['database'] ?? null); } diff --git a/src/Dibi/DataSource.php b/src/Dibi/DataSource.php index 1ecc0ec5..c2c6d9a5 100644 --- a/src/Dibi/DataSource.php +++ b/src/Dibi/DataSource.php @@ -35,7 +35,7 @@ class DataSource implements IDataSource public function __construct(string $sql, Connection $connection) { $this->sql = strpbrk($sql, " \t\r\n") === false - ? $connection->getDriver()->escapeIdentifier($sql) // table name + ? $connection->getDatabaseEngine()->escapeIdentifier($sql) // table name : '(' . $sql . ') t'; // SQL command $this->connection = $connection; } diff --git a/src/Dibi/Drivers/Connection.php b/src/Dibi/Drivers/Connection.php new file mode 100644 index 00000000..6549e57f --- /dev/null +++ b/src/Dibi/Drivers/Connection.php @@ -0,0 +1,77 @@ +format("'Y-m-d'"); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return "'" . substr($value->format('Y-m-d H:i:s.u'), 0, -2) . "'"; + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = addcslashes($this->driver->escapeText($value), '%_\\'); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'") . " ESCAPE '\\'"; + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit > 0 || $offset > 0) { + // http://www.firebirdsql.org/refdocs/langrefupd20-select.html + $sql = 'SELECT ' . ($limit > 0 ? 'FIRST ' . $limit : '') . ($offset > 0 ? ' SKIP ' . $offset : '') . ' * FROM (' . $sql . ')'; + } + } + + /** * Returns list of tables. */ diff --git a/src/Dibi/Drivers/MySqlReflector.php b/src/Dibi/Drivers/Engines/MySQLEngine.php similarity index 65% rename from src/Dibi/Drivers/MySqlReflector.php rename to src/Dibi/Drivers/Engines/MySQLEngine.php index e782e63a..1db5491b 100644 --- a/src/Dibi/Drivers/MySqlReflector.php +++ b/src/Dibi/Drivers/Engines/MySQLEngine.php @@ -7,23 +7,85 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Engines; use Dibi; +use Dibi\Drivers\Connection; +use Dibi\Drivers\Engine; /** * The reflector for MySQL databases. * @internal */ -class MySqlReflector implements Dibi\Reflector +class MySQLEngine implements Engine { public function __construct( - private readonly Dibi\Driver $driver, + private readonly Connection $driver, ) { } + public function escapeIdentifier(string $value): string + { + return '`' . str_replace('`', '``', $value) . '`'; + } + + + public function escapeBool(bool $value): string + { + return $value ? '1' : '0'; + } + + + public function escapeDate(\DateTimeInterface $value): string + { + return $value->format("'Y-m-d'"); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return $value->format("'Y-m-d H:i:s.u'"); + } + + + public function escapeDateInterval(\DateInterval $value): string + { + if ($value->y || $value->m || $value->d) { + throw new Dibi\NotSupportedException('Only time interval is supported.'); + } + + return $value->format("'%r%H:%I:%S.%f'"); + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_"); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit < 0 || $offset < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + + } elseif ($limit !== null || $offset) { + // see http://dev.mysql.com/doc/refman/5.0/en/select.html + $sql .= ' LIMIT ' . ($limit ?? '18446744073709551615') + . ($offset ? ' OFFSET ' . $offset : ''); + } + } + + /** * Returns list of tables. */ @@ -47,7 +109,7 @@ public function getTables(): array */ public function getColumns(string $table): array { - $res = $this->driver->query("SHOW FULL COLUMNS FROM {$this->driver->escapeIdentifier($table)}"); + $res = $this->driver->query("SHOW FULL COLUMNS FROM {$this->escapeIdentifier($table)}"); $columns = []; while ($row = $res->fetch(true)) { $type = explode('(', $row['Type']); @@ -72,7 +134,7 @@ public function getColumns(string $table): array */ public function getIndexes(string $table): array { - $res = $this->driver->query("SHOW INDEX FROM {$this->driver->escapeIdentifier($table)}"); + $res = $this->driver->query("SHOW INDEX FROM {$this->escapeIdentifier($table)}"); $indexes = []; while ($row = $res->fetch(true)) { $indexes[$row['Key_name']]['name'] = $row['Key_name']; diff --git a/src/Dibi/Drivers/OdbcReflector.php b/src/Dibi/Drivers/Engines/ODBCEngine.php similarity index 52% rename from src/Dibi/Drivers/OdbcReflector.php rename to src/Dibi/Drivers/Engines/ODBCEngine.php index f259d447..3a3ad1d3 100644 --- a/src/Dibi/Drivers/OdbcReflector.php +++ b/src/Dibi/Drivers/Engines/ODBCEngine.php @@ -7,22 +7,81 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Engines; use Dibi; +use Dibi\Drivers\Connection; +use Dibi\Drivers\Engine; /** * The reflector for ODBC connections. */ -class OdbcReflector implements Dibi\Reflector +class ODBCEngine implements Engine { public function __construct( - private readonly Dibi\Driver $driver, + private readonly Connection $driver, ) { } + public function escapeIdentifier(string $value): string + { + return '[' . str_replace(['[', ']'], ['[[', ']]'], $value) . ']'; + } + + + public function escapeBool(bool $value): string + { + return $value ? '1' : '0'; + } + + + public function escapeDate(\DateTimeInterface $value): string + { + return $value->format('#m/d/Y#'); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return $value->format($this->microseconds ? '#m/d/Y H:i:s.u#' : '#m/d/Y H:i:s#'); // TODO + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($offset) { + throw new Dibi\NotSupportedException('Offset is not supported by this database.'); + + } elseif ($limit < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + + } elseif ($limit !== null) { + $sql = 'SELECT TOP ' . $limit . ' * FROM (' . $sql . ') t'; + } + } + + /** * Returns list of tables. */ diff --git a/src/Dibi/Drivers/Engines/OracleEngine.php b/src/Dibi/Drivers/Engines/OracleEngine.php new file mode 100644 index 00000000..620b1552 --- /dev/null +++ b/src/Dibi/Drivers/Engines/OracleEngine.php @@ -0,0 +1,153 @@ +nativeDate // TODO + ? "to_date('" . $value->format('Y-m-d') . "', 'YYYY-mm-dd')" + : $value->format('U'); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return $this->nativeDate // TODO + ? "to_date('" . $value->format('Y-m-d G:i:s') . "', 'YYYY-mm-dd hh24:mi:ss')" + : $value->format('U'); + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\\%_"); + $value = str_replace("'", "''", $value); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit < 0 || $offset < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + + } elseif ($offset) { + // see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html + $sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' + . ($limit !== null ? 'WHERE ROWNUM <= ' . ($offset + $limit) : '') + . ') WHERE "__rnum" > ' . $offset; + + } elseif ($limit !== null) { + $sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . $limit; + } + } + + + /** + * Returns list of tables. + */ + public function getTables(): array + { + $res = $this->driver->query('SELECT * FROM cat'); + $tables = []; + while ($row = $res->fetch(false)) { + if ($row[1] === 'TABLE' || $row[1] === 'VIEW') { + $tables[] = [ + 'name' => $row[0], + 'view' => $row[1] === 'VIEW', + ]; + } + } + + return $tables; + } + + + /** + * Returns metadata for all columns in a table. + */ + public function getColumns(string $table): array + { + $res = $this->driver->query('SELECT * FROM "ALL_TAB_COLUMNS" WHERE "TABLE_NAME" = ' . $this->driver->escapeText($table)); + $columns = []; + while ($row = $res->fetch(true)) { + $columns[] = [ + 'table' => $row['TABLE_NAME'], + 'name' => $row['COLUMN_NAME'], + 'nativetype' => $row['DATA_TYPE'], + 'size' => $row['DATA_LENGTH'] ?? null, + 'nullable' => $row['NULLABLE'] === 'Y', + 'default' => $row['DATA_DEFAULT'], + 'vendor' => $row, + ]; + } + + return $columns; + } + + + /** + * Returns metadata for all indexes in a table. + */ + public function getIndexes(string $table): array + { + throw new Dibi\NotImplementedException; + } + + + /** + * Returns metadata for all foreign keys in a table. + */ + public function getForeignKeys(string $table): array + { + throw new Dibi\NotImplementedException; + } +} diff --git a/src/Dibi/Drivers/PostgreReflector.php b/src/Dibi/Drivers/Engines/PostgreSQLEngine.php similarity index 76% rename from src/Dibi/Drivers/PostgreReflector.php rename to src/Dibi/Drivers/Engines/PostgreSQLEngine.php index ca4854fe..338be739 100644 --- a/src/Dibi/Drivers/PostgreReflector.php +++ b/src/Dibi/Drivers/Engines/PostgreSQLEngine.php @@ -7,22 +7,86 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Engines; use Dibi; +use Dibi\Drivers\Connection; +use Dibi\Drivers\Engine; /** * The reflector for PostgreSQL database. */ -class PostgreReflector implements Dibi\Reflector +class PostgreSQLEngine implements Engine { public function __construct( - private readonly Dibi\Driver $driver, + private readonly Connection $driver, ) { } + public function escapeIdentifier(string $value): string + { + // @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS + return '"' . str_replace('"', '""', $value) . '"'; + } + + + public function escapeBool(bool $value): string + { + return $value ? 'TRUE' : 'FALSE'; + } + + + public function escapeDate(\DateTimeInterface $value): string + { + return $value->format("'Y-m-d'"); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return $value->format("'Y-m-d H:i:s.u'"); + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $bs = $this->driver->escapeText('\\'); // standard_conforming_strings = on/off + $value = $this->driver->escapeText($value); + $value = strtr($value, ['%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\']); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit < 0 || $offset < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + } + + if ($limit !== null) { + $sql .= ' LIMIT ' . $limit; + } + + if ($offset) { + $sql .= ' OFFSET ' . $offset; + } + } + + /** * Returns list of tables. */ @@ -63,7 +127,7 @@ public function getTables(): array */ public function getColumns(string $table): array { - $_table = $this->driver->escapeText($this->driver->escapeIdentifier($table)); + $_table = $this->driver->escapeText($this->escapeIdentifier($table)); $res = $this->driver->query(" SELECT * @@ -123,7 +187,7 @@ public function getColumns(string $table): array */ public function getIndexes(string $table): array { - $_table = $this->driver->escapeText($this->driver->escapeIdentifier($table)); + $_table = $this->driver->escapeText($this->escapeIdentifier($table)); $res = $this->driver->query(" SELECT a.attnum AS ordinal_position, @@ -173,7 +237,7 @@ public function getIndexes(string $table): array */ public function getForeignKeys(string $table): array { - $_table = $this->driver->escapeText($this->driver->escapeIdentifier($table)); + $_table = $this->driver->escapeText($this->escapeIdentifier($table)); $res = $this->driver->query(" SELECT diff --git a/src/Dibi/Drivers/SqlsrvReflector.php b/src/Dibi/Drivers/Engines/SQLServerEngine.php similarity index 66% rename from src/Dibi/Drivers/SqlsrvReflector.php rename to src/Dibi/Drivers/Engines/SQLServerEngine.php index bbf0418d..ff1b620a 100644 --- a/src/Dibi/Drivers/SqlsrvReflector.php +++ b/src/Dibi/Drivers/Engines/SQLServerEngine.php @@ -7,23 +7,83 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Engines; use Dibi; -use function sprintf; +use Dibi\Drivers\Connection; +use Dibi\Drivers\Engine; /** * The reflector for Microsoft SQL Server and SQL Azure databases. */ -class SqlsrvReflector implements Dibi\Reflector +class SQLServerEngine implements Engine { public function __construct( - private readonly Dibi\Driver $driver, + private readonly Connection $driver, ) { } + public function escapeIdentifier(string $value): string + { + // @see https://msdn.microsoft.com/en-us/library/ms176027.aspx + return '[' . str_replace(']', ']]', $value) . ']'; + } + + + public function escapeBool(bool $value): string + { + return $value ? '1' : '0'; + } + + + public function escapeDate(\DateTimeInterface $value): string + { + return $value->format("'Y-m-d'"); + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return 'CONVERT(DATETIME2(7), ' . $value->format("'Y-m-d H:i:s.u'") . ')'; + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit < 0 || $offset < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + + } elseif ($limit !== null) { + // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx + $sql = sprintf('%s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY', rtrim($sql), $offset, $limit); + } elseif ($offset) { + // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx + $sql = sprintf('%s OFFSET %d ROWS', rtrim($sql), $offset); + } + } + + /** * Returns list of tables. */ diff --git a/src/Dibi/Drivers/SqliteReflector.php b/src/Dibi/Drivers/Engines/SQLiteEngine.php similarity index 64% rename from src/Dibi/Drivers/SqliteReflector.php rename to src/Dibi/Drivers/Engines/SQLiteEngine.php index 1d530997..703c03df 100644 --- a/src/Dibi/Drivers/SqliteReflector.php +++ b/src/Dibi/Drivers/Engines/SQLiteEngine.php @@ -7,22 +7,79 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Engines; use Dibi; +use Dibi\Drivers\Connection; +use Dibi\Drivers\Engine; /** * The reflector for SQLite database. */ -class SqliteReflector implements Dibi\Reflector +class SQLiteEngine implements Engine { public function __construct( - private readonly Dibi\Driver $driver, + private readonly Connection $driver, ) { } + public function escapeIdentifier(string $value): string + { + return '[' . strtr($value, '[]', ' ') . ']'; + } + + + public function escapeBool(bool $value): string + { + return $value ? '1' : '0'; + } + + + public function escapeDate(\DateTimeInterface $value): string + { + return $value->format($this->fmtDate); // TODO + } + + + public function escapeDateTime(\DateTimeInterface $value): string + { + return $value->format($this->fmtDateTime); // TODO + } + + + public function escapeDateInterval(\DateInterval $value): string + { + throw new Dibi\NotImplementedException; + } + + + /** + * Encodes string for use in a LIKE statement. + */ + public function escapeLike(string $value, int $pos): string + { + $value = addcslashes($this->driver->escapeText($value), '%_\\'); + return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'") . " ESCAPE '\\'"; + } + + + /** + * Injects LIMIT/OFFSET to the SQL query. + */ + public function applyLimit(string &$sql, ?int $limit, ?int $offset): void + { + if ($limit < 0 || $offset < 0) { + throw new Dibi\NotSupportedException('Negative offset or limit.'); + + } elseif ($limit !== null || $offset) { + $sql .= ' LIMIT ' . ($limit ?? '-1') + . ($offset ? ' OFFSET ' . $offset : ''); + } + } + + /** * Returns list of tables. */ @@ -48,7 +105,7 @@ public function getTables(): array */ public function getColumns(string $table): array { - $res = $this->driver->query("PRAGMA table_info({$this->driver->escapeIdentifier($table)})"); + $res = $this->driver->query("PRAGMA table_info({$this->escapeIdentifier($table)})"); $columns = []; while ($row = $res->fetch(true)) { $column = $row['name']; @@ -75,7 +132,7 @@ public function getColumns(string $table): array */ public function getIndexes(string $table): array { - $res = $this->driver->query("PRAGMA index_list({$this->driver->escapeIdentifier($table)})"); + $res = $this->driver->query("PRAGMA index_list({$this->escapeIdentifier($table)})"); $indexes = []; while ($row = $res->fetch(true)) { $indexes[$row['name']]['name'] = $row['name']; @@ -83,7 +140,7 @@ public function getIndexes(string $table): array } foreach ($indexes as $index => $values) { - $res = $this->driver->query("PRAGMA index_info({$this->driver->escapeIdentifier($index)})"); + $res = $this->driver->query("PRAGMA index_info({$this->escapeIdentifier($index)})"); while ($row = $res->fetch(true)) { $indexes[$index]['columns'][$row['seqno']] = $row['name']; } @@ -126,7 +183,7 @@ public function getIndexes(string $table): array */ public function getForeignKeys(string $table): array { - $res = $this->driver->query("PRAGMA foreign_key_list({$this->driver->escapeIdentifier($table)})"); + $res = $this->driver->query("PRAGMA foreign_key_list({$this->escapeIdentifier($table)})"); $keys = []; while ($row = $res->fetch(true)) { $keys[$row['id']]['name'] = $row['id']; // foreign key name diff --git a/src/Dibi/Drivers/FirebirdDriver.php b/src/Dibi/Drivers/Firebird/Connection.php similarity index 77% rename from src/Dibi/Drivers/FirebirdDriver.php rename to src/Dibi/Drivers/Firebird/Connection.php index ade68165..1cdbe091 100644 --- a/src/Dibi/Drivers/FirebirdDriver.php +++ b/src/Dibi/Drivers/Firebird/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Ibase; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use function is_resource; @@ -25,11 +26,11 @@ * - buffers (int) => buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. * - resource (resource) => existing connection resource */ -class FirebirdDriver implements Dibi\Driver +class Connection implements Drivers\Connection { public const ErrorExceptionThrown = -836; - /** @deprecated use FirebirdDriver::ErrorExceptionThrown */ + #[\Deprecated('use FirebirdDriver::ErrorExceptionThrown')] public const ERROR_EXCEPTION_THROWN = self::ErrorExceptionThrown; /** @var resource */ @@ -86,7 +87,7 @@ public function disconnect(): void * Executes the SQL query. * @throws Dibi\DriverException|Dibi\Exception */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $resource = $this->inTransaction ? $this->transaction @@ -200,9 +201,9 @@ public function getResource(): mixed /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new FirebirdReflector($this); + return new Drivers\Engines\FirebirdEngine($this); } @@ -210,9 +211,9 @@ public function getReflector(): Dibi\Reflector * Result set driver factory. * @param resource $resource */ - public function createResultDriver($resource): FirebirdResult + public function createResultDriver($resource): Result { - return new FirebirdResult($resource); + return new Result($resource); } @@ -232,56 +233,4 @@ public function escapeBinary(string $value): string { return "'" . str_replace("'", "''", $value) . "'"; } - - - public function escapeIdentifier(string $value): string - { - return '"' . str_replace('"', '""', $value) . '"'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d'"); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return "'" . substr($value->format('Y-m-d H:i:s.u'), 0, -2) . "'"; - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = addcslashes($this->escapeText($value), '%_\\'); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'") . " ESCAPE '\\'"; - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit > 0 || $offset > 0) { - // http://www.firebirdsql.org/refdocs/langrefupd20-select.html - $sql = 'SELECT ' . ($limit > 0 ? 'FIRST ' . $limit : '') . ($offset > 0 ? ' SKIP ' . $offset : '') . ' * FROM (' . $sql . ')'; - } - } } diff --git a/src/Dibi/Drivers/FirebirdResult.php b/src/Dibi/Drivers/Firebird/Result.php similarity index 94% rename from src/Dibi/Drivers/FirebirdResult.php rename to src/Dibi/Drivers/Firebird/Result.php index fba78435..c979973a 100644 --- a/src/Dibi/Drivers/FirebirdResult.php +++ b/src/Dibi/Drivers/Firebird/Result.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\Ibase; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use function is_resource; @@ -17,7 +18,7 @@ /** * The driver for Firebird/InterBase result set. */ -class FirebirdResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( /** @var resource */ @@ -46,7 +47,7 @@ public function fetch(bool $assoc): ?array : @ibase_fetch_row($this->resultSet, IBASE_TEXT); // intentionally @ if (ibase_errcode()) { - if (ibase_errcode() === FirebirdDriver::ERROR_EXCEPTION_THROWN) { + if (ibase_errcode() === Connection::ERROR_EXCEPTION_THROWN) { preg_match('/exception (\d+) (\w+) (.*)/is', ibase_errmsg(), $match); throw new Dibi\ProcedureException($match[3], $match[1], $match[2]); diff --git a/src/Dibi/Drivers/MySqliDriver.php b/src/Dibi/Drivers/MySQLi/Connection.php similarity index 79% rename from src/Dibi/Drivers/MySqliDriver.php rename to src/Dibi/Drivers/MySQLi/Connection.php index 1d475266..4eed92ab 100644 --- a/src/Dibi/Drivers/MySqliDriver.php +++ b/src/Dibi/Drivers/MySQLi/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\MySQLi; use Dibi; +use Dibi\Drivers; use function in_array; use const MYSQLI_REPORT_OFF, MYSQLI_STORE_RESULT, MYSQLI_USE_RESULT, PREG_SET_ORDER; @@ -32,19 +33,19 @@ * - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html * - resource (mysqli) => existing connection resource */ -class MySqliDriver implements Dibi\Driver +class Connection implements Drivers\Connection { public const ErrorAccessDenied = 1045; public const ErrorDuplicateEntry = 1062; public const ErrorDataTruncated = 1265; - /** @deprecated use MySqliDriver::ErrorAccessDenied */ + #[\Deprecated('use MySqliDriver::ErrorAccessDenied')] public const ERROR_ACCESS_DENIED = self::ErrorAccessDenied; - /** @deprecated use MySqliDriver::ErrorDuplicateEntry */ + #[\Deprecated('use MySqliDriver::ErrorDuplicateEntry')] public const ERROR_DUPLICATE_ENTRY = self::ErrorDuplicateEntry; - /** @deprecated use MySqliDriver::ErrorDataTruncated */ + #[\Deprecated('use MySqliDriver::ErrorDataTruncated')] public const ERROR_DATA_TRUNCATED = self::ErrorDataTruncated; private \mysqli $connection; @@ -148,7 +149,7 @@ public function ping(): bool * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $res = @$this->connection->query($sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @ @@ -265,18 +266,18 @@ public function getResource(): ?\mysqli /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new MySqlReflector($this); + return new Drivers\Engines\MySQLEngine($this); } /** * Result set driver factory. */ - public function createResultDriver(\mysqli_result $result): MySqliResult + public function createResultDriver(\mysqli_result $result): Result { - return new MySqliResult($result, $this->buffered); + return new Result($result, $this->buffered); } @@ -296,64 +297,4 @@ public function escapeBinary(string $value): string { return "_binary'" . $this->connection->escape_string($value) . "'"; } - - - public function escapeIdentifier(string $value): string - { - return '`' . str_replace('`', '``', $value) . '`'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d'"); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d H:i:s.u'"); - } - - - public function escapeDateInterval(\DateInterval $value): string - { - if ($value->y || $value->m || $value->d) { - throw new Dibi\NotSupportedException('Only time interval is supported.'); - } - - return $value->format("'%r%H:%I:%S.%f'"); - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_"); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - - } elseif ($limit !== null || $offset) { - // see http://dev.mysql.com/doc/refman/5.0/en/select.html - $sql .= ' LIMIT ' . ($limit ?? '18446744073709551615') - . ($offset ? ' OFFSET ' . $offset : ''); - } - } } diff --git a/src/Dibi/Drivers/MySqliResult.php b/src/Dibi/Drivers/MySQLi/Result.php similarity index 96% rename from src/Dibi/Drivers/MySqliResult.php rename to src/Dibi/Drivers/MySQLi/Result.php index 6276e5f7..2fe38f67 100644 --- a/src/Dibi/Drivers/MySqliResult.php +++ b/src/Dibi/Drivers/MySQLi/Result.php @@ -7,16 +7,17 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\MySQLi; use Dibi; +use Dibi\Drivers; use const MYSQLI_TYPE_LONG, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_TIME, MYSQLI_TYPE_TINY; /** * The driver for MySQL result set. */ -class MySqliResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( private readonly \mysqli_result $resultSet, diff --git a/src/Dibi/Drivers/OracleDriver.php b/src/Dibi/Drivers/OCI8/Connection.php similarity index 71% rename from src/Dibi/Drivers/OracleDriver.php rename to src/Dibi/Drivers/OCI8/Connection.php index 63601761..46b022be 100644 --- a/src/Dibi/Drivers/OracleDriver.php +++ b/src/Dibi/Drivers/OCI8/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\OCI8; use Dibi; +use Dibi\Drivers; use function in_array, is_resource; @@ -26,7 +27,7 @@ * - resource (resource) => existing connection resource * - persistent => Creates persistent connections with oci_pconnect instead of oci_new_connect */ -class OracleDriver implements Dibi\Driver +class Connection implements Drivers\Connection { /** @var resource */ private $connection; @@ -77,7 +78,7 @@ public function disconnect(): void * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $this->affectedRows = null; $res = oci_parse($this->connection, $sql); @@ -190,9 +191,9 @@ public function getResource(): mixed /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new OracleReflector($this); + return new Drivers\Engines\OracleEngine($this); } @@ -200,9 +201,9 @@ public function getReflector(): Dibi\Reflector * Result set driver factory. * @param resource $resource */ - public function createResultDriver($resource): OracleResult + public function createResultDriver($resource): Result { - return new OracleResult($resource); + return new Result($resource); } @@ -222,70 +223,4 @@ public function escapeBinary(string $value): string { return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested } - - - public function escapeIdentifier(string $value): string - { - // @see http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/sql_elements9a.htm - return '"' . str_replace('"', '""', $value) . '"'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $this->nativeDate - ? "to_date('" . $value->format('Y-m-d') . "', 'YYYY-mm-dd')" - : $value->format('U'); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return $this->nativeDate - ? "to_date('" . $value->format('Y-m-d G:i:s') . "', 'YYYY-mm-dd hh24:mi:ss')" - : $value->format('U'); - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\\%_"); - $value = str_replace("'", "''", $value); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - - } elseif ($offset) { - // see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html - $sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' - . ($limit !== null ? 'WHERE ROWNUM <= ' . ($offset + $limit) : '') - . ') WHERE "__rnum" > ' . $offset; - - } elseif ($limit !== null) { - $sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . $limit; - } - } } diff --git a/src/Dibi/Drivers/OracleResult.php b/src/Dibi/Drivers/OCI8/Result.php similarity index 96% rename from src/Dibi/Drivers/OracleResult.php rename to src/Dibi/Drivers/OCI8/Result.php index e601f5a1..e9c5c584 100644 --- a/src/Dibi/Drivers/OracleResult.php +++ b/src/Dibi/Drivers/OCI8/Result.php @@ -7,16 +7,17 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\OCI8; use Dibi; +use Dibi\Drivers; use function is_resource; /** * The driver for Oracle result set. */ -class OracleResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( /** @var resource */ diff --git a/src/Dibi/Drivers/OdbcDriver.php b/src/Dibi/Drivers/ODBC/Connection.php similarity index 73% rename from src/Dibi/Drivers/OdbcDriver.php rename to src/Dibi/Drivers/ODBC/Connection.php index 8d87897c..b76863db 100644 --- a/src/Dibi/Drivers/OdbcDriver.php +++ b/src/Dibi/Drivers/ODBC/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\ODBC; use Dibi; +use Dibi\Drivers; use function is_resource; @@ -24,7 +25,7 @@ * - resource (resource) => existing connection resource * - microseconds (bool) => use microseconds in datetime format? */ -class OdbcDriver implements Dibi\Driver +class Connection implements Drivers\Connection { /** @var resource */ private $connection; @@ -77,7 +78,7 @@ public function disconnect(): void * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $this->affectedRows = null; $res = @odbc_exec($this->connection, $sql); // intentionally @ @@ -176,9 +177,9 @@ public function getResource(): mixed /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new OdbcReflector($this); + return new Drivers\Engines\ODBCEngine($this); } @@ -186,9 +187,9 @@ public function getReflector(): Dibi\Reflector * Result set driver factory. * @param resource $resource */ - public function createResultDriver($resource): OdbcResult + public function createResultDriver($resource): Result { - return new OdbcResult($resource); + return new Result($resource); } @@ -208,61 +209,4 @@ public function escapeBinary(string $value): string { return "'" . str_replace("'", "''", $value) . "'"; } - - - public function escapeIdentifier(string $value): string - { - return '[' . str_replace(['[', ']'], ['[[', ']]'], $value) . ']'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format('#m/d/Y#'); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return $value->format($this->microseconds ? '#m/d/Y H:i:s.u#' : '#m/d/Y H:i:s#'); - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($offset) { - throw new Dibi\NotSupportedException('Offset is not supported by this database.'); - - } elseif ($limit < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - - } elseif ($limit !== null) { - $sql = 'SELECT TOP ' . $limit . ' * FROM (' . $sql . ') t'; - } - } } diff --git a/src/Dibi/Drivers/OdbcResult.php b/src/Dibi/Drivers/ODBC/Result.php similarity index 96% rename from src/Dibi/Drivers/OdbcResult.php rename to src/Dibi/Drivers/ODBC/Result.php index e86d2871..5ae5aad9 100644 --- a/src/Dibi/Drivers/OdbcResult.php +++ b/src/Dibi/Drivers/ODBC/Result.php @@ -7,16 +7,17 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\ODBC; use Dibi; +use Dibi\Drivers; use function is_resource; /** * The driver interacting with result set via ODBC connections. */ -class OdbcResult implements Dibi\ResultDriver +class Result implements Drivers\Result { private int $row = 0; diff --git a/src/Dibi/Drivers/OracleReflector.php b/src/Dibi/Drivers/OracleReflector.php deleted file mode 100644 index 2307063d..00000000 --- a/src/Dibi/Drivers/OracleReflector.php +++ /dev/null @@ -1,85 +0,0 @@ -driver->query('SELECT * FROM cat'); - $tables = []; - while ($row = $res->fetch(false)) { - if ($row[1] === 'TABLE' || $row[1] === 'VIEW') { - $tables[] = [ - 'name' => $row[0], - 'view' => $row[1] === 'VIEW', - ]; - } - } - - return $tables; - } - - - /** - * Returns metadata for all columns in a table. - */ - public function getColumns(string $table): array - { - $res = $this->driver->query('SELECT * FROM "ALL_TAB_COLUMNS" WHERE "TABLE_NAME" = ' . $this->driver->escapeText($table)); - $columns = []; - while ($row = $res->fetch(true)) { - $columns[] = [ - 'table' => $row['TABLE_NAME'], - 'name' => $row['COLUMN_NAME'], - 'nativetype' => $row['DATA_TYPE'], - 'size' => $row['DATA_LENGTH'] ?? null, - 'nullable' => $row['NULLABLE'] === 'Y', - 'default' => $row['DATA_DEFAULT'], - 'vendor' => $row, - ]; - } - - return $columns; - } - - - /** - * Returns metadata for all indexes in a table. - */ - public function getIndexes(string $table): array - { - throw new Dibi\NotImplementedException; - } - - - /** - * Returns metadata for all foreign keys in a table. - */ - public function getForeignKeys(string $table): array - { - throw new Dibi\NotImplementedException; - } -} diff --git a/src/Dibi/Drivers/PDO/Connection.php b/src/Dibi/Drivers/PDO/Connection.php new file mode 100644 index 00000000..7e56a9d7 --- /dev/null +++ b/src/Dibi/Drivers/PDO/Connection.php @@ -0,0 +1,223 @@ + driver specific DSN + * - username (or user) + * - password (or pass) + * - options (array) => driver specific options {@see PDO::__construct} + * - resource (PDO) => existing connection + */ +class Connection implements Drivers\Connection +{ + private ?PDO $connection; + private ?int $affectedRows; + private string $driverName; + + + /** @throws Dibi\NotSupportedException */ + public function __construct(array $config) + { + if (!extension_loaded('pdo')) { + throw new Dibi\NotSupportedException("PHP extension 'pdo' is not loaded."); + } + + $foo = &$config['dsn']; + $foo = &$config['options']; + Helpers::alias($config, 'resource', 'pdo'); + + if ($config['resource'] instanceof PDO) { + $this->connection = $config['resource']; + unset($config['resource'], $config['pdo']); + + if ($this->connection->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_SILENT) { + throw new Dibi\DriverException('PDO connection in exception or warning error mode is not supported.'); + } + } else { + try { + $this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']); + $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); + } catch (\PDOException $e) { + if ($e->getMessage() === 'could not find driver') { + throw new Dibi\NotSupportedException('PHP extension for PDO is not loaded.'); + } + + throw new Dibi\DriverException($e->getMessage(), $e->getCode()); + } + } + + $this->driverName = $this->connection->getAttribute(PDO::ATTR_DRIVER_NAME); + } + + + /** + * Disconnects from a database. + */ + public function disconnect(): void + { + $this->connection = null; + } + + + /** + * Executes the SQL query. + * @throws Dibi\DriverException + */ + public function query(string $sql): ?Result + { + $res = $this->connection->query($sql); + if ($res) { + $this->affectedRows = $res->rowCount(); + return $res->columnCount() ? $this->createResultDriver($res) : null; + } + + $this->affectedRows = null; + + [$sqlState, $code, $message] = $this->connection->errorInfo(); + $code ??= 0; + $message = "SQLSTATE[$sqlState]: $message"; + throw match ($this->driverName) { + 'mysql' => Drivers\MySQLi\Connection::createException($message, $code, $sql), + 'oci' => Drivers\OCI8\Connection::createException($message, $code, $sql), + 'pgsql' => Drivers\PgSQL\Connection::createException($message, $sqlState, $sql), + 'sqlite' => Drivers\SQLite3\Connection::createException($message, $code, $sql), + default => new Dibi\DriverException($message, $code, $sql), + }; + } + + + /** + * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query. + */ + public function getAffectedRows(): ?int + { + return $this->affectedRows; + } + + + /** + * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. + */ + public function getInsertId(?string $sequence): ?int + { + return Helpers::intVal($this->connection->lastInsertId($sequence)); + } + + + /** + * Begins a transaction (if supported). + * @throws Dibi\DriverException + */ + public function begin(?string $savepoint = null): void + { + if (!$this->connection->beginTransaction()) { + $err = $this->connection->errorInfo(); + throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); + } + } + + + /** + * Commits statements in a transaction. + * @throws Dibi\DriverException + */ + public function commit(?string $savepoint = null): void + { + if (!$this->connection->commit()) { + $err = $this->connection->errorInfo(); + throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); + } + } + + + /** + * Rollback changes in a transaction. + * @throws Dibi\DriverException + */ + public function rollback(?string $savepoint = null): void + { + if (!$this->connection->rollBack()) { + $err = $this->connection->errorInfo(); + throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); + } + } + + + /** + * Returns the connection resource. + */ + public function getResource(): ?PDO + { + return $this->connection; + } + + + /** + * Returns the connection reflector. + */ + public function getReflector(): Drivers\Engine + { + return match ($this->driverName) { + 'mysql' => new Engines\MySQLEngine($this), + 'oci' => new Engines\OracleEngine($this), + 'pgsql' => new Engines\PostgreSQLEngine($this), + 'sqlite' => new Engines\SQLiteEngine($this), + 'mssql', 'dblib', 'sqlsrv' => new Engines\SQLServerEngine($this), + default => throw new Dibi\NotSupportedException, + }; + } + + + /** + * Result set driver factory. + */ + public function createResultDriver(\PDOStatement $result): Result + { + return new Result($result, $this->driverName); + } + + + /********************* SQL ****************d*g**/ + + + /** + * Encodes data for use in a SQL statement. + */ + public function escapeText(string $value): string + { + return match ($this->driverName) { + 'odbc' => "'" . str_replace("'", "''", $value) . "'", + 'sqlsrv' => "N'" . str_replace("'", "''", $value) . "'", + default => $this->connection->quote($value, PDO::PARAM_STR), + }; + } + + + public function escapeBinary(string $value): string + { + return match ($this->driverName) { + 'odbc' => "'" . str_replace("'", "''", $value) . "'", + 'sqlsrv' => '0x' . bin2hex($value), + default => $this->connection->quote($value, PDO::PARAM_LOB), + }; + } +} diff --git a/src/Dibi/Drivers/PdoResult.php b/src/Dibi/Drivers/PDO/Result.php similarity index 96% rename from src/Dibi/Drivers/PdoResult.php rename to src/Dibi/Drivers/PDO/Result.php index a7941503..9365c4c4 100644 --- a/src/Dibi/Drivers/PdoResult.php +++ b/src/Dibi/Drivers/PDO/Result.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\PDO; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use PDO; @@ -17,7 +18,7 @@ /** * The driver for PDO result set. */ -class PdoResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( private ?\PDOStatement $resultSet, diff --git a/src/Dibi/Drivers/PdoDriver.php b/src/Dibi/Drivers/PdoDriver.php deleted file mode 100644 index a6abb8f3..00000000 --- a/src/Dibi/Drivers/PdoDriver.php +++ /dev/null @@ -1,382 +0,0 @@ - driver specific DSN - * - username (or user) - * - password (or pass) - * - options (array) => driver specific options {@see PDO::__construct} - * - resource (PDO) => existing connection - */ -class PdoDriver implements Dibi\Driver -{ - private ?PDO $connection; - private ?int $affectedRows; - private string $driverName; - - - /** @throws Dibi\NotSupportedException */ - public function __construct(array $config) - { - if (!extension_loaded('pdo')) { - throw new Dibi\NotSupportedException("PHP extension 'pdo' is not loaded."); - } - - $foo = &$config['dsn']; - $foo = &$config['options']; - Helpers::alias($config, 'resource', 'pdo'); - - if ($config['resource'] instanceof PDO) { - $this->connection = $config['resource']; - unset($config['resource'], $config['pdo']); - - if ($this->connection->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_SILENT) { - throw new Dibi\DriverException('PDO connection in exception or warning error mode is not supported.'); - } - } else { - try { - $this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']); - $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); - } catch (\PDOException $e) { - if ($e->getMessage() === 'could not find driver') { - throw new Dibi\NotSupportedException('PHP extension for PDO is not loaded.'); - } - - throw new Dibi\DriverException($e->getMessage(), $e->getCode()); - } - } - - $this->driverName = $this->connection->getAttribute(PDO::ATTR_DRIVER_NAME); - } - - - /** - * Disconnects from a database. - */ - public function disconnect(): void - { - $this->connection = null; - } - - - /** - * Executes the SQL query. - * @throws Dibi\DriverException - */ - public function query(string $sql): ?Dibi\ResultDriver - { - $res = $this->connection->query($sql); - if ($res) { - $this->affectedRows = $res->rowCount(); - return $res->columnCount() ? $this->createResultDriver($res) : null; - } - - $this->affectedRows = null; - - [$sqlState, $code, $message] = $this->connection->errorInfo(); - $code ??= 0; - $message = "SQLSTATE[$sqlState]: $message"; - throw match ($this->driverName) { - 'mysql' => MySqliDriver::createException($message, $code, $sql), - 'oci' => OracleDriver::createException($message, $code, $sql), - 'pgsql' => PostgreDriver::createException($message, $sqlState, $sql), - 'sqlite' => SqliteDriver::createException($message, $code, $sql), - default => new Dibi\DriverException($message, $code, $sql), - }; - } - - - /** - * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query. - */ - public function getAffectedRows(): ?int - { - return $this->affectedRows; - } - - - /** - * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. - */ - public function getInsertId(?string $sequence): ?int - { - return Helpers::intVal($this->connection->lastInsertId($sequence)); - } - - - /** - * Begins a transaction (if supported). - * @throws Dibi\DriverException - */ - public function begin(?string $savepoint = null): void - { - if (!$this->connection->beginTransaction()) { - $err = $this->connection->errorInfo(); - throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); - } - } - - - /** - * Commits statements in a transaction. - * @throws Dibi\DriverException - */ - public function commit(?string $savepoint = null): void - { - if (!$this->connection->commit()) { - $err = $this->connection->errorInfo(); - throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); - } - } - - - /** - * Rollback changes in a transaction. - * @throws Dibi\DriverException - */ - public function rollback(?string $savepoint = null): void - { - if (!$this->connection->rollBack()) { - $err = $this->connection->errorInfo(); - throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1] ?? 0); - } - } - - - /** - * Returns the connection resource. - */ - public function getResource(): ?PDO - { - return $this->connection; - } - - - /** - * Returns the connection reflector. - */ - public function getReflector(): Dibi\Reflector - { - return match ($this->driverName) { - 'mysql' => new MySqlReflector($this), - 'oci' => new OracleReflector($this), - 'pgsql' => new PostgreReflector($this), - 'sqlite' => new SqliteReflector($this), - 'mssql', 'dblib', 'sqlsrv' => new SqlsrvReflector($this), - default => throw new Dibi\NotSupportedException, - }; - } - - - /** - * Result set driver factory. - */ - public function createResultDriver(\PDOStatement $result): PdoResult - { - return new PdoResult($result, $this->driverName); - } - - - /********************* SQL ****************d*g**/ - - - /** - * Encodes data for use in a SQL statement. - */ - public function escapeText(string $value): string - { - return match ($this->driverName) { - 'odbc' => "'" . str_replace("'", "''", $value) . "'", - 'sqlsrv' => "N'" . str_replace("'", "''", $value) . "'", - default => $this->connection->quote($value, PDO::PARAM_STR), - }; - } - - - public function escapeBinary(string $value): string - { - return match ($this->driverName) { - 'odbc' => "'" . str_replace("'", "''", $value) . "'", - 'sqlsrv' => '0x' . bin2hex($value), - default => $this->connection->quote($value, PDO::PARAM_LOB), - }; - } - - - public function escapeIdentifier(string $value): string - { - return match ($this->driverName) { - 'mysql' => '`' . str_replace('`', '``', $value) . '`', - 'oci', 'pgsql' => '"' . str_replace('"', '""', $value) . '"', - 'sqlite' => '[' . strtr($value, '[]', ' ') . ']', - 'odbc', 'mssql' => '[' . str_replace(['[', ']'], ['[[', ']]'], $value) . ']', - 'dblib', 'sqlsrv' => '[' . str_replace(']', ']]', $value) . ']', - default => $value, - }; - } - - - public function escapeBool(bool $value): string - { - if ($this->driverName === 'pgsql') { - return $value ? 'TRUE' : 'FALSE'; - } else { - return $value ? '1' : '0'; - } - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format($this->driverName === 'odbc' ? '#m/d/Y#' : "'Y-m-d'"); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return match ($this->driverName) { - 'odbc' => $value->format('#m/d/Y H:i:s.u#'), - 'mssql', 'dblib', 'sqlsrv' => 'CONVERT(DATETIME2(7), ' . $value->format("'Y-m-d H:i:s.u'") . ')', - default => $value->format("'Y-m-d H:i:s.u'"), - }; - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - switch ($this->driverName) { - case 'mysql': - $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_"); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - - case 'oci': - $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\\%_"); - $value = str_replace("'", "''", $value); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - - case 'pgsql': - $bs = substr($this->connection->quote('\\', PDO::PARAM_STR), 1, -1); // standard_conforming_strings = on/off - $value = substr($this->connection->quote($value, PDO::PARAM_STR), 1, -1); - $value = strtr($value, ['%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\']); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - - case 'sqlite': - $value = addcslashes(substr($this->connection->quote($value, PDO::PARAM_STR), 1, -1), '%_\\'); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'") . " ESCAPE '\\'"; - - case 'odbc': - case 'mssql': - case 'dblib': - case 'sqlsrv': - $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - - default: - throw new Dibi\NotImplementedException; - } - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - } - - switch ($this->driverName) { - case 'mysql': - if ($limit !== null || $offset) { - // see http://dev.mysql.com/doc/refman/5.0/en/select.html - $sql .= ' LIMIT ' . ($limit ?? '18446744073709551615') - . ($offset ? ' OFFSET ' . $offset : ''); - } - - break; - - case 'pgsql': - if ($limit !== null) { - $sql .= ' LIMIT ' . $limit; - } - - if ($offset) { - $sql .= ' OFFSET ' . $offset; - } - - break; - - case 'sqlite': - if ($limit !== null || $offset) { - $sql .= ' LIMIT ' . ($limit ?? '-1') - . ($offset ? ' OFFSET ' . $offset : ''); - } - - break; - - case 'oci': - if ($offset) { - // see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html - $sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' - . ($limit !== null ? 'WHERE ROWNUM <= ' . ($offset + $limit) : '') - . ') WHERE "__rnum" > ' . $offset; - - } elseif ($limit !== null) { - $sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . $limit; - } - - break; - - case 'mssql': - case 'sqlsrv': - case 'dblib': - // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx - if ($limit !== null) { - $sql = sprintf('%s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY', rtrim($sql), $offset, $limit); - } elseif ($offset) { - $sql = sprintf('%s OFFSET %d ROWS', rtrim($sql), $offset); - } - - break; - - case 'odbc': - if ($offset) { - throw new Dibi\NotSupportedException('Offset is not supported by this database.'); - - } elseif ($limit !== null) { - $sql = 'SELECT TOP ' . $limit . ' * FROM (' . $sql . ') t'; - break; - } - // break omitted - default: - throw new Dibi\NotSupportedException('PDO or driver does not support applying limit or offset.'); - } - } -} diff --git a/src/Dibi/Drivers/PostgreDriver.php b/src/Dibi/Drivers/PgSQL/Connection.php similarity index 78% rename from src/Dibi/Drivers/PostgreDriver.php rename to src/Dibi/Drivers/PgSQL/Connection.php index 637b96d7..cba724aa 100644 --- a/src/Dibi/Drivers/PostgreDriver.php +++ b/src/Dibi/Drivers/PgSQL/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\PgSQL; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use PgSql; use function in_array, is_array, is_resource, strlen; @@ -27,7 +28,7 @@ * - resource (PgSql\Connection) => existing connection resource * - connect_type (int) => see pg_connect() */ -class PostgreDriver implements Dibi\Driver +class Connection implements Drivers\Connection { private PgSql\Connection $connection; private ?int $affectedRows; @@ -110,7 +111,7 @@ public function ping(): bool * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $this->affectedRows = null; $res = @pg_query($this->connection, $sql); // intentionally @ @@ -232,18 +233,18 @@ public function getResource(): PgSql\Connection /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new PostgreReflector($this); + return new Drivers\Engines\PostgreSQLEngine($this); } /** * Result set driver factory. */ - public function createResultDriver(PgSql\Result $resource): PostgreResult + public function createResultDriver(PgSql\Result $resource): Result { - return new PostgreResult($resource); + return new Result($resource); } @@ -271,66 +272,4 @@ public function escapeBinary(string $value): string return "'" . pg_escape_bytea($this->connection, $value) . "'"; } - - - public function escapeIdentifier(string $value): string - { - // @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS - return '"' . str_replace('"', '""', $value) . '"'; - } - - - public function escapeBool(bool $value): string - { - return $value ? 'TRUE' : 'FALSE'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d'"); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d H:i:s.u'"); - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $bs = pg_escape_string($this->connection, '\\'); // standard_conforming_strings = on/off - $value = pg_escape_string($this->connection, $value); - $value = strtr($value, ['%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\']); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - } - - if ($limit !== null) { - $sql .= ' LIMIT ' . $limit; - } - - if ($offset) { - $sql .= ' OFFSET ' . $offset; - } - } } diff --git a/src/Dibi/Drivers/PostgreResult.php b/src/Dibi/Drivers/PgSQL/Result.php similarity index 95% rename from src/Dibi/Drivers/PostgreResult.php rename to src/Dibi/Drivers/PgSQL/Result.php index 763dabaf..92553fe7 100644 --- a/src/Dibi/Drivers/PostgreResult.php +++ b/src/Dibi/Drivers/PgSQL/Result.php @@ -7,9 +7,9 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\PgSQL; -use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use PgSql; @@ -17,7 +17,7 @@ /** * The driver for PostgreSQL result set. */ -class PostgreResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( private readonly PgSql\Result $resultSet, diff --git a/src/Dibi/Drivers/Result.php b/src/Dibi/Drivers/Result.php new file mode 100644 index 00000000..23372cdb --- /dev/null +++ b/src/Dibi/Drivers/Result.php @@ -0,0 +1,58 @@ + character encoding to set (default is UTF-8) * - resource (resource) => existing connection resource */ -class SqlsrvDriver implements Dibi\Driver +class Connection implements Drivers\Connection { /** @var resource */ private $connection; @@ -84,7 +85,7 @@ public function disconnect(): void * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $this->affectedRows = null; $res = sqlsrv_query($this->connection, $sql); @@ -171,9 +172,9 @@ public function getResource(): mixed /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new SqlsrvReflector($this); + return new Drivers\Engines\SQLServerEngine($this); } @@ -181,9 +182,9 @@ public function getReflector(): Dibi\Reflector * Result set driver factory. * @param resource $resource */ - public function createResultDriver($resource): SqlsrvResult + public function createResultDriver($resource): Result { - return new SqlsrvResult($resource); + return new Result($resource); } @@ -203,63 +204,4 @@ public function escapeBinary(string $value): string { return '0x' . bin2hex($value); } - - - public function escapeIdentifier(string $value): string - { - // @see https://msdn.microsoft.com/en-us/library/ms176027.aspx - return '[' . str_replace(']', ']]', $value) . ']'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format("'Y-m-d'"); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return 'CONVERT(DATETIME2(7), ' . $value->format("'Y-m-d H:i:s.u'") . ')'; - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'"); - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - - } elseif ($limit !== null) { - // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx - $sql = sprintf('%s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY', rtrim($sql), $offset, $limit); - } elseif ($offset) { - // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx - $sql = sprintf('%s OFFSET %d ROWS', rtrim($sql), $offset); - } - } } diff --git a/src/Dibi/Drivers/SqlsrvResult.php b/src/Dibi/Drivers/SQLSrv/Result.php similarity index 95% rename from src/Dibi/Drivers/SqlsrvResult.php rename to src/Dibi/Drivers/SQLSrv/Result.php index 94a76179..c9e91b88 100644 --- a/src/Dibi/Drivers/SqlsrvResult.php +++ b/src/Dibi/Drivers/SQLSrv/Result.php @@ -7,16 +7,17 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\SQLSrv; use Dibi; +use Dibi\Drivers; use function is_resource; /** * The driver for Microsoft SQL Server and SQL Azure result set. */ -class SqlsrvResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( /** @var resource */ diff --git a/src/Dibi/Drivers/SqliteDriver.php b/src/Dibi/Drivers/SQLite3/Connection.php similarity index 77% rename from src/Dibi/Drivers/SqliteDriver.php rename to src/Dibi/Drivers/SQLite3/Connection.php index 7a2fa5e7..59693a56 100644 --- a/src/Dibi/Drivers/SqliteDriver.php +++ b/src/Dibi/Drivers/SQLite3/Connection.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\SQLite3; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use SQLite3; @@ -23,7 +24,7 @@ * - formatDateTime => how to format datetime in SQL (@see date) * - resource (SQLite3) => existing connection resource */ -class SqliteDriver implements Dibi\Driver +class Connection implements Drivers\Connection { private SQLite3 $connection; private string $fmtDate; @@ -73,7 +74,7 @@ public function disconnect(): void * Executes the SQL query. * @throws Dibi\DriverException */ - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { $res = @$this->connection->query($sql); // intentionally @ if ($code = $this->connection->lastErrorCode()) { @@ -174,18 +175,18 @@ public function getResource(): ?SQLite3 /** * Returns the connection reflector. */ - public function getReflector(): Dibi\Reflector + public function getReflector(): Drivers\Engine { - return new SqliteReflector($this); + return new Drivers\Engines\SQLiteEngine($this); } /** * Result set driver factory. */ - public function createResultDriver(\SQLite3Result $result): SqliteResult + public function createResultDriver(\SQLite3Result $result): Result { - return new SqliteResult($result); + return new Result($result); } @@ -207,61 +208,6 @@ public function escapeBinary(string $value): string } - public function escapeIdentifier(string $value): string - { - return '[' . strtr($value, '[]', ' ') . ']'; - } - - - public function escapeBool(bool $value): string - { - return $value ? '1' : '0'; - } - - - public function escapeDate(\DateTimeInterface $value): string - { - return $value->format($this->fmtDate); - } - - - public function escapeDateTime(\DateTimeInterface $value): string - { - return $value->format($this->fmtDateTime); - } - - - public function escapeDateInterval(\DateInterval $value): string - { - throw new Dibi\NotImplementedException; - } - - - /** - * Encodes string for use in a LIKE statement. - */ - public function escapeLike(string $value, int $pos): string - { - $value = addcslashes($this->connection->escapeString($value), '%_\\'); - return ($pos & 1 ? "'%" : "'") . $value . ($pos & 2 ? "%'" : "'") . " ESCAPE '\\'"; - } - - - /** - * Injects LIMIT/OFFSET to the SQL query. - */ - public function applyLimit(string &$sql, ?int $limit, ?int $offset): void - { - if ($limit < 0 || $offset < 0) { - throw new Dibi\NotSupportedException('Negative offset or limit.'); - - } elseif ($limit !== null || $offset) { - $sql .= ' LIMIT ' . ($limit ?? '-1') - . ($offset ? ' OFFSET ' . $offset : ''); - } - } - - /********************* user defined functions ****************d*g**/ diff --git a/src/Dibi/Drivers/SqliteResult.php b/src/Dibi/Drivers/SQLite3/Result.php similarity index 96% rename from src/Dibi/Drivers/SqliteResult.php rename to src/Dibi/Drivers/SQLite3/Result.php index 08d38904..cf89a9db 100644 --- a/src/Dibi/Drivers/SqliteResult.php +++ b/src/Dibi/Drivers/SQLite3/Result.php @@ -7,9 +7,10 @@ declare(strict_types=1); -namespace Dibi\Drivers; +namespace Dibi\Drivers\SQLite3; use Dibi; +use Dibi\Drivers; use Dibi\Helpers; use const SQLITE3_ASSOC, SQLITE3_BLOB, SQLITE3_FLOAT, SQLITE3_INTEGER, SQLITE3_NULL, SQLITE3_NUM, SQLITE3_TEXT; @@ -17,7 +18,7 @@ /** * The driver for SQLite result set. */ -class SqliteResult implements Dibi\ResultDriver +class Result implements Drivers\Result { public function __construct( private readonly \SQLite3Result $resultSet, diff --git a/src/Dibi/Drivers/Sqlite3Driver.php b/src/Dibi/Drivers/Sqlite3Driver.php deleted file mode 100644 index 0a99af83..00000000 --- a/src/Dibi/Drivers/Sqlite3Driver.php +++ /dev/null @@ -1,18 +0,0 @@ - 'text', diff --git a/src/Dibi/IDataSource.php b/src/Dibi/IDataSource.php new file mode 100644 index 00000000..9b41dc87 --- /dev/null +++ b/src/Dibi/IDataSource.php @@ -0,0 +1,20 @@ +columns)) { $this->columns = []; - $reflector = $this->driver instanceof Dibi\Reflector + $reflector = $this->driver instanceof Dibi\Drivers\Engine ? $this->driver : null; foreach ($this->driver->getResultColumns() as $info) { diff --git a/src/Dibi/Reflection/Table.php b/src/Dibi/Reflection/Table.php index 53e281d2..5e1829fc 100644 --- a/src/Dibi/Reflection/Table.php +++ b/src/Dibi/Reflection/Table.php @@ -26,7 +26,7 @@ */ class Table { - private readonly Dibi\Reflector $reflector; + private readonly Dibi\Drivers\Engine $reflector; private string $name; private bool $view; @@ -41,7 +41,7 @@ class Table private ?Index $primaryKey; - public function __construct(Dibi\Reflector $reflector, array $info) + public function __construct(Dibi\Drivers\Engine $reflector, array $info) { $this->reflector = $reflector; $this->name = $info['name']; diff --git a/src/Dibi/Result.php b/src/Dibi/Result.php index 50046ac1..ad380477 100644 --- a/src/Dibi/Result.php +++ b/src/Dibi/Result.php @@ -20,7 +20,7 @@ */ class Result implements IDataSource { - private ?ResultDriver $driver; + private ?Drivers\Result $driver; /** Translate table */ private array $types = []; @@ -37,7 +37,7 @@ class Result implements IDataSource private array $formats = []; - public function __construct(ResultDriver $driver, bool $normalize = true) + public function __construct(Drivers\Result $driver, bool $normalize = true) { $this->driver = $driver; if ($normalize) { @@ -62,7 +62,7 @@ final public function free(): void * Safe access to property $driver. * @throws \RuntimeException */ - final public function getResultDriver(): ResultDriver + final public function getResultDriver(): Drivers\Result { if ($this->driver === null) { throw new \RuntimeException('Result-set was released from memory.'); @@ -455,7 +455,7 @@ private function normalize(array &$row): void } $value = $row[$key]; - $format = $this->formats[$type] ?? null; + $format = $this->formats[$type ?? ''] ?? null; if ($type === null || $format === 'native') { $row[$key] = $value; diff --git a/src/Dibi/Row.php b/src/Dibi/Row.php index 9ab26fde..42d50903 100644 --- a/src/Dibi/Row.php +++ b/src/Dibi/Row.php @@ -75,7 +75,7 @@ final public function count(): int final public function getIterator(): \ArrayIterator { - return new \ArrayIterator($this); + return new \ArrayIterator((array) $this); } diff --git a/src/Dibi/Translator.php b/src/Dibi/Translator.php index be28e187..5aa44c4c 100644 --- a/src/Dibi/Translator.php +++ b/src/Dibi/Translator.php @@ -18,7 +18,8 @@ final class Translator { private readonly Connection $connection; - private readonly Driver $driver; + private readonly Drivers\Connection $driver; + private readonly Drivers\Engine $engine; private int $cursor = 0; private array $args; @@ -36,6 +37,7 @@ public function __construct(Connection $connection) { $this->connection = $connection; $this->driver = $connection->getDriver(); + $this->engine = $connection->getDatabaseEngine(); $this->identifiers = new HashMap($this->delimite(...)); } @@ -144,7 +146,7 @@ public function translate(array $args): string // apply limit if ($this->limit !== null || $this->offset !== null) { - $this->driver->applyLimit($sql, $this->limit, $this->offset); + $this->engine->applyLimit($sql, $this->limit, $this->offset); } return $sql; @@ -209,7 +211,7 @@ public function formatValue(mixed $value, ?string $modifier): string case 'n': // key, key, ... identifier names foreach ($value as $k => $v) { if (is_string($k)) { - $vx[] = $this->identifiers->$k . (empty($v) ? '' : ' AS ' . $this->driver->escapeIdentifier($v)); + $vx[] = $this->identifiers->$k . (empty($v) ? '' : ' AS ' . $this->engine->escapeIdentifier($v)); } else { $pair = explode('%', $v, 2); // split into identifier & modifier $vx[] = $this->identifiers->{$pair[0]}; @@ -346,7 +348,7 @@ public function formatValue(mixed $value, ?string $modifier): string case 's': // string return $value === null ? 'NULL' - : $this->driver->escapeText((string) $value); + : $this->engine->escapeText((string) $value); case 'bin':// binary return $value === null @@ -356,7 +358,7 @@ public function formatValue(mixed $value, ?string $modifier): string case 'b': // boolean return $value === null ? 'NULL' - : $this->driver->escapeBool((bool) $value); + : $this->engine->escapeBool((bool) $value); case 'sN': // string or null case 'sn': @@ -406,15 +408,15 @@ public function formatValue(mixed $value, ?string $modifier): string } return $modifier === 'd' - ? $this->driver->escapeDate($value) - : $this->driver->escapeDateTime($value); + ? $this->engine->escapeDate($value) + : $this->engine->escapeDateTime($value); case 'by': case 'n': // composed identifier name return $this->identifiers->$value; case 'N': // identifier name - return $this->driver->escapeIdentifier($value); + return $this->engine->escapeIdentifier($value); case 'ex': case 'sql': // preserve as dibi-SQL (TODO: leave only %ex) @@ -450,16 +452,16 @@ public function formatValue(mixed $value, ?string $modifier): string return (string) $value; case 'like~': // LIKE string% - return $this->driver->escapeLike($value, 2); + return $this->engine->escapeLike($value, 2); case '~like': // LIKE %string - return $this->driver->escapeLike($value, 1); + return $this->engine->escapeLike($value, 1); case '~like~': // LIKE %string% - return $this->driver->escapeLike($value, 3); + return $this->engine->escapeLike($value, 3); case 'like': // LIKE string - return $this->driver->escapeLike($value, 0); + return $this->engine->escapeLike($value, 0); case 'and': case 'or': @@ -485,16 +487,16 @@ public function formatValue(mixed $value, ?string $modifier): string return rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.'); } elseif (is_bool($value)) { - return $this->driver->escapeBool($value); + return $this->engine->escapeBool($value); } elseif ($value === null) { return 'NULL'; } elseif ($value instanceof \DateTimeInterface) { - return $this->driver->escapeDateTime($value); + return $this->engine->escapeDateTime($value); } elseif ($value instanceof \DateInterval) { - return $this->driver->escapeDateInterval($value); + return $this->engine->escapeDateInterval($value); } elseif ($value instanceof Literal) { return (string) $value; @@ -653,7 +655,7 @@ public function delimite(string $value): string $parts = explode('.', $value); foreach ($parts as &$v) { if ($v !== '*') { - $v = $this->driver->escapeIdentifier($v); + $v = $this->engine->escapeIdentifier($v); } } diff --git a/src/Dibi/Type.php b/src/Dibi/Type.php index da0f49df..d98f2d78 100644 --- a/src/Dibi/Type.php +++ b/src/Dibi/Type.php @@ -27,31 +27,31 @@ class Type Time = 't', TimeInterval = 'ti'; - /** @deprecated use Type::Text */ + #[\Deprecated('use Type::Text')] public const TEXT = self::Text; - /** @deprecated use Type::Binary */ + #[\Deprecated('use Type::Binary')] public const BINARY = self::Binary; - /** @deprecated use Type::Bool */ + #[\Deprecated('use Type::Bool')] public const BOOL = self::Bool; - /** @deprecated use Type::Integer */ + #[\Deprecated('use Type::Integer')] public const INTEGER = self::Integer; - /** @deprecated use Type::Float */ + #[\Deprecated('use Type::Float')] public const FLOAT = self::Float; - /** @deprecated use Type::Date */ + #[\Deprecated('use Type::Date')] public const DATE = self::Date; - /** @deprecated use Type::DateTime */ + #[\Deprecated('use Type::DateTime')] public const DATETIME = self::DateTime; - /** @deprecated use Type::Time */ + #[\Deprecated('use Type::Time')] public const TIME = self::Time; - /** @deprecated use Type::TimeInterval */ + #[\Deprecated('use Type::TimeInterval')] public const TIME_INTERVAL = self::TimeInterval; diff --git a/src/Dibi/dibi.php b/src/Dibi/dibi.php index a7c0517a..90086ead 100644 --- a/src/Dibi/dibi.php +++ b/src/Dibi/dibi.php @@ -37,15 +37,12 @@ */ class dibi { - public const Version = '5.1-dev'; + public const Version = '6.0-dev'; - /** @deprecated use dibi::Version */ public const VERSION = self::Version; - /** @deprecated use Dibi\Fluent::AffectedRows */ public const AFFECTED_ROWS = Dibi\Fluent::AffectedRows; - /** @deprecated use Dibi\Fluent::Identifier */ public const IDENTIFIER = Dibi\Fluent::Identifier; /** sorting order */ diff --git a/src/Dibi/interfaces.php b/src/Dibi/interfaces.php deleted file mode 100644 index fbf34d5d..00000000 --- a/src/Dibi/interfaces.php +++ /dev/null @@ -1,240 +0,0 @@ -getConfig('lazy')); Assert::same($config['driver'], $conn->getConfig('driver')); - Assert::type(Dibi\Driver::class, $conn->getDriver()); + Assert::type(Dibi\Drivers\Connection::class, $conn->getDriver()); }); diff --git a/tests/dibi/Connection.objectTranslator.phpt b/tests/dibi/Connection.objectTranslator.phpt index 32938af2..58e3be45 100644 --- a/tests/dibi/Connection.objectTranslator.phpt +++ b/tests/dibi/Connection.objectTranslator.phpt @@ -49,7 +49,7 @@ test('DateTime', function () use ($conn) { // Without object translator, DateTime child is translated by driver Assert::same( - $conn->getDriver()->escapeDateTime($stamp), + $conn->getDatabaseEngine()->escapeDateTime($stamp), $conn->translate('?', $stamp), ); @@ -67,15 +67,15 @@ test('DateTime', function () use ($conn) { // With modifier, it is still translated by driver Assert::same( - $conn->getDriver()->escapeDateTime($stamp), + $conn->getDatabaseEngine()->escapeDateTime($stamp), $conn->translate('%dt', $stamp), ); Assert::same( - $conn->getDriver()->escapeDateTime($stamp), + $conn->getDatabaseEngine()->escapeDateTime($stamp), $conn->translate('%t', $stamp), ); Assert::same( - $conn->getDriver()->escapeDate($stamp), + $conn->getDatabaseEngine()->escapeDate($stamp), $conn->translate('%d', $stamp), ); @@ -83,7 +83,7 @@ test('DateTime', function () use ($conn) { // DateTimeImmutable as a Time parent is not affected and still translated by driver $dt = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2022-11-22 12:13:14'); Assert::same( - $conn->getDriver()->escapeDateTime($dt), + $conn->getDatabaseEngine()->escapeDateTime($dt), $conn->translate('?', $dt), ); diff --git a/tests/dibi/Fluent.fetch.limit.mssql.phpt b/tests/dibi/Fluent.fetch.limit.mssql.phpt index d07ce4e8..cc8fdc36 100644 --- a/tests/dibi/Fluent.fetch.limit.mssql.phpt +++ b/tests/dibi/Fluent.fetch.limit.mssql.phpt @@ -2,12 +2,14 @@ declare(strict_types=1); +use Dibi\Drivers\SQLSrv\Connection; +use Dibi\Drivers\SQLSrv\Result; use Tester\Assert; require __DIR__ . '/bootstrap.php'; -class MockDriver extends Dibi\Drivers\SqlsrvDriver +class MockDriver extends Connection { public function __construct() { @@ -19,14 +21,14 @@ class MockDriver extends Dibi\Drivers\SqlsrvDriver } - public function query(string $sql): ?Dibi\ResultDriver + public function query(string $sql): ?Result { return new MockResult; } } -class MockResult extends Dibi\Drivers\SqlsrvResult +class MockResult extends Result { public function __construct() { diff --git a/tests/dibi/PdoDriver.providedConnection.phpt b/tests/dibi/PdoDriver.providedConnection.phpt index eb524323..7492294d 100644 --- a/tests/dibi/PdoDriver.providedConnection.phpt +++ b/tests/dibi/PdoDriver.providedConnection.phpt @@ -14,7 +14,7 @@ function buildPdoDriver(?int $errorMode) $pdo->setAttribute(PDO::ATTR_ERRMODE, $errorMode); } - new Dibi\Drivers\PdoDriver(['resource' => $pdo]); + new Dibi\Drivers\PDO\Connection(['resource' => $pdo]); }