lphp

The database

This page is about talking to a SQL database directly: connecting, running statements, transactions, the query builder, creating tables, and migrations.

The layer above this one — repositories, models and queries — is in Repositories and queries, and Storing data walks through building one from nothing. Nothing on this page needs a model. A Connection is for a report, a migration or a one-off script as much as for a repository, and an architecture test keeps it that way.

Configuring a connection

One connection needs no file at all, which is what a container image wants:

Variable Is
DB_DSN the PDO DSN, e.g. mysql:host=localhost;dbname=erp;charset=utf8mb4
DB_USERNAME, DB_PASSWORD credentials, if the driver needs them
DB_CONNECTION what to call it, and which one is the default (default: default)

More than one connection, or anything with options, goes in config/database.php — where the environment is still reachable, because a config file may call Env itself:

// config/database.php
return [
    'default' => 'main',
    'connections' => [
        'main' => [
            'dsn' => Env::string('DB_DSN', 'mysql:host=db;dbname=erp'),
            'username' => Env::string('DB_USERNAME'),
            'password' => Env::string('DB_PASSWORD'),
        ],
        'reports' => ['dsn' => 'pgsql:host=replica;dbname=warehouse', 'username' => 'reader'],
        'ledger' => [
            'driver' => 'mysql',
            'host' => 'ledger-db',
            'port' => 3306,
            'database' => 'ledger',
            'charset' => 'utf8mb4',
            'username' => 'ledger',
            'password' => Env::string('LEDGER_PASSWORD'),
        ],
    ],
];

A connection gives either a dsn or its parts — driver, host, port, database, charset — which are assembled for mysql, pgsql, sqlite (where database is the file, or :memory:) and sqlsrv. charset is written for MySQL only; PostgreSQL takes the database’s encoding, and SQL Server’s is a PDO attribute. A dsn wins when both are given, and any other driver needs one.

A part containing ;, or a host containing ,, is refused rather than escaped: no driver documents an escape, and either would start a DSN part the configuration never set.

With nothing configured the application boots and opens nothing, and the shared module’s DataSource factory falls back to the in-memory source.

Several databases

Heavy applications rarely have one database — a reporting replica, a legacy system being migrated from, a separate ledger — so each is a name:

$connections->connection('reports')->select('SELECT ...', [$id]);
$connections->connection();                        // the default one

Connecting is lazy. Building a Connection opens nothing; the PDO handle is created on first use. A request that never reads the database never opens a socket, which is what makes it reasonable to declare every database the application might touch.

Running a statement

$connection->select('SELECT * FROM invoices WHERE customer_id = ?', [$id]);
$connection->selectOne(...);  $connection->scalar(...);  $connection->cursor(...);
$connection->execute(...);    $connection->insert(...);
Method Returns
select every row, as arrays
selectOne the first row, or null
scalar the first column of the first row
cursor a generator, one row at a time
execute the number of rows affected
insert the generated key, where the database gives one

Every method takes the SQL and a separate list of values. A value never becomes part of the statement text. Prepared statements are real rather than emulated (ATTR_EMULATE_PREPARES => false), which matters twice: emulation interpolates values into the statement, and it hands every column back as a string.

A failing statement reports the SQL and the number of bound values, never the values themselves. A bound value is the one thing in a query likely to be a password.

How PHP values are bound

PHP value Bound as
int, bool, null, string their own PDO types
float the shortest decimal that reads back as the same float — PDO alone would write fourteen digits and store 0.1 + 0.2 as 0.3. Infinity and NaN are refused
DateTimeInterface Y-m-d H:i:s, with .u when there are microseconds. The wall-clock time as given: the time zone is not converted, because which zone a column holds is your decision
a stream resource a large object, for binary data — on SQL Server with the driver’s binary encoding, which a VARBINARY column needs
Stringable its string

Anything else is refused, named by parameter position and type, never by value.

Transactions

A transaction is the application’s boundary, not each repository method’s:

$connection->transaction(function (Connection $db) use ($invoice): void {
    $invoices->store($invoice);
    $entries->post($invoice);
    $payments->record($invoice);
});

The callback either finishes, and everything is committed, or throws, and nothing is written.

