Skip to content

feat: Add Doctrine DBAL QueryBuilder support - #101

Merged
romankonz merged 20 commits into
5.xfrom
feat/doctrine-query-builder
Dec 1, 2026
Merged

romankonz merged 20 commits into
5.xfrom
feat/doctrine-query-builder

Conversation

@romankonz

@romankonz romankonz commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Was

  • Neue Methode Connection::createQueryBuilder() liefert einen Doctrine DBAL QueryBuilder (DBAL 4).
  • Die Queries laufen über die bestehende Artemeon-Verbindung: gleicher Treiber, gleiche Transaktion, gleiches Logging.
  • Adapter unter src/Doctrine/Driver/, alles @internal:
    • DBAL-Treiber MysqliDriver, PostgresDriver, Sqlite3Driver
    • Connection, Statement, Result
  • doctrine/dbal: ^4 ist neue Runtime-Abhängigkeit in composer.json.
  • Die Platform (MySQL 8.0/8.4, MariaDB-Varianten, PostgreSQL, SQLite) wählt DBAL anhand der echten Server-Version. Die wird beim ersten Gebrauch per SQL gelesen.
  • Ein Treiber ohne DBAL-Gegenstück wirft DriverNotFoundException.

Warum

  • SQL dynamisch zusammensetzen ohne String-Konkatenation: Bedingungen, IN-Listen, LIMIT/OFFSET je Platform.
  • Kein zweiter Verbindungs-Stack: DBAL nutzt die vorhandene Artemeon-Verbindung, statt eine eigene aufzubauen.

Nutzung

$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();
  • Ausführbares Beispiel: php examples/query_builder_sqlite.php
  • README hat einen Abschnitt „Query builder“, CHANGELOG einen Eintrag unter „Unreleased“.

