Drivers

The Doctrine Driver

Using the Doctrine driver interacting with MySQL, PostgreSQL, and other databases.

Introduction

The Doctrine driver provides a powerful and flexible way to interact with various databases using the Doctrine ORM (or DBAL).

It's based on the latest version 4.x of Doctrine and supports a wide range of database systems, including MySQL, PostgreSQL, SQLite, and more.

You can use it to configure multiple DBAL and Entity Manager connections in your API.

Installation

doctrine/orm 4 is not yet a stable Doctrine release

The driver uses doctrine/orm 4, which Doctrine has not released as stable: Packagist has the 4.0.x-dev branch, and the newest stable release is 3.7. A project that accepts only stable packages, as the starter does, must allow that one package to be a development version. The commands below do so with an inline stability flag, "doctrine/orm": "^4@dev", so every other package in the project stays stable. When Doctrine releases ORM 4.0.0, change the constraint to "doctrine/orm": "^4": Composer ranks 4.0.x-dev above 4.0.0, so the flag would keep the development branch.

With Kipchak CLI 1.2.1 or later, which the starter includes, one command installs the driver, copies its configuration into config/ and initialises it:

vendor/bin/kipchak add doctrine

From CLI 1.2.3 it writes a working SQLite configuration, so that the first migration needs no database server. SQLite is the starting default: use MySQL or PostgreSQL in production, as Configuration shows. An existing config/kipchak.doctrine.php is never overwritten.

Without the CLI, require the driver and allow the unreleased ORM:

composer require kipchak/driver-doctrine "doctrine/orm:^4@dev"

Initialise the Driver

Add the following line to your drivers/drivers.php file:

\Kipchak\Driver\Doctrine\Doctrine::initialise($container);

Handling Doctrine's Singleton

In FrankenPHP worker mode, each worker keeps one EntityManager and one database connection for all the requests it serves. Two things follow: entities loaded by one request stay in the EntityManager's identity map for the next, and a connection the database has closed (after a restart, a failover or an idle timeout) fails every later request on that worker.

The starter project's html/index.php has commented lines for both. For each entity manager your API uses, uncomment them in the request handler, so that at the start of every request the connection is checked and replaced if it was lost, and the EntityManager is cleared:

use Doctrine\DBAL\Exception\ConnectionException;
use Doctrine\DBAL\Exception\ConnectionLost;
use Kipchak\Driver\Doctrine\Doctrine;

// MySQL only: a short read timeout for web requests (see below).
ini_set('mysqlnd.net_read_timeout', '5');

// Paths that must answer without the database. Keep the list short.
const NO_DATABASE_PATHS = ['/livez', '/status'];

$handler = static function () use ($app) {
    $em = Doctrine::get('entitymanager.primary');

    $path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/';
    if (!in_array($path, NO_DATABASE_PATHS, true)) {
        $conn = $em->getConnection();
        try {
            $conn->executeQuery('SELECT 1')->fetchOne();
        } catch (ConnectionLost | ConnectionException) {
            $conn->close(); // DBAL is lazy; the next query opens a fresh connection.
        }
    }

    $em->clear();

    // ... the rest of the handler, which calls $app->run()
};

From starter 4.8, the check is skipped for the paths in NO_DATABASE_PATHS. A liveness probe that waited on a database that is down would get the service restarted for an outage a restart cannot fix.

A read timeout for MySQL

PHP's MySQL client (mysqlnd) waits up to 86,400 seconds for a database that has stopped answering, and every request on the worker waits with it. PDO has no read-timeout attribute for MySQL: \PDO::ATTR_TIMEOUT, which you can set in the connection's driverOptions, is a connect timeout only. Set mysqlnd.net_read_timeout in html/index.php, the web worker, before the first connection opens. A route that needs the database then fails after that time instead of hanging. Long-running commands, such as migrations:up, do not load html/index.php and keep the default.

Configuration

The configuration in kipchak.doctrine.php can be used to configure multiple DBAL and ORM connections. Enable the connections you use; this example is a server database, for production:

return [
    'dbal' => [
        'enabled' => false,
        'connections' => [
            'primary' => [
                'dbname' => 'mydb',
                'user' => env('DB_USER', 'api'),
                'password' => env('DB_PASSWORD', 'api'),
                'host' => env('DB_HOST', 'mysql'),
                'driver' => 'pdo_mysql',
            ]
        ]
    ],
    'orm' => [
        'enabled' => false,
        'entity_managers' => [
            'primary' => [
                'dev_mode' => filter_var(env('DEBUG', 'false'), FILTER_VALIDATE_BOOLEAN),
                'metadata_dirs' => [
                    realpath(__DIR__ . '/../api/Entities/Doctrine/Primary')
                ],
                'connection' => 'primary',
            ],
        ]
    ]
];

Please see the configuration file in the examples repository at https://github.com/kipchak-dev/examples/blob/master/config/kipchak.doctrine.php for full configuration details.

The metadata cache

Outside development mode, an entity manager caches its metadata in the store its configuration names. 'store' => 'file' needs nothing more. 'store' => 'memcached' needs the Memcached driver, which from driver 1.55 is optional: run composer require kipchak/driver-memcached and initialise it. Without it, the API fails at boot with a message that names the package. See the upgrade note.

SQLite

A DBAL connection to SQLite names the file in path, or uses 'memory' => true for an in-memory database (since 1.53):

'connections' => [
    'local' => [
        'driver' => 'pdo_sqlite',
        'path' => env('SQLITE_PATH', '/data/app.db'),
    ],
],

A server connection uses host, port, dbname, user and password as above; unix_socket, charset and driverOptions are passed on when set.

Usage

DBAL Usage

use Kipchak\Driver\Doctrine\Doctrine;

$dbal = Doctrine::get('dbal.primary'); //See config file below for DBAL definition

// Query builder
$queryBuilder = $dbal->createQueryBuilder();
$users = $queryBuilder
    ->select('*')
    ->from('users')
    ->where('status = ?')
    ->setParameter(0, 'active')
    ->executeQuery()
    ->fetchAllAssociative();

// Direct queries
$stmt = $dbal->executeQuery('SELECT * FROM users WHERE id = ?', [123]);
$user = $stmt->fetchAssociative();

DBAL Middleware

From 1.51, DBAL driver middleware registered with Library\Middleware::push() applies to every connection the driver creates, its DBAL connections and those of its entity managers. It is read when each connection is created, on first use, so it can be registered after the driver is initialised. The OpenTelemetry driver uses it to trace queries.

use Doctrine\DBAL\Driver\Middleware as DriverMiddleware;
use Kipchak\Driver\Doctrine\Library\Middleware;

// A DBAL middleware, or a callable that receives the connection's name and returns one.
Middleware::push('query-log', fn (string $connection): DriverMiddleware => new QueryLog($connection));

ORM Usage

use Kipchak\Driver\Doctrine\Doctrine;

$em = Doctrine::get('entitymanager.primary'); // See config file below for ORM EM definition

// Find entity
$user = $em->find(User::class, 123);

// Create entity
$newUser = new User();
$newUser->setName('John Doe');
$newUser->setEmail('john@example.com');
$em->persist($newUser);
$em->flush();

// Query
$users = $em->getRepository(User::class)
    ->findBy(['status' => 'active']);

ORM 4 changes some APIs from ORM 3. QueryBuilder::orderBy() takes PHP 8.6's SortDirection enum, polyfilled by symfony/polyfill-php86, instead of the string 'ASC' or 'DESC':

$latest = $em->createQueryBuilder()->select('u')->from(User::class, 'u')
    ->orderBy('u.id', \SortDirection::Descending)
    ->getQuery()->getResult();

Learn more about Doctrine DBAL and ORM at https://www.doctrine-project.org/projects.html.

Doctrine CLI

The Kipchak Doctrine Driver ships with a Doctrine cli which is available at vendor/bin/doctrine.

Because the driver supports multiple connections, to use it with a specific Entity Manager, pass the --em flag with then name.

Examples:

php vendor/bin/doctrine --em=primary orm:info
php vendor/bin/doctrine migrations:up --em=primary  --file=migrations/database/filename.sql

Migrations

The Doctrine driver includes a custom migration system that uses plain SQL files with support for both "up" and "down" migrations.