Nesting means what it looks like. PDO has no nested transactions — a second beginTransaction() throws or is ignored, and the first commit() writes everything. So begin() uses savepoints beyond the first level: SAVEPOINT/RELEASE/ROLLBACK TO on MySQL, PostgreSQL and SQLite, and SAVE TRANSACTION/ROLLBACK TRANSACTION on SQL Server, which has no release. Any other driver refuses to nest, with a sentence rather than a syntax error.

One caveat, and it is inherent to nested transactions everywhere. Rolling back to a savepoint undoes the inner work and leaves the outer transaction open. So if the calling code swallows the exception, the outer transaction still commits, with the inner work gone. Catch deliberately or not at all.

When something goes wrong inside the machinery itself:

What happens What you get
The callback throws, and the rollback fails too The callback’s exception. The connection is closed, so the database discards the transaction with the session
A rollback fails at an inner level The connection is closed. The outer levels are lost: every statement and commit is refused until each has rolled back, so an outer callback that swallowed the failure cannot go on writing in autocommit mode
The callback leaves a level open, or finishes one it did not begin Everything since the callback began is rolled back, and the imbalance is reported
disconnect() inside a transaction The connection closes (the work is discarded), then an exception names the connection and the depth. disconnectAll() closes every connection before reporting

Isolation levels and retrying

$connection->transaction($callback, isolation: IsolationLevel::Serializable, retries: 3);

isolation: runs the transaction at ReadUncommitted, ReadCommitted, RepeatableRead or Serializable. Each dialect writes the level where its database needs it:

Database Where the level is set What else
MySQL, MariaDB before BEGIN applies to that transaction only
PostgreSQL first statement inside ReadUncommitted runs as ReadCommitted, which is stricter, never weaker
SQL Server before BEGIN lasts for the session, so it is put back to READ COMMITTED afterwards. If that fails, the session is closed
SQLite nowhere only Serializable exists; every other level is refused

A level a database cannot give is refused before anything runs, and a different level is never quietly substituted: code that asked for READ COMMITTED may be relying on not blocking.

The level and the retries belong to the outermost transaction. A nested transaction() given either is refused.

retries: runs the whole transaction again, from a clean state, when it fails with a deadlock or a serialization failure — SQLSTATE 40001 (which MySQL and SQL Server also use for their deadlocks), 40P01 on PostgreSQL, or MySQL’s error 1213. Nothing else is retried: not a constraint violation, not a lock-wait timeout, not a lost connection, and not an exception of your own.

Between attempts there is a short, growing, jittered pause: 10 ms, 20 ms, 40 ms and so on, up to 200 ms. The last failure is thrown once the retries are spent. $connection->isRetryable($e) makes the same judgement for code that manages its own retries.

With retries, the callback may run more than once. Its database work is rolled back between attempts, but nothing else is. An email sent, a card charged, a file written or a job queued inside the callback happens once per attempt. Do those after transaction() returns.

Watching statements and transactions

Inside an application, each connection fires these hooks:

Hook Arguments When
database.query.failed DatabaseException $failure, Connection $connection the database refused a statement
database.transaction.committed Connection $connection the outermost transaction committed
database.transaction.rolled_back Connection $connection, ?Throwable $cause the outermost transaction was rolled back: $cause is the failure that ended a transaction(), or null after a rollBack()
database.transaction.retrying Throwable $failure, int $attempt, Connection $connection transaction(retries:) is about to try again; $attempt is 2 for the first retry
$hooks->add('database.transaction.committed', function (Connection $connection) use ($outbox): void {
    $outbox->flush();
});

Savepoints are not announced: releasing one commits nothing, and rolling one back leaves the transaction open.

Each hook fires once what it reports has already happened, so a listener cannot change it:

The failure carries the SQL and how many values were bound, never the values.

The database layer itself knows nothing about hooks. Outside an application, listen() on a connection or on the ConnectionManager receives the same events, without the database. prefix:

$connections->listen(function (string $event, mixed ...$arguments): void { /* ... */ });

observe() gets a callback after every statement, including a failed one. It receives:

  1. the SQL;
  2. the nanoseconds it took;
  3. the connection’s name;
  4. how many values were bound;
  5. how many rows the statement returned or changed, or null when that was not known at the time (a failure, a cursor, or run()).