Details zum Adapter

  • Lesen läuft über fetchAllAssociative(), Schreiben über _pQuery() ohne Escaping. Beide Wege speichern und vergleichen Werte also unverändert (keine HTML-Kodierung, siehe Grenzen).
  • quote() verdoppelt Backslashes nur auf MySQL. Auf SQLite und PostgreSQL setzt es \ bzw. ? per char()/chr() zusammen, damit expr()->literal() die SQL-Umschreibungen der Artemeon-Treiber übersteht (sonst wäre auf SQLite eine Injection über \' möglich).
  • Bools werden unabhängig vom Parametertyp als int gebunden (PostgreSQL lehnt '' für false ab).
  • Result::getColumnName() ist umgesetzt, damit funktioniert auch enableResultCache().

Grenzen

  • lastInsertId() wird nicht unterstützt (wirft NoIdentityValue).
  • Parameter gehen roh an die Datenbank, wie bei fetch*(). Anders als getPArray()/executeStatement() kodiert der QueryBuilder nichts als HTML. Daten, die HTML-kodiert gespeichert wurden (in AGP alles, was der ORM schreibt, außer bei #[BlockEscaping]), findet man nur, wenn man den Wert selbst kodiert: htmlspecialchars(html_entity_decode($v, ENT_COMPAT, 'UTF-8'), ENT_COMPAT, 'UTF-8'). Das ist dieselbe Kodierung wie dbsafeString(), geprüft u. a. mit &, <, ", ', schon kodierten Werten und Umlauten. Dasselbe gilt beim Schreiben in Spalten, die der ORM liest. Details in der README.
  • Der Adapter sieht nur QueryBuilder-SQL und routet nach dem SQL-Anfang. RETURNING, Kommentare oder schreibende CTEs lassen sich darüber nicht bauen.
  • Die Artemeon-Treiber schreiben das SQL ohne Rücksicht auf Literale um. literal() ist davor geschützt, selbst geschriebene Literale nicht: Ein ? darin wird auf SQLite/Postgres zum Platzhalter, Postgres macht aus LIKE ein ILIKE, und doppelte Leerzeichen werden beim Schreiben zusammengezogen. Ein sauberer Fix bräuchte einen eigenen Ausführungsweg und wäre ein Breaking Change an DriverInterface.
  • Fehler der Datenbank kommen als Artemeon-Exceptions (QueryException) durch, nicht als DBAL-Exceptions.
  • Die API steht nur auf Connection, nicht auf ConnectionInterface (bewusst: kein Breaking Change).

Tests

  • tests/Doctrine/QueryBuilderTest.php läuft gegen den Treiber aus DB_DRIVER, in der CI also auf SQLite, PostgreSQL, MariaDB und MySQL. Abgedeckt:
    • SELECT mit positionalen, benannten, Array- und Bool-Parametern
    • UNION und CTE (with())
    • LIMIT/OFFSET
    • INSERT, UPDATE, DELETE mit Anzahl betroffener Zeilen
    • expr()->literal() beim Lesen und Schreiben: Backslash, \', Backslash am Ende, ?, leerer String
    • Sonderzeichen (&, <, ") werden ohne HTML-Kodierung gespeichert
    • Spaltennamen über getColumnName()
    • Platform-Erkennung aus der echten Server-Version
    • Fehler bei einem Treiber ohne DBAL-Gegenstück
  • Unit-Tests für Result (inkl. getColumnName()), Statement (Routing, Parameterprüfung) und den Adapter (Version wird einmal gelesen, Quoting inkl. char()-Ausdrücken, lastInsertId).
  • Lokal grün: SQLite, PostgreSQL 14, MariaDB 10.6, MySQL 8.0 (142 Tests). PHPStan, Pint und Type Coverage (100 %) ebenfalls grün.
  • Gegengeprüft in artemeon/core-ng (dev/11.x): composer ohne Konflikte; volle Unit-Suite mit denselben Fehlschlägen wie ohne PR, alle umgebungsbedingt; eigener Funktionstest grün auf SQLite und MySQL 8.0 (JOIN/IN, LIMIT/OFFSET, Lesen von ORM-Daten, gemeinsame Transaktion, Query-Cache).

🤖 Generated with Claude Code — Beschreibung von Claude

romankonz and others added 5 commits June 23, 2026 22:50
…eryBuilder()

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 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
@romankonz
romankonz requested review from chriskapp, marcreichel and sidler and removed request for chriskapp June 24, 2026 05:06
Comment thread src/Doctrine/Driver/MysqlDriver.php Resolved
Comment thread src/Doctrine/Driver/PostgresDriver.php Resolved
Comment thread src/Doctrine/Driver/SqliteDriver.php Resolved
@marcreichel
marcreichel changed the base branch from 4.0.x to 5.x June 29, 2026 08:15
@tmArtemeon
tmArtemeon self-requested a review November 11, 2026 13:34
romankonz and others added 15 commits November 29, 2026 21:02
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f94bc22 routed writes through Connection::executeStatement(), which passes
no escape flags, so dbsafeParams() HTML-encoded every parameter: 'A & B'
was stored as 'A &amp; 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@romankonz
romankonz marked this pull request as ready for review November 30, 2026 06:28

@chriskapp chriskapp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Der PR ist richtig gut, aber können wri dafür einen 6.x Branch aufmachen, und das wir im AGP unter main dann "artemeon/database": "^6.0" verwenden? Damit der Change nicht in das aktuelle 11.x Release geht.

@romankonz

Copy link
Copy Markdown
Contributor Author

Der PR ist richtig gut, aber können wri dafür einen 6.x Branch aufmachen, und das wir im AGP unter main dann "artemeon/database": "^6.0" verwenden? Damit der Change nicht in das aktuelle 11.x Release geht.

Wieso ist das nötig?
https://github.com/artemeon/database/pull/101/changes#diff-fdb82797ac69303b7f9b33a9695e1eaee4ad8dd7ff0e4cdd167a676c5258a514R370 ist die einzige Änderung an bestehendem Code, und es wird nur eine neue Methode hinzugefügt

@chriskapp

Copy link
Copy Markdown
Member

Der PR ist richtig gut, aber können wri dafür einen 6.x Branch aufmachen, und das wir im AGP unter main dann "artemeon/database": "^6.0" verwenden? Damit der Change nicht in das aktuelle 11.x Release geht.

Wieso ist das nötig? https://github.com/artemeon/database/pull/101/changes#diff-fdb82797ac69303b7f9b33a9695e1eaee4ad8dd7ff0e4cdd167a676c5258a514R370 ist die einzige Änderung an bestehendem Code, und es wird nur eine neue Methode hinzugefügt

Hatte auch nochmal geschaut und die Connection wird nur in dem Query-Builder verwendet. hatte erst gedacht, die wird jetzt global verwendet, daher passt für mich auch 5.x

@romankonz romankonz linked an issue Dec 1, 2026 that may be closed by this pull request
@romankonz
romankonz enabled auto-merge (squash) December 1, 2026 07:38
@romankonz
romankonz merged commit ca009a3 into 5.x Dec 1, 2026
18 checks passed
@romankonz
romankonz deleted the feat/doctrine-query-builder branch December 1, 2026 09:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

QueryBuilder (Doctrine DBAL) über die Artemeon-Connection

3 participants