From 0f22b77b5c544649f77ae950dffdc899920cc747 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Tue, 23 Jun 2026 22:50:15 +0200 Subject: [PATCH 01/19] feat: Add Doctrine DBAL QueryBuilder support via Connection::createQueryBuilder() Introduces a thin adapter layer (src/Doctrine/) that bridges the Artemeon Connection to Doctrine DBAL's Driver interface, enabling use of the DBAL QueryBuilder against all three supported databases (MySQL, PostgreSQL, SQLite). - Connection::createQueryBuilder() returns a DBAL QueryBuilder backed by the existing connection (no new physical connection is opened; DBAL instance is cached per Connection object) - DML parameters are passed without HTML-escaping to match the behaviour of the existing fetch methods - MysqlDriver queries SELECT VERSION() once to let DBAL pick the correct platform (MySQL vs MariaDB) instead of hard-coding a version string - Connection::quote() escapes backslashes before single quotes to prevent SQL injection on MySQL with default sql_mode - exec() return type widened to int|string to match the DriverConnection interface contract - fetchFirstColumn() sentinel fix: loops on fetchNumeric() to avoid false-cell truncation Co-Authored-By: Claude Sonnet 4.6 --- examples/query_builder_sqlite.php | 123 +++++++++++++++++++++++++ src/Connection.php | 23 +++++ src/Doctrine/Connection.php | 87 +++++++++++++++++ src/Doctrine/Driver/MysqlDriver.php | 37 ++++++++ src/Doctrine/Driver/PostgresDriver.php | 35 +++++++ src/Doctrine/Driver/SqliteDriver.php | 35 +++++++ src/Doctrine/Result.php | 118 ++++++++++++++++++++++++ src/Doctrine/Statement.php | 108 ++++++++++++++++++++++ src/MockConnection.php | 2 +- tests/Doctrine/QueryBuilderTest.php | 84 +++++++++++++++++ 10 files changed, 651 insertions(+), 1 deletion(-) create mode 100644 examples/query_builder_sqlite.php create mode 100644 src/Doctrine/Connection.php create mode 100644 src/Doctrine/Driver/MysqlDriver.php create mode 100644 src/Doctrine/Driver/PostgresDriver.php create mode 100644 src/Doctrine/Driver/SqliteDriver.php create mode 100644 src/Doctrine/Result.php create mode 100644 src/Doctrine/Statement.php create mode 100644 tests/Doctrine/QueryBuilderTest.php diff --git a/examples/query_builder_sqlite.php b/examples/query_builder_sqlite.php new file mode 100644 index 00000000..a7802249 --- /dev/null +++ b/examples/query_builder_sqlite.php @@ -0,0 +1,123 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +/** + * Runnable demo of Connection::createQueryBuilder() backed by an in-memory SQLite database. + * + * Usage (from the repo root): + * + * php examples/query_builder_sqlite.php + * + * Requires `doctrine/dbal:^4` to be installed (already in require-dev). + */ + +use Artemeon\Database\Connection; +use Artemeon\Database\ConnectionParameters; +use Artemeon\Database\DriverFactory; +use Artemeon\Database\Schema\DataType; + +require __DIR__ . '/../vendor/autoload.php'; + +$params = new ConnectionParameters( + host: 'localhost', + username: '', + password: '', + database: ':memory:', + port: null, + driver: 'sqlite3', +); + +$connection = new Connection($params, new DriverFactory()); + +// --- Schema + seed ----------------------------------------------------------- + +$table = 'demo_books'; +$connection->dropTable($table); +$connection->createTable( + $table, + [ + 'id' => [DataType::CHAR20, false], + 'title' => [DataType::CHAR100, false], + 'author' => [DataType::CHAR100, false], + 'year' => [DataType::INT, true], + ], + ['id'], +); + +$books = [ + ['id' => 'b-1', 'title' => 'The Pragmatic Programmer', 'author' => 'Andy Hunt', 'year' => 1999], + ['id' => 'b-2', 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999], + ['id' => 'b-3', 'title' => 'Domain-Driven Design', 'author' => 'Eric Evans', 'year' => 2003], + ['id' => 'b-4', 'title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008], + ['id' => 'b-5', 'title' => 'Designing Data-Intensive Applications', 'author' => 'Martin Kleppmann', 'year' => 2017], +]; +foreach ($books as $book) { + $connection->insert($table, $book); +} + +// --- Build queries via the Doctrine DBAL QueryBuilder ------------------------ + +echo "1) SELECT with WHERE + ORDER BY (positional parameter)\n"; +echo "------------------------------------------------------\n"; +$rows = $connection->createQueryBuilder() + ->select('title', 'author', 'year') + ->from($table) + ->where('year >= ?') + ->orderBy('year', 'ASC') + ->setParameter(0, 2000) + ->executeQuery() + ->fetchAllAssociative(); + +foreach ($rows as $row) { + printf(" %d %-45s %s\n", $row['year'], $row['title'], $row['author']); +} + +echo "\n2) SELECT with named parameter (DBAL rewrites to positional)\n"; +echo "------------------------------------------------------------\n"; +$row = $connection->createQueryBuilder() + ->select('title', 'author') + ->from($table) + ->where('id = :id') + ->setParameter('id', 'b-3') + ->executeQuery() + ->fetchAssociative(); + +printf(" Book b-3 → %s by %s\n", $row['title'], $row['author']); + +echo "\n3) UPDATE returning the affected row count\n"; +echo "-----------------------------------------\n"; +$affected = $connection->createQueryBuilder() + ->update($table) + ->set('author', '?') + ->where('id = ?') + ->setParameter(0, 'Andy Hunt and Dave Thomas') + ->setParameter(1, 'b-1') + ->executeStatement(); + +printf(" Updated %d row(s).\n", $affected); + +$confirmed = $connection->fetchOne( + 'SELECT author FROM ' . $table . ' WHERE id = ?', + ['b-1'], +); +printf(" New author for b-1: %s\n", $confirmed); + +echo "\n4) Aggregate via QueryBuilder\n"; +echo "-----------------------------\n"; +$count = $connection->createQueryBuilder() + ->select('COUNT(*)') + ->from($table) + ->executeQuery() + ->fetchOne(); + +printf(" Total books in table: %d\n", $count); diff --git a/src/Connection.php b/src/Connection.php index be3472e6..3af66e21 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -13,7 +13,13 @@ namespace Artemeon\Database; +use Artemeon\Database\Doctrine\Driver\MysqlDriver as DoctrineMysqlDriver; +use Artemeon\Database\Doctrine\Driver\PostgresDriver as DoctrinePostgresDriver; +use Artemeon\Database\Doctrine\Driver\SqliteDriver as DoctrineSqliteDriver; use Artemeon\Database\Exception\AddColumnException; +use Doctrine\DBAL\Configuration as DbalConfiguration; +use Doctrine\DBAL\Connection as DbalConnection; +use Doctrine\DBAL\Query\QueryBuilder; use Artemeon\Database\Exception\ChangeColumnException; use Artemeon\Database\Exception\CommitException; use Artemeon\Database\Exception\ConnectionException; @@ -73,6 +79,8 @@ class Connection implements ConnectionInterface */ private int $numberCache = 0; + private ?DbalConnection $dbalConnection = null; + /** * Instance of the db-driver defined in the configs. */ @@ -350,6 +358,21 @@ public function executeStatement(string $query, array $params = []): int return $this->dbDriver->getAffectedRowsCount(); } + public function createQueryBuilder(): QueryBuilder + { + if ($this->dbalConnection === null) { + $driver = match ($this->connectionParams->getDriver()) { + 'mysqli' => new DoctrineMysqlDriver($this), + 'postgres' => new DoctrinePostgresDriver($this), + default => new DoctrineSqliteDriver($this), + }; + + $this->dbalConnection = new DbalConnection([], $driver, new DbalConfiguration()); + } + + return $this->dbalConnection->createQueryBuilder(); + } + /** * @inheritDoc */ diff --git a/src/Doctrine/Connection.php b/src/Doctrine/Connection.php new file mode 100644 index 00000000..6482e692 --- /dev/null +++ b/src/Doctrine/Connection.php @@ -0,0 +1,87 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Doctrine\DBAL\Driver\Connection as DriverConnection; +use Doctrine\DBAL\Driver\Exception\NoIdentityValue; +use Doctrine\DBAL\Driver\Result as DriverResult; +use Doctrine\DBAL\Driver\Statement as DriverStatement; + +/** + * DBAL driver connection that delegates to an Artemeon Connection. + * + * Platform selection happens in the {@see Driver} subclasses; this class only + * wires DBAL's per-query primitives to the matching Artemeon Connection calls. + * The server-version string is supplied by the Driver and used by DBAL solely + * to pick a platform variant (MySQL 8.4 vs 8.0, MariaDB 11.7 vs 10.6, etc.). + */ +final class Connection implements DriverConnection +{ + public function __construct( + private readonly ArtemeonConnection $connection, + private readonly string $serverVersion, + ) { + } + + public function prepare(string $sql): DriverStatement + { + return new Statement($this->connection, $sql); + } + + public function query(string $sql): DriverResult + { + return $this->prepare($sql)->execute(); + } + + public function quote(string $value): string + { + return "'" . str_replace(["\\", "'"], ["\\\\", "''"], $value) . "'"; + } + + public function exec(string $sql): int|string + { + return $this->connection->executeStatement($sql); + } + + public function lastInsertId(): int|string + { + throw NoIdentityValue::new(); + } + + public function beginTransaction(): void + { + $this->connection->beginTransaction(); + } + + public function commit(): void + { + $this->connection->commit(); + } + + public function rollBack(): void + { + $this->connection->rollBack(); + } + + public function getNativeConnection(): object + { + return $this->connection; + } + + public function getServerVersion(): string + { + return $this->serverVersion; + } +} diff --git a/src/Doctrine/Driver/MysqlDriver.php b/src/Doctrine/Driver/MysqlDriver.php new file mode 100644 index 00000000..6859cdbb --- /dev/null +++ b/src/Doctrine/Driver/MysqlDriver.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine\Driver; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Doctrine\DBAL\Driver\AbstractMySQLDriver; +use Doctrine\DBAL\Driver\Connection as DriverConnection; +use SensitiveParameter; + +/** + * DBAL driver façade for an Artemeon Mysqli driver. + */ +final class MysqlDriver extends AbstractMySQLDriver +{ + public function __construct(private readonly ArtemeonConnection $connection) + { + } + + public function connect(#[SensitiveParameter] array $params): DriverConnection + { + $version = (string) $this->connection->fetchOne('SELECT VERSION()'); + + return new DriverConnectionAdapter($this->connection, $version); + } +} diff --git a/src/Doctrine/Driver/PostgresDriver.php b/src/Doctrine/Driver/PostgresDriver.php new file mode 100644 index 00000000..8f0e17e0 --- /dev/null +++ b/src/Doctrine/Driver/PostgresDriver.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine\Driver; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver; +use Doctrine\DBAL\Driver\Connection as DriverConnection; +use SensitiveParameter; + +/** + * DBAL driver façade for an Artemeon Postgres driver. + */ +final class PostgresDriver extends AbstractPostgreSQLDriver +{ + public function __construct(private readonly ArtemeonConnection $connection) + { + } + + public function connect(#[SensitiveParameter] array $params): DriverConnection + { + return new DriverConnectionAdapter($this->connection, '16.0'); + } +} diff --git a/src/Doctrine/Driver/SqliteDriver.php b/src/Doctrine/Driver/SqliteDriver.php new file mode 100644 index 00000000..0b50adf3 --- /dev/null +++ b/src/Doctrine/Driver/SqliteDriver.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine\Driver; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Doctrine\DBAL\Driver\AbstractSQLiteDriver; +use Doctrine\DBAL\Driver\Connection as DriverConnection; +use SensitiveParameter; + +/** + * DBAL driver façade for an Artemeon Sqlite3 driver. + */ +final class SqliteDriver extends AbstractSQLiteDriver +{ + public function __construct(private readonly ArtemeonConnection $connection) + { + } + + public function connect(#[SensitiveParameter] array $params): DriverConnection + { + return new DriverConnectionAdapter($this->connection, '3.0.0'); + } +} diff --git a/src/Doctrine/Result.php b/src/Doctrine/Result.php new file mode 100644 index 00000000..20107b26 --- /dev/null +++ b/src/Doctrine/Result.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine; + +use Doctrine\DBAL\Driver\Result as DriverResult; + +/** + * Buffered DBAL driver result backed by a pre-fetched row array. + * + * The Artemeon connection materialises full result sets, so the adapter + * owns the rows up-front and replays them through the DBAL fetch API. + */ +final class Result implements DriverResult +{ + private int $position = 0; + + /** + * @param list> $rows + */ + public function __construct( + private array $rows, + private readonly int $affectedRows, + ) { + } + + public function fetchNumeric(): array | false + { + $row = $this->rows[$this->position] ?? null; + if ($row === null) { + return false; + } + + $this->position++; + + return array_values($row); + } + + public function fetchAssociative(): array | false + { + $row = $this->rows[$this->position] ?? null; + if ($row === null) { + return false; + } + + $this->position++; + + return $row; + } + + public function fetchOne(): mixed + { + $row = $this->fetchNumeric(); + if ($row === false) { + return false; + } + + return $row[0] ?? null; + } + + public function fetchAllNumeric(): array + { + $out = []; + while (($row = $this->fetchNumeric()) !== false) { + $out[] = $row; + } + + return $out; + } + + public function fetchAllAssociative(): array + { + $out = []; + while (($row = $this->fetchAssociative()) !== false) { + $out[] = $row; + } + + return $out; + } + + public function fetchFirstColumn(): array + { + $out = []; + while (($row = $this->fetchNumeric()) !== false) { + $out[] = $row[0]; + } + + return $out; + } + + public function rowCount(): int + { + return $this->affectedRows; + } + + public function columnCount(): int + { + $first = $this->rows[0] ?? null; + + return $first === null ? 0 : count($first); + } + + public function free(): void + { + $this->rows = []; + $this->position = 0; + } +} diff --git a/src/Doctrine/Statement.php b/src/Doctrine/Statement.php new file mode 100644 index 00000000..88ec3abd --- /dev/null +++ b/src/Doctrine/Statement.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Doctrine; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Doctrine\DBAL\Driver\Statement as DriverStatement; +use Doctrine\DBAL\ParameterType; +use LogicException; +use Stringable; + +/** + * DBAL driver statement that delegates to an Artemeon Connection. + * + * Values are buffered via {@see bindValue()} and replayed in positional order at + * {@see execute()} time. The Artemeon driver layer only accepts positional `?` + * placeholders, so named parameters are rejected (the DBAL Connection rewrites + * them to positional before reaching us). + */ +final class Statement implements DriverStatement +{ + /** @var array */ + private array $values = []; + + public function __construct( + private readonly ArtemeonConnection $connection, + private readonly string $sql, + ) { + } + + public function bindValue(int|string $param, mixed $value, ParameterType $type): void + { + if (is_string($param)) { + throw new LogicException( + 'Named parameters are not supported by the Artemeon DBAL adapter; use positional placeholders.', + ); + } + + if ($type === ParameterType::BOOLEAN && is_bool($value)) { + $value = (int) $value; + } + + if ($value instanceof Stringable) { + $value = (string) $value; + } + + if ($value !== null && !is_scalar($value)) { + throw new LogicException( + 'Unsupported parameter type: ' . get_debug_type($value), + ); + } + + $this->values[$param] = $value; + } + + public function execute(): Result + { + ksort($this->values); + $params = array_values($this->values); + + if (self::returnsResultSet($this->sql)) { + $rows = $this->connection->fetchAllAssociative($this->sql, $params); + + return new Result($rows, count($rows)); + } + + $this->connection->_pQuery($this->sql, $params, array_fill(0, count($params), false)); + $affected = $this->connection->getAffectedRowsCount(); + + return new Result([], $affected); + } + + /** + * Heuristic to decide whether a SQL string returns a result set. + * + * This exists because Artemeon splits execution into two separate methods — fetchAllAssociative() + * for queries and _pQuery() for statements — so the driver adapter must route before DBAL decides + * which result interface to use. A real PDO-backed driver never needs this because PDO's execute() + * returns a unified handle that supports both fetch() and rowCount() regardless of SQL type. + * + * Known limitation: writable CTEs (WITH … INSERT/UPDATE/DELETE) start with WITH and are therefore + * misclassified as queries, causing them to be routed through fetchAllAssociative() instead of + * _pQuery(). The proper fix is to add a unified execute-and-return-result method to the Artemeon + * Connection that returns both rows and an affected-row count in one call, eliminating the need + * for this heuristic entirely. + */ + private static function returnsResultSet(string $sql): bool + { + $head = strtoupper(ltrim($sql, " \t\r\n(")); + foreach (['SELECT', 'WITH', 'SHOW', 'PRAGMA', 'EXPLAIN', 'DESCRIBE', 'VALUES', 'TABLE'] as $keyword) { + if (str_starts_with($head, $keyword)) { + return true; + } + } + + return false; + } +} diff --git a/src/MockConnection.php b/src/MockConnection.php index 565579ee..90098860 100644 --- a/src/MockConnection.php +++ b/src/MockConnection.php @@ -150,7 +150,7 @@ public function executeStatement(string $query, array $params = []): int return 1; } - #[Override] +#[Override] public function getAffectedRowsCount(): int { return 1; diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php new file mode 100644 index 00000000..dc896966 --- /dev/null +++ b/tests/Doctrine/QueryBuilderTest.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests\Doctrine; + +use Artemeon\Database\Tests\ConnectionTestCase; + +/** + * @internal + */ +class QueryBuilderTest extends ConnectionTestCase +{ + public function testSelectAllReturnsSeededRows(): void + { + $qb = $this->getConnection()->createQueryBuilder() + ->select('temp_char10') + ->from(self::TEST_TABLE_NAME) + ->orderBy('temp_bigint', 'ASC'); + + $rows = $qb->executeQuery()->fetchAllAssociative(); + + $this->assertCount(50, $rows); + $this->assertSame('char10-1', $rows[0]['temp_char10']); + $this->assertSame('char10-10', $rows[9]['temp_char10']); + } + + public function testSelectWithPositionalParameter(): void + { + $qb = $this->getConnection()->createQueryBuilder() + ->select('temp_int', 'temp_char10') + ->from(self::TEST_TABLE_NAME) + ->where('temp_char10 = ?') + ->setParameter(0, 'char10-3'); + + $row = $qb->executeQuery()->fetchAssociative(); + + $this->assertIsArray($row); + $this->assertSame('char10-3', $row['temp_char10']); + $this->assertEquals(123459, $row['temp_int']); + } + + public function testSelectWithNamedParameterGetsRewrittenByDoctrine(): void + { + $qb = $this->getConnection()->createQueryBuilder() + ->select('temp_char20') + ->from(self::TEST_TABLE_NAME) + ->where('temp_char10 = :needle') + ->setParameter('needle', 'char10-7'); + + $value = $qb->executeQuery()->fetchOne(); + + $this->assertSame('char20-7', $value); + } + + public function testUpdateThroughQueryBuilderReturnsAffectedRows(): void + { + $qb = $this->getConnection()->createQueryBuilder() + ->update(self::TEST_TABLE_NAME) + ->set('temp_char100', '?') + ->where('temp_char10 = ?') + ->setParameter(0, 'updated-via-qb') + ->setParameter(1, 'char10-5'); + + $affected = $qb->executeStatement(); + + $this->assertSame(1, $affected); + + $check = $this->getConnection()->fetchOne( + 'SELECT temp_char100 FROM ' . self::TEST_TABLE_NAME . ' WHERE temp_char10 = ?', + ['char10-5'], + ); + $this->assertSame('updated-via-qb', $check); + } +} From 889386e0af6a5b05abc22ef56fee06ab265bade2 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Tue, 23 Jun 2026 22:52:18 +0200 Subject: [PATCH 02/19] docs: Add complex AND/OR/IN example to query_builder_sqlite demo Co-Authored-By: Claude Sonnet 4.6 --- examples/query_builder_sqlite.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/examples/query_builder_sqlite.php b/examples/query_builder_sqlite.php index a7802249..3369f5fb 100644 --- a/examples/query_builder_sqlite.php +++ b/examples/query_builder_sqlite.php @@ -121,3 +121,32 @@ ->fetchOne(); printf(" Total books in table: %d\n", $count); + +echo "\n5) Complex WHERE with AND, OR, and IN\n"; +echo "---------------------------------------\n"; +// Books published before 2000 OR after 2010, but only from a specific id set +$qb = $connection->createQueryBuilder(); +$rows = $qb + ->select('title', 'author', 'year') + ->from($table) + ->where( + $qb->expr()->and( + $qb->expr()->or( + $qb->expr()->lt('year', ':cutoff_low'), + $qb->expr()->gt('year', ':cutoff_high'), + ), + $qb->expr()->in('id', [':b1', ':b2', ':b3']), + ), + ) + ->setParameter('cutoff_low', 2000) + ->setParameter('cutoff_high', 2010) + ->setParameter('b1', 'b-1') + ->setParameter('b2', 'b-3') + ->setParameter('b3', 'b-5') + ->orderBy('year', 'ASC') + ->executeQuery() + ->fetchAllAssociative(); + +foreach ($rows as $row) { + printf(" %d %-45s %s\n", $row['year'], $row['title'], $row['author']); +} From c23ae868ee254754767d970a08d76d84db9c1b54 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Tue, 23 Jun 2026 22:53:30 +0200 Subject: [PATCH 03/19] docs: Add JOIN example and reviews table to query_builder_sqlite demo Co-Authored-By: Claude Sonnet 4.6 --- examples/query_builder_sqlite.php | 57 +++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/examples/query_builder_sqlite.php b/examples/query_builder_sqlite.php index 3369f5fb..c67662d5 100644 --- a/examples/query_builder_sqlite.php +++ b/examples/query_builder_sqlite.php @@ -42,29 +42,55 @@ // --- Schema + seed ----------------------------------------------------------- $table = 'demo_books'; +$tableReviews = 'demo_reviews'; + $connection->dropTable($table); +$connection->dropTable($tableReviews); + $connection->createTable( $table, [ - 'id' => [DataType::CHAR20, false], - 'title' => [DataType::CHAR100, false], + 'id' => [DataType::CHAR20, false], + 'title' => [DataType::CHAR100, false], 'author' => [DataType::CHAR100, false], - 'year' => [DataType::INT, true], + 'year' => [DataType::INT, true], + ], + ['id'], +); + +$connection->createTable( + $tableReviews, + [ + 'id' => [DataType::CHAR20, false], + 'book_id' => [DataType::CHAR20, false], + 'stars' => [DataType::INT, true], + 'comment' => [DataType::CHAR100, true], ], ['id'], ); $books = [ - ['id' => 'b-1', 'title' => 'The Pragmatic Programmer', 'author' => 'Andy Hunt', 'year' => 1999], - ['id' => 'b-2', 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999], - ['id' => 'b-3', 'title' => 'Domain-Driven Design', 'author' => 'Eric Evans', 'year' => 2003], - ['id' => 'b-4', 'title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008], + ['id' => 'b-1', 'title' => 'The Pragmatic Programmer', 'author' => 'Andy Hunt', 'year' => 1999], + ['id' => 'b-2', 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999], + ['id' => 'b-3', 'title' => 'Domain-Driven Design', 'author' => 'Eric Evans', 'year' => 2003], + ['id' => 'b-4', 'title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008], ['id' => 'b-5', 'title' => 'Designing Data-Intensive Applications', 'author' => 'Martin Kleppmann', 'year' => 2017], ]; foreach ($books as $book) { $connection->insert($table, $book); } +$reviews = [ + ['id' => 'r-1', 'book_id' => 'b-1', 'stars' => 5, 'comment' => 'Essential read'], + ['id' => 'r-2', 'book_id' => 'b-1', 'stars' => 4, 'comment' => 'Very practical'], + ['id' => 'r-3', 'book_id' => 'b-3', 'stars' => 5, 'comment' => 'Changed how I think'], + ['id' => 'r-4', 'book_id' => 'b-4', 'stars' => 3, 'comment' => 'Good but dated'], + ['id' => 'r-5', 'book_id' => 'b-5', 'stars' => 5, 'comment' => 'Comprehensive'], +]; +foreach ($reviews as $review) { + $connection->insert($tableReviews, $review); +} + // --- Build queries via the Doctrine DBAL QueryBuilder ------------------------ echo "1) SELECT with WHERE + ORDER BY (positional parameter)\n"; @@ -150,3 +176,20 @@ foreach ($rows as $row) { printf(" %d %-45s %s\n", $row['year'], $row['title'], $row['author']); } + +echo "\n6) JOIN books with reviews, filter by minimum rating\n"; +echo "------------------------------------------------------\n"; +$qb = $connection->createQueryBuilder(); +$rows = $qb + ->select('b.title', 'b.author', 'r.stars', 'r.comment') + ->from($table, 'b') + ->innerJoin('b', $tableReviews, 'r', 'r.book_id = b.id') + ->where($qb->expr()->gte('r.stars', ':min_stars')) + ->setParameter('min_stars', 5) + ->orderBy('b.year', 'ASC') + ->executeQuery() + ->fetchAllAssociative(); + +foreach ($rows as $row) { + printf(" %-45s %d★ %s\n", $row['title'], $row['stars'], $row['comment']); +} From 5b271f6c01342cc6d208ff859c283e7d7a262619 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Tue, 23 Jun 2026 22:55:16 +0200 Subject: [PATCH 04/19] fix: Resolve PHPStan errors in Doctrine adapter - exec(): narrow return type back to int (covariant narrowing of the interface's int|string is valid; string is never returned in practice) - MysqlDriver: guard fetchOne() result with is_string() before passing as server version string (fetchOne returns mixed) Co-Authored-By: Claude Sonnet 4.6 --- src/Doctrine/Connection.php | 2 +- src/Doctrine/Driver/MysqlDriver.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Doctrine/Connection.php b/src/Doctrine/Connection.php index 6482e692..e30e07ba 100644 --- a/src/Doctrine/Connection.php +++ b/src/Doctrine/Connection.php @@ -50,7 +50,7 @@ public function quote(string $value): string return "'" . str_replace(["\\", "'"], ["\\\\", "''"], $value) . "'"; } - public function exec(string $sql): int|string + public function exec(string $sql): int { return $this->connection->executeStatement($sql); } diff --git a/src/Doctrine/Driver/MysqlDriver.php b/src/Doctrine/Driver/MysqlDriver.php index 6859cdbb..c6c3064a 100644 --- a/src/Doctrine/Driver/MysqlDriver.php +++ b/src/Doctrine/Driver/MysqlDriver.php @@ -30,8 +30,8 @@ public function __construct(private readonly ArtemeonConnection $connection) public function connect(#[SensitiveParameter] array $params): DriverConnection { - $version = (string) $this->connection->fetchOne('SELECT VERSION()'); + $version = $this->connection->fetchOne('SELECT VERSION()'); - return new DriverConnectionAdapter($this->connection, $version); + return new DriverConnectionAdapter($this->connection, is_string($version) ? $version : '8.0.0'); } } From 4b99ecd3080e2cda49215ab4dc2a4593aa108ec5 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Tue, 23 Jun 2026 22:58:07 +0200 Subject: [PATCH 05/19] fix: Add doctrine/dbal as a runtime dependency and fix CI failures - Add doctrine/dbal:^4 to require (was missing; only came in transitively via dev dependencies, causing AbstractSQLiteDriver not found in CI) - Apply Pint style fixes (binary_operator_spaces, whitespace_after_comma, ordered_imports, single_quote) Co-Authored-By: Claude Sonnet 4.6 --- composer.json | 1 + examples/query_builder_sqlite.php | 18 +++++++++--------- src/Connection.php | 6 +++--- src/Doctrine/Connection.php | 4 ++-- src/Doctrine/Statement.php | 2 +- src/MockConnection.php | 2 +- 6 files changed, 17 insertions(+), 16 deletions(-) diff --git a/composer.json b/composer.json index e0d84c48..79e6bc96 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ ], "require": { "php": ">=8.4", + "doctrine/dbal": "^4", "psr/log": "^1|^2|^3", "symfony/process": "^5.0|^6.0|^7.0", "symfony/polyfill-mbstring": "^1.15" diff --git a/examples/query_builder_sqlite.php b/examples/query_builder_sqlite.php index c67662d5..6bdf445c 100644 --- a/examples/query_builder_sqlite.php +++ b/examples/query_builder_sqlite.php @@ -50,10 +50,10 @@ $connection->createTable( $table, [ - 'id' => [DataType::CHAR20, false], - 'title' => [DataType::CHAR100, false], + 'id' => [DataType::CHAR20, false], + 'title' => [DataType::CHAR100, false], 'author' => [DataType::CHAR100, false], - 'year' => [DataType::INT, true], + 'year' => [DataType::INT, true], ], ['id'], ); @@ -61,19 +61,19 @@ $connection->createTable( $tableReviews, [ - 'id' => [DataType::CHAR20, false], + 'id' => [DataType::CHAR20, false], 'book_id' => [DataType::CHAR20, false], - 'stars' => [DataType::INT, true], + 'stars' => [DataType::INT, true], 'comment' => [DataType::CHAR100, true], ], ['id'], ); $books = [ - ['id' => 'b-1', 'title' => 'The Pragmatic Programmer', 'author' => 'Andy Hunt', 'year' => 1999], - ['id' => 'b-2', 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999], - ['id' => 'b-3', 'title' => 'Domain-Driven Design', 'author' => 'Eric Evans', 'year' => 2003], - ['id' => 'b-4', 'title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008], + ['id' => 'b-1', 'title' => 'The Pragmatic Programmer', 'author' => 'Andy Hunt', 'year' => 1999], + ['id' => 'b-2', 'title' => 'Refactoring', 'author' => 'Martin Fowler', 'year' => 1999], + ['id' => 'b-3', 'title' => 'Domain-Driven Design', 'author' => 'Eric Evans', 'year' => 2003], + ['id' => 'b-4', 'title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008], ['id' => 'b-5', 'title' => 'Designing Data-Intensive Applications', 'author' => 'Martin Kleppmann', 'year' => 2017], ]; foreach ($books as $book) { diff --git a/src/Connection.php b/src/Connection.php index 3af66e21..fde78b73 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -17,9 +17,6 @@ use Artemeon\Database\Doctrine\Driver\PostgresDriver as DoctrinePostgresDriver; use Artemeon\Database\Doctrine\Driver\SqliteDriver as DoctrineSqliteDriver; use Artemeon\Database\Exception\AddColumnException; -use Doctrine\DBAL\Configuration as DbalConfiguration; -use Doctrine\DBAL\Connection as DbalConnection; -use Doctrine\DBAL\Query\QueryBuilder; use Artemeon\Database\Exception\ChangeColumnException; use Artemeon\Database\Exception\CommitException; use Artemeon\Database\Exception\ConnectionException; @@ -32,6 +29,9 @@ use Artemeon\Database\Schema\TableIndex; use BackedEnum; use Closure; +use Doctrine\DBAL\Configuration as DbalConfiguration; +use Doctrine\DBAL\Connection as DbalConnection; +use Doctrine\DBAL\Query\QueryBuilder; use Generator; use InvalidArgumentException; use Override; diff --git a/src/Doctrine/Connection.php b/src/Doctrine/Connection.php index e30e07ba..c963e3ae 100644 --- a/src/Doctrine/Connection.php +++ b/src/Doctrine/Connection.php @@ -47,7 +47,7 @@ public function query(string $sql): DriverResult public function quote(string $value): string { - return "'" . str_replace(["\\", "'"], ["\\\\", "''"], $value) . "'"; + return "'" . str_replace(['\\', "'"], ['\\\\', "''"], $value) . "'"; } public function exec(string $sql): int @@ -55,7 +55,7 @@ public function exec(string $sql): int return $this->connection->executeStatement($sql); } - public function lastInsertId(): int|string + public function lastInsertId(): int | string { throw NoIdentityValue::new(); } diff --git a/src/Doctrine/Statement.php b/src/Doctrine/Statement.php index 88ec3abd..e81fd1c1 100644 --- a/src/Doctrine/Statement.php +++ b/src/Doctrine/Statement.php @@ -38,7 +38,7 @@ public function __construct( ) { } - public function bindValue(int|string $param, mixed $value, ParameterType $type): void + public function bindValue(int | string $param, mixed $value, ParameterType $type): void { if (is_string($param)) { throw new LogicException( diff --git a/src/MockConnection.php b/src/MockConnection.php index 90098860..565579ee 100644 --- a/src/MockConnection.php +++ b/src/MockConnection.php @@ -150,7 +150,7 @@ public function executeStatement(string $query, array $params = []): int return 1; } -#[Override] + #[Override] public function getAffectedRowsCount(): int { return 1; From 2497977d700256e050b9e27a19ee9bba2f5d8495 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:06:48 +0100 Subject: [PATCH 06/19] refactor: Move DBAL adapter into Doctrine\Driver and mark it internal Mirror DBAL's own layout (driver, connection, statement and result side by side), name the drivers after their Artemeon counterparts (MysqliDriver, PostgresDriver, Sqlite3Driver) and mark all adapter classes @internal: the public entry point is Connection::createQueryBuilder(). Co-Authored-By: Claude Opus 5.5 --- src/Connection.php | 8 ++++---- src/Doctrine/{ => Driver}/Connection.php | 6 ++++-- src/Doctrine/Driver/{MysqlDriver.php => MysqliDriver.php} | 6 ++++-- src/Doctrine/Driver/PostgresDriver.php | 4 +++- src/Doctrine/{ => Driver}/Result.php | 4 +++- .../Driver/{SqliteDriver.php => Sqlite3Driver.php} | 6 ++++-- src/Doctrine/{ => Driver}/Statement.php | 4 +++- 7 files changed, 25 insertions(+), 13 deletions(-) rename src/Doctrine/{ => Driver}/Connection.php (90%) rename src/Doctrine/Driver/{MysqlDriver.php => MysqliDriver.php} (81%) rename src/Doctrine/{ => Driver}/Result.php (94%) rename src/Doctrine/Driver/{SqliteDriver.php => Sqlite3Driver.php} (79%) rename src/Doctrine/{ => Driver}/Statement.php (96%) diff --git a/src/Connection.php b/src/Connection.php index fde78b73..a4446449 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -13,9 +13,9 @@ namespace Artemeon\Database; -use Artemeon\Database\Doctrine\Driver\MysqlDriver as DoctrineMysqlDriver; +use Artemeon\Database\Doctrine\Driver\MysqliDriver as DoctrineMysqliDriver; use Artemeon\Database\Doctrine\Driver\PostgresDriver as DoctrinePostgresDriver; -use Artemeon\Database\Doctrine\Driver\SqliteDriver as DoctrineSqliteDriver; +use Artemeon\Database\Doctrine\Driver\Sqlite3Driver as DoctrineSqlite3Driver; use Artemeon\Database\Exception\AddColumnException; use Artemeon\Database\Exception\ChangeColumnException; use Artemeon\Database\Exception\CommitException; @@ -362,9 +362,9 @@ public function createQueryBuilder(): QueryBuilder { if ($this->dbalConnection === null) { $driver = match ($this->connectionParams->getDriver()) { - 'mysqli' => new DoctrineMysqlDriver($this), + 'mysqli' => new DoctrineMysqliDriver($this), 'postgres' => new DoctrinePostgresDriver($this), - default => new DoctrineSqliteDriver($this), + default => new DoctrineSqlite3Driver($this), }; $this->dbalConnection = new DbalConnection([], $driver, new DbalConfiguration()); diff --git a/src/Doctrine/Connection.php b/src/Doctrine/Driver/Connection.php similarity index 90% rename from src/Doctrine/Connection.php rename to src/Doctrine/Driver/Connection.php index c963e3ae..ca1ac3b5 100644 --- a/src/Doctrine/Connection.php +++ b/src/Doctrine/Driver/Connection.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Artemeon\Database\Doctrine; +namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; use Doctrine\DBAL\Driver\Connection as DriverConnection; @@ -22,10 +22,12 @@ /** * DBAL driver connection that delegates to an Artemeon Connection. * - * Platform selection happens in the {@see Driver} subclasses; this class only + * Platform selection happens in the driver classes of this namespace; this class only * wires DBAL's per-query primitives to the matching Artemeon Connection calls. * The server-version string is supplied by the Driver and used by DBAL solely * to pick a platform variant (MySQL 8.4 vs 8.0, MariaDB 11.7 vs 10.6, etc.). + * + * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ final class Connection implements DriverConnection { diff --git a/src/Doctrine/Driver/MysqlDriver.php b/src/Doctrine/Driver/MysqliDriver.php similarity index 81% rename from src/Doctrine/Driver/MysqlDriver.php rename to src/Doctrine/Driver/MysqliDriver.php index c6c3064a..79ac3cf4 100644 --- a/src/Doctrine/Driver/MysqlDriver.php +++ b/src/Doctrine/Driver/MysqliDriver.php @@ -14,15 +14,17 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractMySQLDriver; use Doctrine\DBAL\Driver\Connection as DriverConnection; use SensitiveParameter; /** * DBAL driver façade for an Artemeon Mysqli driver. + * + * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ -final class MysqlDriver extends AbstractMySQLDriver +final class MysqliDriver extends AbstractMySQLDriver { public function __construct(private readonly ArtemeonConnection $connection) { diff --git a/src/Doctrine/Driver/PostgresDriver.php b/src/Doctrine/Driver/PostgresDriver.php index 8f0e17e0..68d00c7b 100644 --- a/src/Doctrine/Driver/PostgresDriver.php +++ b/src/Doctrine/Driver/PostgresDriver.php @@ -14,13 +14,15 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver; use Doctrine\DBAL\Driver\Connection as DriverConnection; use SensitiveParameter; /** * DBAL driver façade for an Artemeon Postgres driver. + * + * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ final class PostgresDriver extends AbstractPostgreSQLDriver { diff --git a/src/Doctrine/Result.php b/src/Doctrine/Driver/Result.php similarity index 94% rename from src/Doctrine/Result.php rename to src/Doctrine/Driver/Result.php index 20107b26..25ca089b 100644 --- a/src/Doctrine/Result.php +++ b/src/Doctrine/Driver/Result.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Artemeon\Database\Doctrine; +namespace Artemeon\Database\Doctrine\Driver; use Doctrine\DBAL\Driver\Result as DriverResult; @@ -20,6 +20,8 @@ * * The Artemeon connection materialises full result sets, so the adapter * owns the rows up-front and replays them through the DBAL fetch API. + * + * @internal Only reachable through {@see \Artemeon\Database\Connection::createQueryBuilder()}. */ final class Result implements DriverResult { diff --git a/src/Doctrine/Driver/SqliteDriver.php b/src/Doctrine/Driver/Sqlite3Driver.php similarity index 79% rename from src/Doctrine/Driver/SqliteDriver.php rename to src/Doctrine/Driver/Sqlite3Driver.php index 0b50adf3..b159b286 100644 --- a/src/Doctrine/Driver/SqliteDriver.php +++ b/src/Doctrine/Driver/Sqlite3Driver.php @@ -14,15 +14,17 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Connection as DriverConnectionAdapter; +use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractSQLiteDriver; use Doctrine\DBAL\Driver\Connection as DriverConnection; use SensitiveParameter; /** * DBAL driver façade for an Artemeon Sqlite3 driver. + * + * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ -final class SqliteDriver extends AbstractSQLiteDriver +final class Sqlite3Driver extends AbstractSQLiteDriver { public function __construct(private readonly ArtemeonConnection $connection) { diff --git a/src/Doctrine/Statement.php b/src/Doctrine/Driver/Statement.php similarity index 96% rename from src/Doctrine/Statement.php rename to src/Doctrine/Driver/Statement.php index e81fd1c1..06a5e303 100644 --- a/src/Doctrine/Statement.php +++ b/src/Doctrine/Driver/Statement.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Artemeon\Database\Doctrine; +namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; use Doctrine\DBAL\Driver\Statement as DriverStatement; @@ -26,6 +26,8 @@ * {@see execute()} time. The Artemeon driver layer only accepts positional `?` * placeholders, so named parameters are rejected (the DBAL Connection rewrites * them to positional before reaching us). + * + * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ final class Statement implements DriverStatement { From 19bc736ff01737ac07d5e42ff871a887e8e32444 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:07:44 +0100 Subject: [PATCH 07/19] feat: Read the real server version for DBAL platform detection The drivers no longer hard-code '16.0' (Postgres) and '3.0.0' (SQLite) or fall back silently to '8.0.0' (MySQL). Each driver now names the SQL that reports its version (VERSION(), SHOW server_version, sqlite_version()); the adapter runs it once, on first use, and throws if no version comes back. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Connection.php | 22 ++++++++++++++++++++-- src/Doctrine/Driver/MysqliDriver.php | 15 ++++++++------- src/Doctrine/Driver/PostgresDriver.php | 13 ++++++++----- src/Doctrine/Driver/Sqlite3Driver.php | 13 ++++++++----- 4 files changed, 44 insertions(+), 19 deletions(-) diff --git a/src/Doctrine/Driver/Connection.php b/src/Doctrine/Driver/Connection.php index ca1ac3b5..ecef7386 100644 --- a/src/Doctrine/Driver/Connection.php +++ b/src/Doctrine/Driver/Connection.php @@ -14,6 +14,7 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Exception\ConnectionException; use Doctrine\DBAL\Driver\Connection as DriverConnection; use Doctrine\DBAL\Driver\Exception\NoIdentityValue; use Doctrine\DBAL\Driver\Result as DriverResult; @@ -24,16 +25,21 @@ * * Platform selection happens in the driver classes of this namespace; this class only * wires DBAL's per-query primitives to the matching Artemeon Connection calls. - * The server-version string is supplied by the Driver and used by DBAL solely + * The server version is read from the database on first use and only serves DBAL * to pick a platform variant (MySQL 8.4 vs 8.0, MariaDB 11.7 vs 10.6, etc.). * * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ final class Connection implements DriverConnection { + private ?string $serverVersion = null; + + /** + * @param string $serverVersionQuery SQL returning the server version as a single value + */ public function __construct( private readonly ArtemeonConnection $connection, - private readonly string $serverVersion, + private readonly string $serverVersionQuery, ) { } @@ -82,8 +88,20 @@ public function getNativeConnection(): object return $this->connection; } + /** + * @throws ConnectionException if the database does not report a version + */ public function getServerVersion(): string { + if ($this->serverVersion === null) { + $version = $this->connection->fetchOne($this->serverVersionQuery); + if (!is_string($version) || $version === '') { + throw new ConnectionException('Could not determine the database server version via: ' . $this->serverVersionQuery); + } + + $this->serverVersion = $version; + } + return $this->serverVersion; } } diff --git a/src/Doctrine/Driver/MysqliDriver.php b/src/Doctrine/Driver/MysqliDriver.php index 79ac3cf4..b316181a 100644 --- a/src/Doctrine/Driver/MysqliDriver.php +++ b/src/Doctrine/Driver/MysqliDriver.php @@ -14,13 +14,12 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractMySQLDriver; -use Doctrine\DBAL\Driver\Connection as DriverConnection; +use Override; use SensitiveParameter; /** - * DBAL driver façade for an Artemeon Mysqli driver. + * DBAL driver for an Artemeon connection using the mysqli driver. * * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ @@ -30,10 +29,12 @@ public function __construct(private readonly ArtemeonConnection $connection) { } - public function connect(#[SensitiveParameter] array $params): DriverConnection + /** + * The Artemeon connection is already configured, so DBAL's connection parameters are ignored. + */ + #[Override] + public function connect(#[SensitiveParameter] array $params): Connection { - $version = $this->connection->fetchOne('SELECT VERSION()'); - - return new DriverConnectionAdapter($this->connection, is_string($version) ? $version : '8.0.0'); + return new Connection($this->connection, 'SELECT VERSION()'); } } diff --git a/src/Doctrine/Driver/PostgresDriver.php b/src/Doctrine/Driver/PostgresDriver.php index 68d00c7b..e035d029 100644 --- a/src/Doctrine/Driver/PostgresDriver.php +++ b/src/Doctrine/Driver/PostgresDriver.php @@ -14,13 +14,12 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver; -use Doctrine\DBAL\Driver\Connection as DriverConnection; +use Override; use SensitiveParameter; /** - * DBAL driver façade for an Artemeon Postgres driver. + * DBAL driver for an Artemeon connection using the postgres driver. * * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ @@ -30,8 +29,12 @@ public function __construct(private readonly ArtemeonConnection $connection) { } - public function connect(#[SensitiveParameter] array $params): DriverConnection + /** + * The Artemeon connection is already configured, so DBAL's connection parameters are ignored. + */ + #[Override] + public function connect(#[SensitiveParameter] array $params): Connection { - return new DriverConnectionAdapter($this->connection, '16.0'); + return new Connection($this->connection, 'SHOW server_version'); } } diff --git a/src/Doctrine/Driver/Sqlite3Driver.php b/src/Doctrine/Driver/Sqlite3Driver.php index b159b286..a315c5d8 100644 --- a/src/Doctrine/Driver/Sqlite3Driver.php +++ b/src/Doctrine/Driver/Sqlite3Driver.php @@ -14,13 +14,12 @@ namespace Artemeon\Database\Doctrine\Driver; use Artemeon\Database\Connection as ArtemeonConnection; -use Artemeon\Database\Doctrine\Driver\Connection as DriverConnectionAdapter; use Doctrine\DBAL\Driver\AbstractSQLiteDriver; -use Doctrine\DBAL\Driver\Connection as DriverConnection; +use Override; use SensitiveParameter; /** - * DBAL driver façade for an Artemeon Sqlite3 driver. + * DBAL driver for an Artemeon connection using the sqlite3 driver. * * @internal Only reachable through {@see ArtemeonConnection::createQueryBuilder()}. */ @@ -30,8 +29,12 @@ public function __construct(private readonly ArtemeonConnection $connection) { } - public function connect(#[SensitiveParameter] array $params): DriverConnection + /** + * The Artemeon connection is already configured, so DBAL's connection parameters are ignored. + */ + #[Override] + public function connect(#[SensitiveParameter] array $params): Connection { - return new DriverConnectionAdapter($this->connection, '3.0.0'); + return new Connection($this->connection, 'SELECT sqlite_version()'); } } From b985fbeb3c26edb265d2baeb789d8fccdd953808 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:08:16 +0100 Subject: [PATCH 08/19] fix: Fail loudly when no DBAL driver matches the connection createQueryBuilder() fell back to the SQLite platform for any driver that was not spelled exactly 'mysqli' or 'postgres'. It now picks the DBAL driver by the class of the actual Artemeon driver and throws a DriverNotFoundException otherwise. Co-Authored-By: Claude Opus 5.5 --- src/Connection.php | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/Connection.php b/src/Connection.php index a4446449..79d1b4d1 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -16,6 +16,9 @@ use Artemeon\Database\Doctrine\Driver\MysqliDriver as DoctrineMysqliDriver; use Artemeon\Database\Doctrine\Driver\PostgresDriver as DoctrinePostgresDriver; use Artemeon\Database\Doctrine\Driver\Sqlite3Driver as DoctrineSqlite3Driver; +use Artemeon\Database\Driver\MysqliDriver; +use Artemeon\Database\Driver\PostgresDriver; +use Artemeon\Database\Driver\Sqlite3Driver; use Artemeon\Database\Exception\AddColumnException; use Artemeon\Database\Exception\ChangeColumnException; use Artemeon\Database\Exception\CommitException; @@ -31,6 +34,7 @@ use Closure; use Doctrine\DBAL\Configuration as DbalConfiguration; use Doctrine\DBAL\Connection as DbalConnection; +use Doctrine\DBAL\Driver as DbalDriver; use Doctrine\DBAL\Query\QueryBuilder; use Generator; use InvalidArgumentException; @@ -358,21 +362,31 @@ public function executeStatement(string $query, array $params = []): int return $this->dbDriver->getAffectedRowsCount(); } + /** + * Creates a Doctrine DBAL QueryBuilder that runs its queries through this connection. + * + * @throws DriverNotFoundException if the configured driver has no DBAL counterpart + */ public function createQueryBuilder(): QueryBuilder { - if ($this->dbalConnection === null) { - $driver = match ($this->connectionParams->getDriver()) { - 'mysqli' => new DoctrineMysqliDriver($this), - 'postgres' => new DoctrinePostgresDriver($this), - default => new DoctrineSqlite3Driver($this), - }; - - $this->dbalConnection = new DbalConnection([], $driver, new DbalConfiguration()); - } + $this->dbalConnection ??= new DbalConnection([], $this->createDbalDriver(), new DbalConfiguration()); return $this->dbalConnection->createQueryBuilder(); } + /** + * @throws DriverNotFoundException + */ + private function createDbalDriver(): DbalDriver + { + return match (true) { + $this->dbDriver instanceof MysqliDriver => new DoctrineMysqliDriver($this), + $this->dbDriver instanceof PostgresDriver => new DoctrinePostgresDriver($this), + $this->dbDriver instanceof Sqlite3Driver => new DoctrineSqlite3Driver($this), + default => throw new DriverNotFoundException('No Doctrine DBAL driver for ' . $this->dbDriver::class), + }; + } + /** * @inheritDoc */ From 96ad4f337ef4173a806ab2cf645d94a651af9adc Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:09:01 +0100 Subject: [PATCH 09/19] fix: Quote string literals per platform The adapter doubled backslashes on every platform. SQLite and PostgreSQL (standard_conforming_strings) take backslashes literally, so a value passed through expr()->literal() came back with every backslash doubled. Only the MySQL driver escapes backslashes now. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Connection.php | 8 +++++++- src/Doctrine/Driver/MysqliDriver.php | 2 +- src/Doctrine/Driver/PostgresDriver.php | 2 +- src/Doctrine/Driver/Sqlite3Driver.php | 2 +- tests/Doctrine/QueryBuilderTest.php | 8 ++++++++ 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/Doctrine/Driver/Connection.php b/src/Doctrine/Driver/Connection.php index ecef7386..0b160946 100644 --- a/src/Doctrine/Driver/Connection.php +++ b/src/Doctrine/Driver/Connection.php @@ -36,10 +36,12 @@ final class Connection implements DriverConnection /** * @param string $serverVersionQuery SQL returning the server version as a single value + * @param bool $escapeBackslashes whether the database treats a backslash in string literals as escape character (MySQL) */ public function __construct( private readonly ArtemeonConnection $connection, private readonly string $serverVersionQuery, + private readonly bool $escapeBackslashes = false, ) { } @@ -55,7 +57,11 @@ public function query(string $sql): DriverResult public function quote(string $value): string { - return "'" . str_replace(['\\', "'"], ['\\\\', "''"], $value) . "'"; + if ($this->escapeBackslashes) { + $value = str_replace('\\', '\\\\', $value); + } + + return "'" . str_replace("'", "''", $value) . "'"; } public function exec(string $sql): int diff --git a/src/Doctrine/Driver/MysqliDriver.php b/src/Doctrine/Driver/MysqliDriver.php index b316181a..50a35ad8 100644 --- a/src/Doctrine/Driver/MysqliDriver.php +++ b/src/Doctrine/Driver/MysqliDriver.php @@ -35,6 +35,6 @@ public function __construct(private readonly ArtemeonConnection $connection) #[Override] public function connect(#[SensitiveParameter] array $params): Connection { - return new Connection($this->connection, 'SELECT VERSION()'); + return new Connection($this->connection, serverVersionQuery: 'SELECT VERSION()', escapeBackslashes: true); } } diff --git a/src/Doctrine/Driver/PostgresDriver.php b/src/Doctrine/Driver/PostgresDriver.php index e035d029..7bc55677 100644 --- a/src/Doctrine/Driver/PostgresDriver.php +++ b/src/Doctrine/Driver/PostgresDriver.php @@ -35,6 +35,6 @@ public function __construct(private readonly ArtemeonConnection $connection) #[Override] public function connect(#[SensitiveParameter] array $params): Connection { - return new Connection($this->connection, 'SHOW server_version'); + return new Connection($this->connection, serverVersionQuery: 'SHOW server_version'); } } diff --git a/src/Doctrine/Driver/Sqlite3Driver.php b/src/Doctrine/Driver/Sqlite3Driver.php index a315c5d8..0fe3f79e 100644 --- a/src/Doctrine/Driver/Sqlite3Driver.php +++ b/src/Doctrine/Driver/Sqlite3Driver.php @@ -35,6 +35,6 @@ public function __construct(private readonly ArtemeonConnection $connection) #[Override] public function connect(#[SensitiveParameter] array $params): Connection { - return new Connection($this->connection, 'SELECT sqlite_version()'); + return new Connection($this->connection, serverVersionQuery: 'SELECT sqlite_version()'); } } diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index dc896966..21385340 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -81,4 +81,12 @@ public function testUpdateThroughQueryBuilderReturnsAffectedRows(): void ); $this->assertSame('updated-via-qb', $check); } + + public function testLiteralRoundTripsQuotesAndBackslashes(): void + { + $value = "back\\slash 'quoted'"; + $qb = $this->getConnection()->createQueryBuilder(); + + $this->assertSame($value, $this->getConnection()->fetchOne('SELECT ' . $qb->expr()->literal($value))); + } } From f94bc220a0dd97e365a28c0777a114d78a320a30 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:09:29 +0100 Subject: [PATCH 10/19] refactor: Run DBAL statements through Connection::executeStatement() Statement::execute() rebuilt executeStatement() by hand from _pQuery() and getAffectedRowsCount(). Rejected parameters now raise an InvalidArgumentException (still a LogicException) instead of a bare LogicException. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Statement.php | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Doctrine/Driver/Statement.php b/src/Doctrine/Driver/Statement.php index 06a5e303..ad5a3927 100644 --- a/src/Doctrine/Driver/Statement.php +++ b/src/Doctrine/Driver/Statement.php @@ -16,7 +16,7 @@ use Artemeon\Database\Connection as ArtemeonConnection; use Doctrine\DBAL\Driver\Statement as DriverStatement; use Doctrine\DBAL\ParameterType; -use LogicException; +use InvalidArgumentException; use Stringable; /** @@ -31,7 +31,7 @@ */ final class Statement implements DriverStatement { - /** @var array */ + /** @var array */ private array $values = []; public function __construct( @@ -43,7 +43,7 @@ public function __construct( public function bindValue(int | string $param, mixed $value, ParameterType $type): void { if (is_string($param)) { - throw new LogicException( + throw new InvalidArgumentException( 'Named parameters are not supported by the Artemeon DBAL adapter; use positional placeholders.', ); } @@ -57,7 +57,7 @@ public function bindValue(int | string $param, mixed $value, ParameterType $type } if ($value !== null && !is_scalar($value)) { - throw new LogicException( + throw new InvalidArgumentException( 'Unsupported parameter type: ' . get_debug_type($value), ); } @@ -76,23 +76,20 @@ public function execute(): Result return new Result($rows, count($rows)); } - $this->connection->_pQuery($this->sql, $params, array_fill(0, count($params), false)); - $affected = $this->connection->getAffectedRowsCount(); - - return new Result([], $affected); + return new Result([], $this->connection->executeStatement($this->sql, $params)); } /** * Heuristic to decide whether a SQL string returns a result set. * * This exists because Artemeon splits execution into two separate methods — fetchAllAssociative() - * for queries and _pQuery() for statements — so the driver adapter must route before DBAL decides + * for queries and executeStatement() for statements — so the driver adapter must route before DBAL decides * which result interface to use. A real PDO-backed driver never needs this because PDO's execute() * returns a unified handle that supports both fetch() and rowCount() regardless of SQL type. * * Known limitation: writable CTEs (WITH … INSERT/UPDATE/DELETE) start with WITH and are therefore * misclassified as queries, causing them to be routed through fetchAllAssociative() instead of - * _pQuery(). The proper fix is to add a unified execute-and-return-result method to the Artemeon + * executeStatement(). The proper fix is to add a unified execute-and-return-result method to the Artemeon * Connection that returns both rows and an affected-row count in one call, eliminating the need * for this heuristic entirely. */ From 8daa3bf6a8ba5e6bfa3420c2995c8495dbdf1996 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:12:10 +0100 Subject: [PATCH 11/19] test: Cover the DBAL QueryBuilder adapter on every driver QueryBuilderTest runs against whatever DB_DRIVER points to, so CI exercises it on SQLite, PostgreSQL, MariaDB and MySQL. New cases: array parameter expansion, LIMIT/OFFSET, INSERT and DELETE, platform detection from the real server version, and the missing-driver error. Unit tests pin down Result, Statement routing and parameter checks, and the adapter connection (version caching, quoting, lastInsertId). Co-Authored-By: Claude Opus 5.5 --- tests/Doctrine/Driver/ConnectionTest.php | 70 +++++++++++ tests/Doctrine/Driver/ResultTest.php | 59 ++++++++++ tests/Doctrine/Driver/StatementTest.php | 86 ++++++++++++++ tests/Doctrine/QueryBuilderTest.php | 142 +++++++++++++++++++---- 4 files changed, 336 insertions(+), 21 deletions(-) create mode 100644 tests/Doctrine/Driver/ConnectionTest.php create mode 100644 tests/Doctrine/Driver/ResultTest.php create mode 100644 tests/Doctrine/Driver/StatementTest.php diff --git a/tests/Doctrine/Driver/ConnectionTest.php b/tests/Doctrine/Driver/ConnectionTest.php new file mode 100644 index 00000000..2b1fd8be --- /dev/null +++ b/tests/Doctrine/Driver/ConnectionTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests\Doctrine\Driver; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Doctrine\Driver\Connection; +use Artemeon\Database\Exception\ConnectionException; +use Doctrine\DBAL\Driver\Exception\NoIdentityValue; +use Mockery; +use PHPUnit\Framework\TestCase; + +/** + * @internal + */ +final class ConnectionTest extends TestCase +{ + #[\Override] + protected function tearDown(): void + { + Mockery::close(); + parent::tearDown(); + } + + public function testReadsTheServerVersionOnlyOnce(): void + { + $artemeon = Mockery::mock(ArtemeonConnection::class); + $artemeon->expects('fetchOne')->once()->with('SELECT VERSION()')->andReturn('10.6.21-MariaDB'); + + $connection = new Connection($artemeon, 'SELECT VERSION()'); + + $this->assertSame('10.6.21-MariaDB', $connection->getServerVersion()); + $this->assertSame('10.6.21-MariaDB', $connection->getServerVersion()); + } + + public function testThrowsWhenTheServerReportsNoVersion(): void + { + $artemeon = Mockery::mock(ArtemeonConnection::class); + $artemeon->allows('fetchOne')->andReturn(false); + + $this->expectException(ConnectionException::class); + + (new Connection($artemeon, 'SELECT VERSION()'))->getServerVersion(); + } + + public function testQuotesBackslashesOnlyWhenTheDatabaseTreatsThemAsEscapes(): void + { + $artemeon = Mockery::mock(ArtemeonConnection::class); + + $this->assertSame("'a\\b''c'", (new Connection($artemeon, ''))->quote("a\\b'c")); + $this->assertSame("'a\\\\b''c'", (new Connection($artemeon, '', escapeBackslashes: true))->quote("a\\b'c")); + } + + public function testHasNoIdentityValue(): void + { + $this->expectException(NoIdentityValue::class); + + (new Connection(Mockery::mock(ArtemeonConnection::class), ''))->lastInsertId(); + } +} diff --git a/tests/Doctrine/Driver/ResultTest.php b/tests/Doctrine/Driver/ResultTest.php new file mode 100644 index 00000000..56735014 --- /dev/null +++ b/tests/Doctrine/Driver/ResultTest.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests\Doctrine\Driver; + +use Artemeon\Database\Doctrine\Driver\Result; +use PHPUnit\Framework\TestCase; + +/** + * @internal + */ +final class ResultTest extends TestCase +{ + public function testReplaysRowsThroughTheFetchApi(): void + { + $result = new Result([['id' => 'a', 'n' => 1], ['id' => 'b', 'n' => 2], ['id' => 'c', 'n' => 3]], 3); + + $this->assertSame(['id' => 'a', 'n' => 1], $result->fetchAssociative()); + $this->assertSame(['b', 2], $result->fetchNumeric()); + $this->assertSame('c', $result->fetchOne()); + $this->assertFalse($result->fetchAssociative()); + $this->assertFalse($result->fetchOne()); + } + + public function testFetchAllContinuesFromTheCurrentRow(): void + { + $result = new Result([['id' => 'a'], ['id' => 'b'], ['id' => 'c']], 3); + $result->fetchNumeric(); + + $this->assertSame(['b', 'c'], $result->fetchFirstColumn()); + $this->assertSame([], $result->fetchAllAssociative()); + } + + public function testReportsCounts(): void + { + $this->assertSame(2, (new Result([['id' => 'a', 'n' => 1]], 7))->columnCount()); + $this->assertSame(7, (new Result([['id' => 'a', 'n' => 1]], 7))->rowCount()); + $this->assertSame(0, (new Result([], 4))->columnCount()); + } + + public function testFreeDropsTheRows(): void + { + $result = new Result([['id' => 'a']], 1); + $result->free(); + + $this->assertFalse($result->fetchAssociative()); + $this->assertSame(0, $result->columnCount()); + } +} diff --git a/tests/Doctrine/Driver/StatementTest.php b/tests/Doctrine/Driver/StatementTest.php new file mode 100644 index 00000000..db200d0c --- /dev/null +++ b/tests/Doctrine/Driver/StatementTest.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests\Doctrine\Driver; + +use Artemeon\Database\Connection as ArtemeonConnection; +use Artemeon\Database\Doctrine\Driver\Statement; +use Doctrine\DBAL\ParameterType; +use InvalidArgumentException; +use Mockery; +use PHPUnit\Framework\TestCase; +use stdClass; +use Stringable; + +/** + * @internal + */ +final class StatementTest extends TestCase +{ + #[\Override] + protected function tearDown(): void + { + Mockery::close(); + parent::tearDown(); + } + + public function testRoutesQueriesToFetchAllAssociativeWithParametersInPositionOrder(): void + { + $connection = Mockery::mock(ArtemeonConnection::class); + $connection->expects('fetchAllAssociative') + ->with('SELECT a FROM t WHERE b = ? AND c = ?', ['first', 1]) + ->andReturn([['a' => 'x'], ['a' => 'y']]); + + $statement = new Statement($connection, 'SELECT a FROM t WHERE b = ? AND c = ?'); + $statement->bindValue(2, true, ParameterType::BOOLEAN); + $statement->bindValue(1, new class () implements Stringable { + public function __toString(): string + { + return 'first'; + } + }, ParameterType::STRING); + $result = $statement->execute(); + + $this->assertSame(['x', 'y'], $result->fetchFirstColumn()); + $this->assertSame(2, $result->rowCount()); + } + + public function testRoutesStatementsToExecuteStatement(): void + { + $connection = Mockery::mock(ArtemeonConnection::class); + $connection->expects('executeStatement')->with('DELETE FROM t WHERE b = ?', ['x'])->andReturn(3); + + $statement = new Statement($connection, 'DELETE FROM t WHERE b = ?'); + $statement->bindValue(1, 'x', ParameterType::STRING); + + $this->assertSame(3, $statement->execute()->rowCount()); + } + + public function testRejectsNamedParameters(): void + { + $statement = new Statement(Mockery::mock(ArtemeonConnection::class), 'SELECT 1'); + + $this->expectException(InvalidArgumentException::class); + + $statement->bindValue('name', 'x', ParameterType::STRING); + } + + public function testRejectsNonScalarValues(): void + { + $statement = new Statement(Mockery::mock(ArtemeonConnection::class), 'SELECT ?'); + + $this->expectException(InvalidArgumentException::class); + + $statement->bindValue(1, new stdClass(), ParameterType::STRING); + } +} diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index 21385340..27bd44ba 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -13,21 +13,37 @@ namespace Artemeon\Database\Tests\Doctrine; +use Artemeon\Database\Connection; +use Artemeon\Database\ConnectionParameters; +use Artemeon\Database\Doctrine\Driver\MysqliDriver; +use Artemeon\Database\Doctrine\Driver\PostgresDriver; +use Artemeon\Database\Doctrine\Driver\Sqlite3Driver; +use Artemeon\Database\DriverFactory; +use Artemeon\Database\DriverInterface; +use Artemeon\Database\Exception\DriverNotFoundException; use Artemeon\Database\Tests\ConnectionTestCase; +use Doctrine\DBAL\ArrayParameterType; +use Doctrine\DBAL\Platforms\MariaDBPlatform; +use Doctrine\DBAL\Platforms\MySQLPlatform; +use Doctrine\DBAL\Platforms\PostgreSQLPlatform; +use Doctrine\DBAL\Platforms\SQLitePlatform; +use Mockery; /** + * Runs against the database configured via DB_DRIVER (SQLite by default; CI also runs PostgreSQL, MariaDB and MySQL). + * * @internal */ -class QueryBuilderTest extends ConnectionTestCase +final class QueryBuilderTest extends ConnectionTestCase { public function testSelectAllReturnsSeededRows(): void { - $qb = $this->getConnection()->createQueryBuilder() + $rows = $this->getConnection()->createQueryBuilder() ->select('temp_char10') ->from(self::TEST_TABLE_NAME) - ->orderBy('temp_bigint', 'ASC'); - - $rows = $qb->executeQuery()->fetchAllAssociative(); + ->orderBy('temp_bigint', 'ASC') + ->executeQuery() + ->fetchAllAssociative(); $this->assertCount(50, $rows); $this->assertSame('char10-1', $rows[0]['temp_char10']); @@ -36,13 +52,13 @@ public function testSelectAllReturnsSeededRows(): void public function testSelectWithPositionalParameter(): void { - $qb = $this->getConnection()->createQueryBuilder() + $row = $this->getConnection()->createQueryBuilder() ->select('temp_int', 'temp_char10') ->from(self::TEST_TABLE_NAME) ->where('temp_char10 = ?') - ->setParameter(0, 'char10-3'); - - $row = $qb->executeQuery()->fetchAssociative(); + ->setParameter(0, 'char10-3') + ->executeQuery() + ->fetchAssociative(); $this->assertIsArray($row); $this->assertSame('char10-3', $row['temp_char10']); @@ -51,35 +67,91 @@ public function testSelectWithPositionalParameter(): void public function testSelectWithNamedParameterGetsRewrittenByDoctrine(): void { - $qb = $this->getConnection()->createQueryBuilder() + $value = $this->getConnection()->createQueryBuilder() ->select('temp_char20') ->from(self::TEST_TABLE_NAME) ->where('temp_char10 = :needle') - ->setParameter('needle', 'char10-7'); - - $value = $qb->executeQuery()->fetchOne(); + ->setParameter('needle', 'char10-7') + ->executeQuery() + ->fetchOne(); $this->assertSame('char20-7', $value); } + public function testSelectWithArrayParameterGetsExpandedByDoctrine(): void + { + $qb = $this->getConnection()->createQueryBuilder(); + $values = $qb + ->select('temp_char10') + ->from(self::TEST_TABLE_NAME) + ->where($qb->expr()->in('temp_char10', ':needles')) + ->orderBy('temp_bigint', 'ASC') + ->setParameter('needles', ['char10-2', 'char10-4', 'char10-6'], ArrayParameterType::STRING) + ->executeQuery() + ->fetchFirstColumn(); + + $this->assertSame(['char10-2', 'char10-4', 'char10-6'], $values); + } + + public function testLimitAndOffsetUseThePlatformSyntax(): void + { + $values = $this->getConnection()->createQueryBuilder() + ->select('temp_char10') + ->from(self::TEST_TABLE_NAME) + ->orderBy('temp_bigint', 'ASC') + ->setFirstResult(10) + ->setMaxResults(3) + ->executeQuery() + ->fetchFirstColumn(); + + $this->assertSame(['char10-11', 'char10-12', 'char10-13'], $values); + } + public function testUpdateThroughQueryBuilderReturnsAffectedRows(): void { - $qb = $this->getConnection()->createQueryBuilder() + $affected = $this->getConnection()->createQueryBuilder() ->update(self::TEST_TABLE_NAME) ->set('temp_char100', '?') ->where('temp_char10 = ?') ->setParameter(0, 'updated-via-qb') - ->setParameter(1, 'char10-5'); - - $affected = $qb->executeStatement(); + ->setParameter(1, 'char10-5') + ->executeStatement(); $this->assertSame(1, $affected); - - $check = $this->getConnection()->fetchOne( + $this->assertSame('updated-via-qb', $this->getConnection()->fetchOne( 'SELECT temp_char100 FROM ' . self::TEST_TABLE_NAME . ' WHERE temp_char10 = ?', ['char10-5'], - ); - $this->assertSame('updated-via-qb', $check); + )); + } + + public function testInsertThroughQueryBuilder(): void + { + $affected = $this->getConnection()->createQueryBuilder() + ->insert(self::TEST_TABLE_NAME) + ->values(['temp_id' => ':id', 'temp_char10' => ':char10', 'temp_int' => ':int']) + ->setParameter('id', $this->generateSystemid()) + ->setParameter('char10', 'inserted') + ->setParameter('int', 42) + ->executeStatement(); + + $this->assertSame(1, $affected); + $this->assertEquals(42, $this->getConnection()->fetchOne( + 'SELECT temp_int FROM ' . self::TEST_TABLE_NAME . ' WHERE temp_char10 = ?', + ['inserted'], + )); + } + + public function testDeleteThroughQueryBuilderReturnsAffectedRows(): void + { + $qb = $this->getConnection()->createQueryBuilder(); + $affected = $qb + ->delete(self::TEST_TABLE_NAME) + ->where($qb->expr()->lte('temp_smallint', ':max')) + ->setParameter('max', 1010) + ->executeStatement(); + + $this->assertSame(10, $affected); + $this->assertEquals(40, $this->getConnection()->fetchOne('SELECT COUNT(*) FROM ' . self::TEST_TABLE_NAME)); } public function testLiteralRoundTripsQuotesAndBackslashes(): void @@ -89,4 +161,32 @@ public function testLiteralRoundTripsQuotesAndBackslashes(): void $this->assertSame($value, $this->getConnection()->fetchOne('SELECT ' . $qb->expr()->literal($value))); } + + public function testDetectsThePlatformFromTheRealServerVersion(): void + { + $connection = $this->getConnection(); + [$driver, $expectedPlatform] = match (getenv('DB_DRIVER') ?: 'sqlite3') { + 'mysqli' => [new MysqliDriver($connection), null], + 'postgres' => [new PostgresDriver($connection), PostgreSQLPlatform::class], + default => [new Sqlite3Driver($connection), SQLitePlatform::class], + }; + + $driverConnection = $driver->connect([]); + $version = $driverConnection->getServerVersion(); + $expectedPlatform ??= stripos($version, 'mariadb') !== false ? MariaDBPlatform::class : MySQLPlatform::class; + + $this->assertMatchesRegularExpression('/^\d+\.\d+/', $version); + $this->assertInstanceOf($expectedPlatform, $driver->getDatabasePlatform($driverConnection)); + } + + public function testThrowsForDriversWithoutDbalCounterpart(): void + { + $driverFactory = Mockery::mock(DriverFactory::class); + $driverFactory->allows('factory')->andReturn(Mockery::mock(DriverInterface::class)->shouldIgnoreMissing()); + $connection = new Connection(new ConnectionParameters('localhost', '', '', ':memory:', null, 'custom'), $driverFactory); + + $this->expectException(DriverNotFoundException::class); + + $connection->createQueryBuilder(); + } } From 258b0e4fcb93800f8d574aaae828db033a879a55 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:12:29 +0100 Subject: [PATCH 12/19] docs: Tidy the query builder example Fix the outdated note about require-dev, drop the no-op dropTable() calls on the in-memory database and show array parameter expansion (ArrayParameterType) instead of hand-numbered IN placeholders. Co-Authored-By: Claude Opus 5.5 --- examples/query_builder_sqlite.php | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/examples/query_builder_sqlite.php b/examples/query_builder_sqlite.php index 6bdf445c..5f731ce4 100644 --- a/examples/query_builder_sqlite.php +++ b/examples/query_builder_sqlite.php @@ -18,13 +18,15 @@ * * php examples/query_builder_sqlite.php * - * Requires `doctrine/dbal:^4` to be installed (already in require-dev). + * Uses SQLite so it runs without a database server; the same calls work on + * MySQL/MariaDB and PostgreSQL connections. */ use Artemeon\Database\Connection; use Artemeon\Database\ConnectionParameters; use Artemeon\Database\DriverFactory; use Artemeon\Database\Schema\DataType; +use Doctrine\DBAL\ArrayParameterType; require __DIR__ . '/../vendor/autoload.php'; @@ -44,9 +46,6 @@ $table = 'demo_books'; $tableReviews = 'demo_reviews'; -$connection->dropTable($table); -$connection->dropTable($tableReviews); - $connection->createTable( $table, [ @@ -148,8 +147,8 @@ printf(" Total books in table: %d\n", $count); -echo "\n5) Complex WHERE with AND, OR, and IN\n"; -echo "---------------------------------------\n"; +echo "\n5) Complex WHERE with AND, OR, and IN (array parameter)\n"; +echo "-------------------------------------------------------\n"; // Books published before 2000 OR after 2010, but only from a specific id set $qb = $connection->createQueryBuilder(); $rows = $qb @@ -161,14 +160,12 @@ $qb->expr()->lt('year', ':cutoff_low'), $qb->expr()->gt('year', ':cutoff_high'), ), - $qb->expr()->in('id', [':b1', ':b2', ':b3']), + $qb->expr()->in('id', ':ids'), ), ) ->setParameter('cutoff_low', 2000) ->setParameter('cutoff_high', 2010) - ->setParameter('b1', 'b-1') - ->setParameter('b2', 'b-3') - ->setParameter('b3', 'b-5') + ->setParameter('ids', ['b-1', 'b-3', 'b-5'], ArrayParameterType::STRING) ->orderBy('year', 'ASC') ->executeQuery() ->fetchAllAssociative(); From 94b356a14b00c838fd2a119889ed89b4c18f764e Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:12:39 +0100 Subject: [PATCH 13/19] docs: Document createQueryBuilder() in README and CHANGELOG Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ README.md | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33654792..f294beb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Add `Connection::createQueryBuilder()` returning a Doctrine DBAL QueryBuilder; adds `doctrine/dbal: ^4` as a dependency. + # 4.0.0 - Add support for PHP 8.4. diff --git a/README.md b/README.md index 410a55ef..c19ebb32 100644 --- a/README.md +++ b/README.md @@ -8,3 +8,23 @@ The following matrix shows the Branch to AGP version mapping | `4.0.x` | 11.0 | | `3.0.x` | 10.0 | | `0.2.x` | 9.0 | + +## Query builder + +`Connection::createQueryBuilder()` returns a [Doctrine DBAL QueryBuilder](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.2/reference/query-builder.html) +whose queries run through the existing Artemeon connection (same driver, same transaction): + +```php +$qb = $connection->createQueryBuilder(); +$rows = $qb + ->select('title', 'year') + ->from('books') + ->where($qb->expr()->in('id', ':ids')) + ->setParameter('ids', ['b-1', 'b-3'], ArrayParameterType::STRING) + ->setMaxResults(10) + ->executeQuery() + ->fetchAllAssociative(); +``` + +Works with the `mysqli`, `postgres` and `sqlite3` drivers. `lastInsertId()` is not supported. +A runnable demo lives in [`examples/query_builder_sqlite.php`](examples/query_builder_sqlite.php). From d130303477331acba0fa38853d2d1b8d7151c09c Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:26:33 +0100 Subject: [PATCH 14/19] fix: Keep QueryBuilder writes free of HTML encoding f94bc22 routed writes through Connection::executeStatement(), which passes no escape flags, so dbsafeParams() HTML-encoded every parameter: 'A & B' was stored as 'A & B' and WHERE parameters of UPDATE/DELETE stopped matching. Go back to _pQuery() with escaping disabled, like the read path. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Statement.php | 9 ++++++--- tests/Doctrine/Driver/StatementTest.php | 5 +++-- tests/Doctrine/QueryBuilderTest.php | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/Doctrine/Driver/Statement.php b/src/Doctrine/Driver/Statement.php index ad5a3927..bc94438b 100644 --- a/src/Doctrine/Driver/Statement.php +++ b/src/Doctrine/Driver/Statement.php @@ -76,20 +76,23 @@ public function execute(): Result return new Result($rows, count($rows)); } - return new Result([], $this->connection->executeStatement($this->sql, $params)); + // Not executeStatement(): it HTML-encodes parameters (dbsafeString), the read path does not. + $this->connection->_pQuery($this->sql, $params, array_fill(0, count($params), false)); + + return new Result([], $this->connection->getAffectedRowsCount()); } /** * Heuristic to decide whether a SQL string returns a result set. * * This exists because Artemeon splits execution into two separate methods — fetchAllAssociative() - * for queries and executeStatement() for statements — so the driver adapter must route before DBAL decides + * for queries and _pQuery() for statements — so the driver adapter must route before DBAL decides * which result interface to use. A real PDO-backed driver never needs this because PDO's execute() * returns a unified handle that supports both fetch() and rowCount() regardless of SQL type. * * Known limitation: writable CTEs (WITH … INSERT/UPDATE/DELETE) start with WITH and are therefore * misclassified as queries, causing them to be routed through fetchAllAssociative() instead of - * executeStatement(). The proper fix is to add a unified execute-and-return-result method to the Artemeon + * _pQuery(). The proper fix is to add a unified execute-and-return-result method to the Artemeon * Connection that returns both rows and an affected-row count in one call, eliminating the need * for this heuristic entirely. */ diff --git a/tests/Doctrine/Driver/StatementTest.php b/tests/Doctrine/Driver/StatementTest.php index db200d0c..f5a077e3 100644 --- a/tests/Doctrine/Driver/StatementTest.php +++ b/tests/Doctrine/Driver/StatementTest.php @@ -55,10 +55,11 @@ public function __toString(): string $this->assertSame(2, $result->rowCount()); } - public function testRoutesStatementsToExecuteStatement(): void + public function testRoutesStatementsToPQueryWithoutEscaping(): void { $connection = Mockery::mock(ArtemeonConnection::class); - $connection->expects('executeStatement')->with('DELETE FROM t WHERE b = ?', ['x'])->andReturn(3); + $connection->expects('_pQuery')->with('DELETE FROM t WHERE b = ?', ['x'], [false])->andReturn(true); + $connection->expects('getAffectedRowsCount')->andReturn(3); $statement = new Statement($connection, 'DELETE FROM t WHERE b = ?'); $statement->bindValue(1, 'x', ParameterType::STRING); diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index 27bd44ba..557273af 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -189,4 +189,24 @@ public function testThrowsForDriversWithoutDbalCounterpart(): void $connection->createQueryBuilder(); } + + public function testWritesStoreSpecialCharactersUnencoded(): void + { + $value = 'Tom & Jerry "quoted"'; + $this->getConnection()->createQueryBuilder() + ->update(self::TEST_TABLE_NAME) + ->set('temp_char100', ':value') + ->where('temp_char10 = :key') + ->setParameter('value', $value) + ->setParameter('key', 'char10-8') + ->executeStatement(); + + $this->assertSame($value, $this->getConnection()->createQueryBuilder() + ->select('temp_char100') + ->from(self::TEST_TABLE_NAME) + ->where('temp_char100 = :value') + ->setParameter('value', $value) + ->executeQuery() + ->fetchOne()); + } } From 221a543d03cc0c3c897f6e413effe762a01525a0 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:41:25 +0100 Subject: [PATCH 15/19] fix: Keep quoted literals intact through the Artemeon query rewrites The Artemeon drivers rewrite the SQL text without regard for string literals, which broke values from expr()->literal(): - SQLite: fixQuoting() turns \' into '', so a literal like x\' OR 1=1 -- closed early and injected SQL, and a trailing backslash left the string unterminated. - SQLite and PostgreSQL: every ? became a placeholder, so 'Why?' was stored as 'Why:param1' or failed to bind. quote() now concatenates these characters in as char()/chr() expressions ('a' || char(63) || 'b'), so they never appear inside the literal. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Connection.php | 22 +++++++++++++ src/Doctrine/Driver/PostgresDriver.php | 7 +++- src/Doctrine/Driver/Sqlite3Driver.php | 7 +++- tests/Doctrine/Driver/ConnectionTest.php | 10 ++++++ tests/Doctrine/QueryBuilderTest.php | 42 ++++++++++++++++++++++-- 5 files changed, 83 insertions(+), 5 deletions(-) diff --git a/src/Doctrine/Driver/Connection.php b/src/Doctrine/Driver/Connection.php index 0b160946..47cbe0be 100644 --- a/src/Doctrine/Driver/Connection.php +++ b/src/Doctrine/Driver/Connection.php @@ -37,11 +37,16 @@ final class Connection implements DriverConnection /** * @param string $serverVersionQuery SQL returning the server version as a single value * @param bool $escapeBackslashes whether the database treats a backslash in string literals as escape character (MySQL) + * @param array $characterExpressions characters that quote() must not emit + * verbatim, mapped to an SQL expression producing them. The Artemeon drivers rewrite the SQL text without + * regard for string literals (e.g. `?` becomes a placeholder), so these characters are concatenated in + * (`'a' || chr(63) || 'b'`) instead of appearing inside the literal. */ public function __construct( private readonly ArtemeonConnection $connection, private readonly string $serverVersionQuery, private readonly bool $escapeBackslashes = false, + private readonly array $characterExpressions = [], ) { } @@ -61,6 +66,23 @@ public function quote(string $value): string $value = str_replace('\\', '\\\\', $value); } + if ($this->characterExpressions === []) { + return self::quoteVerbatim($value); + } + + $pattern = '/(' . implode('|', array_map(static fn (string $character): string => preg_quote($character, '/'), array_keys($this->characterExpressions))) . ')/'; + if (preg_match($pattern, $value) !== 1) { + return self::quoteVerbatim($value); + } + + $parts = preg_split($pattern, $value, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: []; + $sql = array_map(fn (string $part): string => $this->characterExpressions[$part] ?? self::quoteVerbatim($part), $parts); + + return '(' . implode(' || ', $sql) . ')'; + } + + private static function quoteVerbatim(string $value): string + { return "'" . str_replace("'", "''", $value) . "'"; } diff --git a/src/Doctrine/Driver/PostgresDriver.php b/src/Doctrine/Driver/PostgresDriver.php index 7bc55677..7a918598 100644 --- a/src/Doctrine/Driver/PostgresDriver.php +++ b/src/Doctrine/Driver/PostgresDriver.php @@ -35,6 +35,11 @@ public function __construct(private readonly ArtemeonConnection $connection) #[Override] public function connect(#[SensitiveParameter] array $params): Connection { - return new Connection($this->connection, serverVersionQuery: 'SHOW server_version'); + return new Connection( + $this->connection, + serverVersionQuery: 'SHOW server_version', + // PostgresDriver::processQuery() turns every ? into a $n placeholder. + characterExpressions: ['?' => 'chr(63)'], + ); } } diff --git a/src/Doctrine/Driver/Sqlite3Driver.php b/src/Doctrine/Driver/Sqlite3Driver.php index 0fe3f79e..9ee60a67 100644 --- a/src/Doctrine/Driver/Sqlite3Driver.php +++ b/src/Doctrine/Driver/Sqlite3Driver.php @@ -35,6 +35,11 @@ public function __construct(private readonly ArtemeonConnection $connection) #[Override] public function connect(#[SensitiveParameter] array $params): Connection { - return new Connection($this->connection, serverVersionQuery: 'SELECT sqlite_version()'); + return new Connection( + $this->connection, + serverVersionQuery: 'SELECT sqlite_version()', + // Sqlite3Driver rewrites \' to '' (fixQuoting) and every ? into a :param placeholder (processQuery). + characterExpressions: ['\\' => 'char(92)', '?' => 'char(63)'], + ); } } diff --git a/tests/Doctrine/Driver/ConnectionTest.php b/tests/Doctrine/Driver/ConnectionTest.php index 2b1fd8be..da899610 100644 --- a/tests/Doctrine/Driver/ConnectionTest.php +++ b/tests/Doctrine/Driver/ConnectionTest.php @@ -61,6 +61,16 @@ public function testQuotesBackslashesOnlyWhenTheDatabaseTreatsThemAsEscapes(): v $this->assertSame("'a\\\\b''c'", (new Connection($artemeon, '', escapeBackslashes: true))->quote("a\\b'c")); } + public function testConcatenatesCharactersTheArtemeonDriversWouldRewrite(): void + { + $connection = new Connection(Mockery::mock(ArtemeonConnection::class), '', characterExpressions: ['\\' => 'char(92)', '?' => 'char(63)']); + + $this->assertSame("('it''s' || char(92) || char(63))", $connection->quote("it's\\?")); + $this->assertSame('(char(63))', $connection->quote('?')); + $this->assertSame("'plain'", $connection->quote('plain')); + $this->assertSame("''", $connection->quote('')); + } + public function testHasNoIdentityValue(): void { $this->expectException(NoIdentityValue::class); diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index 557273af..151cc13d 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -28,6 +28,7 @@ use Doctrine\DBAL\Platforms\PostgreSQLPlatform; use Doctrine\DBAL\Platforms\SQLitePlatform; use Mockery; +use PHPUnit\Framework\Attributes\DataProvider; /** * Runs against the database configured via DB_DRIVER (SQLite by default; CI also runs PostgreSQL, MariaDB and MySQL). @@ -154,12 +155,47 @@ public function testDeleteThroughQueryBuilderReturnsAffectedRows(): void $this->assertEquals(40, $this->getConnection()->fetchOne('SELECT COUNT(*) FROM ' . self::TEST_TABLE_NAME)); } - public function testLiteralRoundTripsQuotesAndBackslashes(): void + /** + * @return iterable + */ + public static function literalProvider(): iterable { - $value = "back\\slash 'quoted'"; + yield 'backslash and quotes' => ["back\\slash 'quoted'"]; + yield 'backslash before quote' => ["x\\' OR 1=1 --"]; + yield 'trailing backslash' => ['C:\\']; + yield 'question marks' => ['Why? a?b ?']; + yield 'empty' => ['']; + } + + #[DataProvider('literalProvider')] + public function testLiteralRoundTripsOnReads(string $value): void + { + $qb = $this->getConnection()->createQueryBuilder(); + + $this->assertSame($value, $qb->select($qb->expr()->literal($value))->executeQuery()->fetchOne()); + } + + #[DataProvider('literalProvider')] + public function testLiteralRoundTripsOnWritesAndMatchesOnlyItself(string $value): void + { + $qb = $this->getConnection()->createQueryBuilder(); + $affected = $qb + ->update(self::TEST_TABLE_NAME) + ->set('temp_char100', $qb->expr()->literal($value)) + ->where('temp_char10 = ?') + ->setParameter(0, 'char10-9') + ->executeStatement(); + $this->assertSame(1, $affected); + $qb = $this->getConnection()->createQueryBuilder(); + $rows = $qb + ->select('temp_char10', 'temp_char100') + ->from(self::TEST_TABLE_NAME) + ->where($qb->expr()->eq('temp_char100', $qb->expr()->literal($value))) + ->executeQuery() + ->fetchAllAssociative(); - $this->assertSame($value, $this->getConnection()->fetchOne('SELECT ' . $qb->expr()->literal($value))); + $this->assertSame([['temp_char10' => 'char10-9', 'temp_char100' => $value]], $rows); } public function testDetectsThePlatformFromTheRealServerVersion(): void From 0d4478446013e2320a34cc633a50fc96ec7b5ba8 Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:41:55 +0100 Subject: [PATCH 16/19] fix: Bind booleans as integers regardless of the declared type setParameter(0, false) defaults to ParameterType::STRING, so the bool reached fetchAllAssociative() unconverted and went out as '', which PostgreSQL rejects for integer columns, while writes converted it to 0. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Statement.php | 3 ++- tests/Doctrine/QueryBuilderTest.php | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/Doctrine/Driver/Statement.php b/src/Doctrine/Driver/Statement.php index bc94438b..879cdb17 100644 --- a/src/Doctrine/Driver/Statement.php +++ b/src/Doctrine/Driver/Statement.php @@ -48,7 +48,8 @@ public function bindValue(int | string $param, mixed $value, ParameterType $type ); } - if ($type === ParameterType::BOOLEAN && is_bool($value)) { + // Regardless of the declared type: the read path would otherwise send false as '' (rejected by PostgreSQL). + if (is_bool($value)) { $value = (int) $value; } diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index 151cc13d..60351be4 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -198,6 +198,28 @@ public function testLiteralRoundTripsOnWritesAndMatchesOnlyItself(string $value) $this->assertSame([['temp_char10' => 'char10-9', 'temp_char100' => $value]], $rows); } + public function testBooleanParametersWithoutExplicitTypeWorkOnReadsAndWrites(): void + { + $affected = $this->getConnection()->createQueryBuilder() + ->update(self::TEST_TABLE_NAME) + ->set('temp_tinyint', '?') + ->where('temp_char10 = ?') + ->setParameter(0, false) + ->setParameter(1, 'char10-1') + ->executeStatement(); + $this->assertSame(1, $affected); + + $values = $this->getConnection()->createQueryBuilder() + ->select('temp_char10') + ->from(self::TEST_TABLE_NAME) + ->where('temp_tinyint = ?') + ->setParameter(0, false) + ->executeQuery() + ->fetchFirstColumn(); + + $this->assertSame(['char10-1'], $values); + } + public function testDetectsThePlatformFromTheRealServerVersion(): void { $connection = $this->getConnection(); From d35f9cbfc87834a4c03c18e66adcf68a608947bc Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:42:34 +0100 Subject: [PATCH 17/19] feat: Support Result::getColumnName() in the DBAL adapter DBAL 4 calls getColumnName() for result caching (enableResultCache()) and exposes it on its Result; without it the adapter threw a LogicException. Names come from the first buffered row, so an empty result has none. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Result.php | 16 ++++++++++++++++ tests/Doctrine/Driver/ResultTest.php | 23 +++++++++++++++++++++++ tests/Doctrine/QueryBuilderTest.php | 11 +++++++++++ 3 files changed, 50 insertions(+) diff --git a/src/Doctrine/Driver/Result.php b/src/Doctrine/Driver/Result.php index 25ca089b..466bbdd4 100644 --- a/src/Doctrine/Driver/Result.php +++ b/src/Doctrine/Driver/Result.php @@ -14,6 +14,7 @@ namespace Artemeon\Database\Doctrine\Driver; use Doctrine\DBAL\Driver\Result as DriverResult; +use Doctrine\DBAL\Exception\InvalidColumnIndex; /** * Buffered DBAL driver result backed by a pre-fetched row array. @@ -112,6 +113,21 @@ public function columnCount(): int return $first === null ? 0 : count($first); } + /** + * Column names are taken from the first row, so an empty result has none. + * + * @throws InvalidColumnIndex + */ + public function getColumnName(int $index): string + { + $name = array_keys($this->rows[0] ?? [])[$index] ?? null; + if (!is_string($name)) { + throw InvalidColumnIndex::new($index); + } + + return $name; + } + public function free(): void { $this->rows = []; diff --git a/tests/Doctrine/Driver/ResultTest.php b/tests/Doctrine/Driver/ResultTest.php index 56735014..47643d60 100644 --- a/tests/Doctrine/Driver/ResultTest.php +++ b/tests/Doctrine/Driver/ResultTest.php @@ -14,6 +14,7 @@ namespace Artemeon\Database\Tests\Doctrine\Driver; use Artemeon\Database\Doctrine\Driver\Result; +use Doctrine\DBAL\Exception\InvalidColumnIndex; use PHPUnit\Framework\TestCase; /** @@ -48,6 +49,28 @@ public function testReportsCounts(): void $this->assertSame(0, (new Result([], 4))->columnCount()); } + public function testReturnsColumnNamesFromTheFirstRow(): void + { + $result = new Result([['id' => 'a', 'n' => 1]], 1); + + $this->assertSame('id', $result->getColumnName(0)); + $this->assertSame('n', $result->getColumnName(1)); + } + + public function testThrowsForUnknownColumnIndexes(): void + { + $this->expectException(InvalidColumnIndex::class); + + (new Result([['id' => 'a']], 1))->getColumnName(1); + } + + public function testHasNoColumnNamesWithoutRows(): void + { + $this->expectException(InvalidColumnIndex::class); + + (new Result([], 0))->getColumnName(0); + } + public function testFreeDropsTheRows(): void { $result = new Result([['id' => 'a']], 1); diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index 60351be4..b2cd20b2 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -220,6 +220,17 @@ public function testBooleanParametersWithoutExplicitTypeWorkOnReadsAndWrites(): $this->assertSame(['char10-1'], $values); } + public function testExposesColumnNames(): void + { + $result = $this->getConnection()->createQueryBuilder() + ->select('temp_char10', 'temp_int AS alias_int') + ->from(self::TEST_TABLE_NAME) + ->executeQuery(); + + $this->assertSame('temp_char10', $result->getColumnName(0)); + $this->assertSame('alias_int', $result->getColumnName(1)); + } + public function testDetectsThePlatformFromTheRealServerVersion(): void { $connection = $this->getConnection(); From 1423862be91b89063ec3a503cacec623eb1854dd Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Sun, 29 Nov 2026 21:44:53 +0100 Subject: [PATCH 18/19] test: Pin down query routing for UNION and CTEs Only QueryBuilder SQL reaches the adapter, so RETURNING, writable CTEs, leading comments and CALL cannot be built (except as raw union()/with() strings). Document that instead of the outdated writable-CTE caveat, and cover the two QueryBuilder shapes that do not start with SELECT. Co-Authored-By: Claude Opus 5.5 --- src/Doctrine/Driver/Statement.php | 10 +++++----- tests/Doctrine/QueryBuilderTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/Doctrine/Driver/Statement.php b/src/Doctrine/Driver/Statement.php index 879cdb17..459709d6 100644 --- a/src/Doctrine/Driver/Statement.php +++ b/src/Doctrine/Driver/Statement.php @@ -91,11 +91,11 @@ public function execute(): Result * which result interface to use. A real PDO-backed driver never needs this because PDO's execute() * returns a unified handle that supports both fetch() and rowCount() regardless of SQL type. * - * Known limitation: writable CTEs (WITH … INSERT/UPDATE/DELETE) start with WITH and are therefore - * misclassified as queries, causing them to be routed through fetchAllAssociative() instead of - * _pQuery(). The proper fix is to add a unified execute-and-return-result method to the Artemeon - * Connection that returns both rows and an affected-row count in one call, eliminating the need - * for this heuristic entirely. + * Only SQL generated by DBAL's QueryBuilder reaches this adapter (the DBAL connection is not exposed), + * so the input starts with SELECT, WITH … SELECT, a parenthesised UNION part, INSERT, UPDATE or DELETE. + * Statements the heuristic would misroute (… RETURNING, writable CTEs, leading comments, CALL) cannot be + * built with the QueryBuilder, except as a raw string passed to union()/with(). Should the DBAL connection ever be exposed for raw SQL, replace this with a + * Connection method that returns rows and the affected-row count in one call. */ private static function returnsResultSet(string $sql): bool { diff --git a/tests/Doctrine/QueryBuilderTest.php b/tests/Doctrine/QueryBuilderTest.php index b2cd20b2..83f5c26d 100644 --- a/tests/Doctrine/QueryBuilderTest.php +++ b/tests/Doctrine/QueryBuilderTest.php @@ -94,6 +94,32 @@ public function testSelectWithArrayParameterGetsExpandedByDoctrine(): void $this->assertSame(['char10-2', 'char10-4', 'char10-6'], $values); } + public function testUnionIsRoutedAsQuery(): void + { + $qb = $this->getConnection()->createQueryBuilder(); + $values = $qb + ->union($this->getConnection()->createQueryBuilder()->select('temp_char10')->from(self::TEST_TABLE_NAME)->where("temp_char10 = 'char10-1'")) + ->addUnion($this->getConnection()->createQueryBuilder()->select('temp_char10')->from(self::TEST_TABLE_NAME)->where("temp_char10 = 'char10-2'")) + ->orderBy('temp_char10') + ->executeQuery() + ->fetchFirstColumn(); + + $this->assertSame(['char10-1', 'char10-2'], $values); + } + + public function testCommonTableExpressionIsRoutedAsQuery(): void + { + $values = $this->getConnection()->createQueryBuilder() + ->with('low', $this->getConnection()->createQueryBuilder()->select('temp_char10', 'temp_bigint')->from(self::TEST_TABLE_NAME)->where('temp_smallint <= 1002')) + ->select('temp_char10') + ->from('low') + ->orderBy('temp_bigint') + ->executeQuery() + ->fetchFirstColumn(); + + $this->assertSame(['char10-1', 'char10-2'], $values); + } + public function testLimitAndOffsetUseThePlatformSyntax(): void { $values = $this->getConnection()->createQueryBuilder() From eae11daf7169871680cc98d319ed7230be5644ce Mon Sep 17 00:00:00 2001 From: Roman Konz Date: Mon, 30 Nov 2026 07:23:51 +0100 Subject: [PATCH 19/19] docs: Explain how to match HTML-encoded data with the query builder Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index c19ebb32..353c9ba8 100644 --- a/README.md +++ b/README.md @@ -27,4 +27,19 @@ $rows = $qb ``` Works with the `mysqli`, `postgres` and `sqlite3` drivers. `lastInsertId()` is not supported. + +Parameters are passed to the database as they are, like with the `fetch*()` methods. Unlike `getPArray()` and +`executeStatement()`, the query builder does not HTML-encode them. Data written with HTML encoding (e.g. by an ORM on +top of this library) therefore only matches if you encode the value the same way yourself: + +```php +$encode = static fn (string $value): string => + htmlspecialchars(html_entity_decode($value, ENT_COMPAT, 'UTF-8'), ENT_COMPAT, 'UTF-8'); + +$qb->where('title = :title')->setParameter('title', $encode('A & B')); // matches 'A & B' +``` + +This is the encoding `getPArray()` and `executeStatement()` apply. Also use it when writing to columns that are read or +rendered as encoded text, and for values passed to `expr()->literal()`. Leave numbers, IDs and booleans as they are. +Results are returned as stored, without decoding. A runnable demo lives in [`examples/query_builder_sqlite.php`](examples/query_builder_sqlite.php).