An observer may declare fewer parameters and ignore the rest. The bound values are never passed. The profiler and the slow-query warning are built on it.

The query builder

For reads that are SQL and should look like it, table() gives a builder:

$invoices = $connection->table('invoices AS i')
    ->select('i.id', 'i.total', 'i.customer_id AS customer')
    ->whereNull('i.cancelled_at')
    ->where(fn (QueryBuilder $q) => $q->where('i.status', 'open')->orWhere('i.total', '>', 1000))
    ->whereIn('i.region', $regions)
    ->orderByDesc('i.id')
    ->limit(50)
    ->get();
Building Running
select(...) — names, t.*, x AS y, or a RawExpression get() — every row
where / orWhere — (col, value), (col, op, value), a closure group, or a RawExpression first() — one row or null
whereNull / whereNotNull cursor() — a generator, one row at a time
whereIn / whereNotIn — an empty list matches nothing / excludes nothing count() — ignores order, limit and offset
whereBetween / whereNotBetween — inclusive exists() — reads at most one row
orderBy(col, 'asc'\|'desc'), orderByDesc, limit, offset compile() — the SQL and bindings, without running them

Five things to know:

The builder is SQL-only. Data\Query is a different thing: AND only, no joins, the same on every kind of storage. A repository method uses the builder when a read is relational, the same way it would use raw SQL.

Joins, grouping and aggregates

$revenue = $db->table('customers AS c')
    ->select('c.region', Aggregate::count(as: 'orders'), Aggregate::sum('o.total', as: 'revenue'))
    ->join('orders AS o', 'o.customer_id', '=', 'c.id')
    ->leftJoin('refunds AS r', fn (JoinClause $j) => $j->on('r.order_id', '=', 'o.id')->where('r.status', 'settled'))
    ->whereNull('r.id')
    ->groupBy('c.region')
    ->having(Aggregate::sum('o.total'), '>', 10000)
    ->orderByDesc('revenue')
    ->get();

$db->table('orders')->where('status', 'paid')->sum('total');   // also avg(), min(), max()

Writing through the builder

$id = $db->table('invoices')->insert(['customer_id' => 7, 'total' => 120.5], 'id');
$db->table('lines')->insertMany($lines);                        // how many were written
$db->table('stock')->where('sku', $sku)->update(['quantity' => new RawExpression('quantity - ?', [2])]);
$db->table('sessions')->where('expires_at', '<', $now)->delete();
$db->table('stock')->upsert($rows, uniqueBy: ['sku'], update: ['quantity']);

Locking rows for a read-modify-write:

$db->transaction(function (Connection $db) use ($sku): void {
    $row = $db->table('stock')->where('sku', $sku)->lockForUpdate()->first();
    $db->table('stock')->where('sku', $sku)->update(['quantity' => $row['quantity'] - 1]);
});

lockForUpdate() holds the rows it reads until the transaction ends, so no other transaction changes or locks them in between. It is FOR UPDATE on MySQL and PostgreSQL and WITH (UPDLOCK, ROWLOCK) on SQL Server. SQLite writes nothing: a write there locks the whole database, one writer at a time.

Outside a transaction the lock would end with its own statement, so running one is refused. A grouped query is refused too, since each result row stands for many. The database session store is built on it.

Creating tables

A table is described once, with chained methods, and each connection’s grammar writes it in its own dialect:

$connection->tables()->create('invoices', static function (Table $table): void {
    $table->id();
    $table->bigInteger('customer_id')->index();
    $table->string('number', 30)->unique();
    $table->decimal('total', 12, 2)->default('0.00');
    $table->boolean('paid')->default(false);
    $table->dateTime('issued_at')->nullable();
    $table->timestamps();
    $table->foreign('customer_id')->references('customers')->onDelete('cascade');
});