Migration File Location

By default, migrations are stored in:

<your-project-root>/migrations/database

This path is resolved from your project root (not from the vendor directory).

Migration File Format

Migration files should be SQL files (.sql extension) with the following structure:

-- Up migration statements go here
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE
);

-- Down
-- Rollback statements go here
DROP TABLE users;

Key points:

  • Everything before -- Down is considered the "up" migration
  • Everything after -- Down is considered the "down" migration (rollback)
  • The -- Down comment acts as a separator between up and down migrations

How Statements Are Split

Statements are sent to the database one at a time. From driver 1.58, a ; ends a statement only when it is outside:

  • comments: -- (in MySQL, followed by a space), # (MySQL only) and /* ... */;
  • quoted strings and identifiers, such as 'a;b' or `odd;name`;
  • PostgreSQL dollar quotes, such as $$ ... $$;
  • the BEGIN ... END body of a CREATE TRIGGER, PROCEDURE, FUNCTION or EVENT.

Each statement reaches the database exactly as written, comments included, and a piece made of comments alone is not sent. Before 1.58 every ; ended a statement, so text after a ; in a comment ran as SQL: a line such as -- note; DROP TABLE keepme dropped the table. A file without a ; in one of those places splits exactly as before. If the driver cannot read a file cleanly, for example because a quote is never closed, it splits that file at every ; as before and prints a warning.

Migration Tracking

The system automatically creates a schema_migrations table to track which migrations have been applied:

Migrations work on MySQL, PostgreSQL and, from driver 1.54, SQLite. Earlier releases recorded each migration with NOW(), which SQLite does not have, so migrations:up failed there.

CREATE TABLE schema_migrations (
    filename VARCHAR(255) PRIMARY KEY,
    applied_at DATETIME NOT NULL
)

On PostgreSQL the column is TIMESTAMP. Before driver 1.57 it was DATETIME, a type PostgreSQL does not have, so migrations:up and migrations:down failed on a new PostgreSQL database before doing anything.

Migration Naming Convention

While not strictly enforced, it's recommended to name migration files with a timestamp prefix for proper ordering:

20250101120000_create_users_table.sql
20250102140000_add_status_to_users.sql

Migration files are sorted alphabetically by filename, so timestamp prefixes ensure they run in the correct order.

Running Migrations

Apply Migrations (migrations:up)

Apply all pending migrations:

php vendor/bin/doctrine migrations:up --em=primary

Apply a specific migration file:

php vendor/bin/doctrine migrations:up --em=primary --file=20250101120000_create_users_table.sql

Apply all migrations in a specific directory:

php vendor/bin/doctrine migrations:up --em=primary --file=subdirectory/

How --file works:

  • Can be a single SQL file path (absolute or relative to current working directory)
  • Can be a directory path (runs all .sql files recursively)
  • Can be a file or directory relative to migrations/database
  • If omitted, runs all pending migrations in migrations/database

Migration behavior:

  • Each migration is executed only once
  • Already-applied migrations are automatically skipped
  • Migrations run in alphabetical order by filename
  • On PostgreSQL, SQLite, and SQL Server, migrations run in transactions (automatic rollback on failure)
  • Gracefully handles certain errors like "table already exists" or "duplicate column"

Revert Migrations (migrations:down)

Revert the most recently applied migration:

php vendor/bin/doctrine migrations:down --em=primary

Revert a specific migration:

php vendor/bin/doctrine migrations:down --em=primary --file=20250101120000_create_users_table.sql

How --file works:

  • Can be a single SQL file path (absolute or relative to current working directory)
  • Can be a file relative to migrations/database
  • Directory paths are not supported for migrations:down
  • If omitted, reverts the last applied migration

Rollback behavior:

  • Executes the "down" section of the migration file (after -- Down comment)
  • Removes the entry from schema_migrations table
  • Runs in a transaction on supported platforms
  • Fails if no "down" section is found in the migration file

The Migration Lock

From driver 1.57, migrations:up holds a lock for its whole run, so two runs against one database, such as two pods starting at once, cannot both find a migration unapplied and both execute it. The lock is taken before schema_migrations is created or read, and released when the run ends, whether it succeeded, failed or threw. The second run waits, then finds the migrations applied and skips them. The log says so:

Taking the migration lock kipchak.migrations.shop.
Waiting up to 300 s for the migration lock kipchak.migrations.shop, which another run holds.
Obtained the migration lock kipchak.migrations.shop after 2.0 s.
Skipping 2026_01_01_000000_shelves.sql (already applied)
Released the migration lock kipchak.migrations.shop.
PlatformLock
MySQL, MariaDBGET_LOCK / RELEASE_LOCK, named kipchak.migrations.<database>
PostgreSQLpg_advisory_lock / pg_advisory_unlock, on a bigint key derived from kipchak.migrations.<database>
SQLiteNone. SQLite allows one writer at a time and runs each migration in a transaction.
SQL Server and othersNone. Do not start two runs at once.

migrations:down takes the same lock, with the same timeout and messages.

  • The name includes the database name, so runs against two databases on one server do not wait for each other.
  • The lock belongs to the command's connection: if the process dies, the database releases it when the connection closes.
  • The lock is a session lock, so it does not hold through a transaction-pooling proxy (PgBouncer in transaction mode, ProxySQL multiplexing). Run migrations on a direct or session-pooled connection.
  • If the lock is not obtained within migrations.lock_timeout seconds, the command prints Did not obtain the migration lock ... No migration was run. and exits with an error, having created nothing.

Settings

Both settings are optional, in a migrations block of kipchak.doctrine.php:

return [
    // 'dbal' => [...], 'orm' => [...],
    'migrations' => [
        'lock_timeout' => 300, // seconds to wait for the migration lock
        'strict' => false,     // true: an "already exists" error fails the migration
    ],
];
SettingDefaultMeaning
migrations.lock_timeout300Seconds to wait for the migration lock. 0 tries once without waiting.
migrations.strictfalseWhether an "already exists" error fails the migration (see Error Handling).

Transaction Support

The migration system automatically uses transactions when the database platform supports DDL transactions:

  • PostgreSQL: ✅ Supports DDL transactions
  • SQLite: ✅ Supports DDL transactions
  • SQL Server: ✅ Supports DDL transactions
  • MySQL: ❌ Does not support DDL transactions (runs statements individually)

When transactions are enabled:

  • All migration statements are wrapped in a single transaction
  • If any statement fails, the entire migration is rolled back
  • Transaction control statements (BEGIN, COMMIT, ROLLBACK) in migration files are automatically skipped

Error Handling

The migration system includes graceful error handling for common scenarios:

Graceful failures (logged as warnings but don't stop execution):

  • "Duplicate column name"
  • "Table already exists"
  • "Duplicate key name"
  • "Unknown column" (on down migrations)
  • Other "already exists" errors

Hard failures (stop execution and rollback):

  • Syntax errors
  • Permission errors
  • Other database errors not in the graceful list

When a graceful failure skips a statement, the file is still recorded as applied, and from driver 1.57 the warning names the file and the statement. "Already exists" is matched by name only, so a rerun that finds a column or index of the same name with a different definition still records the statement as applied.

With migrations.strict on (from 1.57), these errors fail the migration like any other: the file is rolled back where the platform supports transactional schema changes, it is not recorded, and the command exits with an error.

Two lines are kept stable for tools that read the output. Match these rather than the warning, whose wording may change:

kipchak-migrations: skipped-existing 2026_01_02_000000_books.sql
Failed 2026_01_02_000000_books.sql: <the database error>

The first follows each skipped statement (from 1.58); the second is printed when a migration fails.

On PostgreSQL the skip does not help: the failed statement aborts the file's transaction, so the next statement fails and the file is rolled back, with strict mode on or off.

Best Practices

  1. Always include down migrations for reversibility
  2. Use timestamp prefixes in filenames for proper ordering
  3. Test migrations on a development database before production
  4. Keep migrations small and focused on a single change
  5. Don't modify already-applied migration files (create new ones instead)

Git Repository

The source code for this driver is available on 1x.ax at https://1x.ax/mamluk/kipchak/drivers/doctrine.

Previous
Filecache