Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
0f22b77
feat: Add Doctrine DBAL QueryBuilder support via Connection::createQu…
romankonz Jun 23, 2026
889386e
docs: Add complex AND/OR/IN example to query_builder_sqlite demo
romankonz Jun 23, 2026
c23ae86
docs: Add JOIN example and reviews table to query_builder_sqlite demo
romankonz Jun 23, 2026
5b271f6
fix: Resolve PHPStan errors in Doctrine adapter
romankonz Jun 23, 2026
4b99ecd
fix: Add doctrine/dbal as a runtime dependency and fix CI failures
romankonz Jun 23, 2026
bfb0411
Merge remote-tracking branch 'origin/5.x' into feat/doctrine-query-bu…
romankonz Nov 29, 2026
2497977
refactor: Move DBAL adapter into Doctrine\Driver and mark it internal
romankonz Nov 29, 2026
19bc736
feat: Read the real server version for DBAL platform detection
romankonz Nov 29, 2026
b985fbe
fix: Fail loudly when no DBAL driver matches the connection
romankonz Nov 29, 2026
96ad4f3
fix: Quote string literals per platform
romankonz Nov 29, 2026
f94bc22
refactor: Run DBAL statements through Connection::executeStatement()
romankonz Nov 29, 2026
8daa3bf
test: Cover the DBAL QueryBuilder adapter on every driver
romankonz Nov 29, 2026
258b0e4
docs: Tidy the query builder example
romankonz Nov 29, 2026
94b356a
docs: Document createQueryBuilder() in README and CHANGELOG
romankonz Nov 29, 2026
d130303
fix: Keep QueryBuilder writes free of HTML encoding
romankonz Nov 29, 2026
221a543
fix: Keep quoted literals intact through the Artemeon query rewrites
romankonz Nov 29, 2026
0d44784
fix: Bind booleans as integers regardless of the declared type
romankonz Nov 29, 2026
d35f9cb
feat: Support Result::getColumnName() in the DBAL adapter
romankonz Nov 29, 2026
1423862
test: Pin down query routing for UNION and CTEs
romankonz Nov 29, 2026
eae11da
docs: Explain how to match HTML-encoded data with the query builder
romankonz Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,38 @@ 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.

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).
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
],
"require": {
"php": ">=8.4",
"doctrine/dbal": "^4",
"psr/log": "^1|^2|^3",
"phpmyadmin/sql-parser": "^5.10",
"symfony/process": "^5.0|^6.0|^7.0|^8.0",
Expand Down
192 changes: 192 additions & 0 deletions examples/query_builder_sqlite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
<?php

/*
* This file is part of the Artemeon Core - Web Application Framework.
*
* (c) Artemeon <www.artemeon.de>
*
* 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
*
* 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';

$params = new ConnectionParameters(
host: 'localhost',
username: '',
password: '',
database: ':memory:',
port: null,
driver: 'sqlite3',
);

$connection = new Connection($params, new DriverFactory());

// --- Schema + seed -----------------------------------------------------------

$table = 'demo_books';
$tableReviews = 'demo_reviews';

$connection->createTable(
$table,
[
'id' => [DataType::CHAR20, false],
'title' => [DataType::CHAR100, false],
'author' => [DataType::CHAR100, false],
'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-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";
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);

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
->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', ':ids'),
),
)
->setParameter('cutoff_low', 2000)
->setParameter('cutoff_high', 2010)
->setParameter('ids', ['b-1', 'b-3', 'b-5'], ArrayParameterType::STRING)
->orderBy('year', 'ASC')
->executeQuery()
->fetchAllAssociative();

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']);
}
37 changes: 37 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@

namespace Artemeon\Database;

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;
Expand All @@ -26,6 +32,10 @@
use Artemeon\Database\Schema\TableIndex;
use BackedEnum;
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;
use Override;
Expand Down Expand Up @@ -73,6 +83,8 @@ class Connection implements ConnectionInterface
*/
private int $numberCache = 0;

private ?DbalConnection $dbalConnection = null;

/**
* Instance of the db-driver defined in the configs.
*/
Expand Down Expand Up @@ -350,6 +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
{
$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
*/
Expand Down
Loading
Loading