$connection->tables()->drop('invoices');
Builder MySQL PostgreSQL SQLite SQL Server
id() BIGINT AUTO_INCREMENT PRIMARY KEY BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY INTEGER PRIMARY KEY AUTOINCREMENT BIGINT IDENTITY(1,1) PRIMARY KEY
integer / bigInteger INT / BIGINT INTEGER / BIGINT INTEGER INT / BIGINT
decimal(p, s) DECIMAL(p,s) NUMERIC(p,s) NUMERIC DECIMAL(p,s)
string(n), 255 by default VARCHAR(n) VARCHAR(n) TEXT NVARCHAR(n)
text LONGTEXT TEXT TEXT NVARCHAR(MAX)
boolean TINYINT(1) BOOLEAN INTEGER BIT
date / dateTime DATE / DATETIME(6) DATE / TIMESTAMP(6) TEXT DATE / DATETIME2(6)
binary LONGBLOB BYTEA BLOB VARBINARY(MAX)

Every column type, default, key and index above is created, filled, read back and dropped on each database by DialectConformanceTest.

Changing tables

alter() takes a description of the change only. The column methods add columns, and five more take away:

$connection->tables()->alter('invoices', static function (Table $table): void {
    $table->string('reference', 40)->nullable()->unique();
    $table->integer('copies')->default(1);
    $table->renameColumn('number', 'code');
    $table->dropIndex('customer_id');      // or dropUnique(), over the same columns
    $table->dropForeign('account_id');
    $table->dropColumn('notes', 'legacy_total');
});

Each of these changes is run against a table that already holds rows, on each database, by DialectConformanceTest.

Migrations and seeders

A migration is one change to the structure of the database. A seeder is rows a module needs to start with.

A module keeps migrations in Database/Migrations/ and seeders in Database/Seeders/, one file each. Nothing registers them: the folder is enough. A disabled module’s are skipped.

// modules/Billing/Database/Migrations/2026_09_19_120000_create_invoices.php
return new class implements Reversible {
    public function up(Tables $tables): void
    {
        $tables->create('invoices', static function (Table $table): void {
            $table->id();
            $table->bigInteger('customer_id')->index();
            $table->decimal('total', 12, 2)->default('0.00');
            $table->foreign('customer_id')->references('customers');
        });
    }

    public function down(Tables $tables): void
    {
        $tables->drop('invoices');
    }
};

A file returns a Migration, which has up(Tables), or a Reversible, which adds down(Tables). Its name is YYYY_MM_DD_HHMMSS_what_it_does.php, in lower case, and its id is <module id>:<file name>. There is no make:migration — create the file yourself. The one exception is a module’s first: php laika module:make Billing --with=database,seeder writes a starter migration and seeder.

Command Does
migrate Runs every pending migration, as one batch. --pretend prints the SQL each would send to this database and runs nothing; hand-written SQL is marked [raw].
migrate:status Lists every migration, whether it ran and in which batch. A recorded migration whose file has gone is called out.
migrate:rollback Undoes the last batch, or --batches=N, newest first. Needs --force in production.
db:seed Runs every seeder, or one module’s with --module=Billing. Needs --force in production.

All four take --connection=<name>. Migrations are a deployment step: give that connection an account allowed to create tables, which the application’s own account should not be. Nothing creates a table during a request.

What to know about a run:

Seeders

A seeder returns a Seeder, whose run(Connection $db) writes through the query builder:

// modules/Billing/Database/Seeders/currencies.php
return new class implements Seeder {
    public function run(Connection $db): void
    {
        if (!$db->table('currencies')->where('code', 'BDT')->exists()) {
            $db->table('currencies')->insert(['code' => 'BDT', 'name' => 'Taka']);
        }
    }
};

In a test, $this->migrate($app) runs every module’s migrations on the booted application, so the test has the same tables production has.

Running the data layer on it

SqlSource implements DataSource, so every repository, query, read model, relation and page from Repositories and queries runs against a real database unchanged. Switching is one factory in a module:

$services->singleton(DataSource::class, static function (Container $c): DataSource {
    $connections = $c->get(ConnectionManager::class);

    return $connections->isConfigured()
        ? new SqlSource($connections->connection())
        : new ArraySource();
});

That is the only place in the application that knows which kind of storage it has. The framework does not bind DataSource itself — which source an application reads through is its decision, not the framework’s, and that is architecture-tested too.

SqlSource::fetch() returns a cursor, so Query::stream() and Query::chunk() genuinely hold one row at a time rather than a whole table.

Testing against a database

The database tests are real integration tests against SQLite in memory — real PDO, real prepared statements, real savepoints — costing about a millisecond each and needing nothing installed.

tests/Feature/SqlSourceTest.php runs the same repository against ArraySource and SqlSource and asserts the answers are identical, which is the DataSource claim stated as a test rather than as a paragraph.

SQLite agreeing with a dialect proves nothing about the other databases, so DialectConformanceTest runs each dialect on its own database too: MySQL, PostgreSQL or SQL Server, whichever DB_TEST_*_DSN names (see Development). CI runs all three. MySQL (as MariaDB) and PostgreSQL are also run where the framework is developed; SQL Server is not, so CI is the only place its dialect meets a real server.

If it doesn’t work

What you see Why Fix
“no such table” The migrations have not run on this database php laika migrate; migrate:status shows what is pending
Everything saved is gone next request No database is configured, so the memory source is in use Set DB_DSN
A rename is refused on MySQL or MariaDB RENAME COLUMN needs MySQL 8.0 or MariaDB 10.5.2 Upgrade, or write the CHANGE with $tables->raw(…, 'mysql')
update() or delete() throws It has no where(), and will not rewrite a table by accident Add a condition, or call updateAll() / deleteAll()
where('col', null) throws = NULL is never true in SQL Use whereNull()
A sort column from a request throws Names are checked against the identifier pattern Map request input onto names you chose
A migration run waits, then stops Another run holds the lock Wait for the other deployment to finish
upsert() is refused SQL Server has no equivalent statement Write the MERGE yourself, or insert and update
A callback ran twice retries: retried a deadlock Move emails, charges and queued jobs out of the callback

Why it works this way

The injection boundary is one file wide

No database accepts a parameter where a column name goes, so table and column names are the one part of a statement built by interpolation. All of that lives in Grammar and its dialects, and every part of a name passes one check first:

/^[A-Za-z_][A-Za-z0-9_]*$/

A name is split on its dots (sales.orders is two parts; a table may have two, a column three) and on AS for an alias, and each part is checked and quoted on its own. Anything else — a quote, a space, a comment, a semicolon, a function call, an empty part — is refused with an exception naming it.

Names reach the Grammar from repository declarations rather than from requests. The check is what keeps that true on the day somebody passes a sort column straight from a query string. An architecture test asserts that no other file in engine/Database/ builds SQL at all.

Limits and offsets are written in rather than bound: they are typed int in PHP by the time they arrive, so there is nothing to inject, and binding them is the one thing several drivers get wrong.

Dialects

Each connection speaks its database’s dialect, picked from the driver in its DSN by Grammar::for():

Driver Dialect Differs in
mysql MySqlGrammar backtick quoting; 65535 placeholders per statement
pgsql PostgresGrammar 65535 placeholders. Placeholders stay ?, which PDO rewrites into PostgreSQL’s numbered form
sqlite SqliteGrammar nothing: standard quoting and paging, 999 placeholders
sqlsrv SqlServerGrammar [bracket] quoting; OFFSET … FETCH paging, with ORDER BY (SELECT NULL) when a query has no order of its own; SAVE TRANSACTION savepoints; 2000 placeholders
anything else Grammar standard SQL, and no capabilities claimed

What a database can do at all is asked of the connection:

if ($connection->supports(Capability::Savepoints)) { ... }
Capability MySQL PostgreSQL SQLite SQL Server
Savepoints — transactions nest yes yes yes yes
Returning — an INSERT hands back its generated key no yes no¹ yes (OUTPUT)
Upsert — insert or update by a unique key yes yes yes no
RightJoin — RIGHT JOIN yes yes no² yes
TransactionalDdl — creating and dropping tables can be rolled back no yes yes yes

¹ SQLite has had RETURNING since 3.35, but some distributions still ship older builds. SQLite’s last-insert id is correct per statement anyway. ² From 3.39, which is newer than some distributions ship.

A capability is added with the feature that needs it, never ahead of one. A test holds this table for every dialect, so a new capability cannot be added without deciding it for each database.