Turns the remaining rasuvaeff/context
budget into a statement timeout the database server enforces itself — MySQL,
MariaDB and PostgreSQL over PDO. A query stops on the server when the budget
runs out instead of running on after the caller gave up.
Using an AI coding assistant? llms.txt contains a compact API reference you can share with the model. Projects using the llm/skills Composer plugin also get this package's agent skill synced into
.agents/skills/automatically on install.
- PHP 8.3+,
ext-pdo rasuvaeff/context^0.3ext-pdo_mysqlfor MySQL/MariaDB,ext-pdo_pgsqlfor PostgreSQL
composer require rasuvaeff/context-dbPDO has no per-query timeout of its own (only a connect timeout), so this package uses what each server offers — and each offers something different:
| Server | Per statement (apply()) |
Per scope (within()) |
Error when it fires |
|---|---|---|---|
| MySQL 5.7.8+ | /*+ MAX_EXECUTION_TIME(ms) */ on the main read-only SELECT |
SET SESSION max_execution_time |
HY000 / 3024 |
| MariaDB 10.1+ | SET STATEMENT max_statement_time=s FOR … on any statement |
SET SESSION max_statement_time |
70100 / 1969 |
| PostgreSQL | — (no per-statement syntax) | SET statement_timeout, SET LOCAL in a transaction |
57014 |
| SQLite and others | unchanged | callback only | — |
- MySQL limits only read-only SELECT.
INSERT … SELECT,UPDATE,DELETEand DDL run without a server-side limit, whatever you set: keep checking the context between them.apply()returns such statements unchanged rather than adding a hint MySQL would silently ignore. - An interrupted MySQL
SLEEP()returns 1 instead of failing. Real work fails with error 3024; do not test the limit withSELECT SLEEP(n). - PostgreSQL behind a transaction-pooling pgbouncer: a session
SETleaks to whoever gets the server connection next. Callwithin()inside a transaction — it then usesSET LOCAL, which ends with the transaction. - A PostgreSQL timeout aborts the transaction. Every further statement
fails with
25P02until the caller rolls back;within()andrun()never touch your transaction — onlytransaction(), which owns its own, rolls it back. - On PostgreSQL, a transaction left open across
within()is refused. PostgreSQL has no non-transactionalSET: whenwithin()is entered outside a transaction and the callback opens one and leaves it open, the restore runs inside that transaction and a later rollback would undo it — the session would keep the budget.within()therefore throwsLogicExceptionwhen its callback returns with such a transaction open. When the callback throws with it open, its own error is rethrown unchanged and the restore may still be lost: roll back and treat the connection'sstatement_timeoutas unknown. The safe forms:transaction()(it owns the transaction and usesSET LOCAL),within()called inside your transaction (alsoSET LOCAL), or a transaction opened and closed inside the callback. within()gives each statement the budget measured at entry, not what is left after the previous statement: keep callingassertActive()between statements.
use Rasuvaeff\Context\Context;
use Rasuvaeff\Context\Db\StatementTimeout;
[$context, $controller] = Context::background()->withTimeout(2.0);
$timeout = StatementTimeout::for($pdo); // detects MySQL / MariaDB / PostgreSQL
try {
// per statement (MySQL, MariaDB)
$rows = $pdo->query($timeout->apply('SELECT * FROM report WHERE day = CURDATE()', $context))->fetchAll();
// per scope (all three; the only way on PostgreSQL)
$rows = $timeout->within($context, static fn(): array => $pdo->query('SELECT * FROM report')->fetchAll());
} catch (\PDOException $error) {
throw $timeout->translate($error, $context); // ContextExpiredException when the budget ran out
} finally {
$controller->cancel();
}| Dialect | Result for apply('SELECT 1', …) with 1.5 s left |
|---|---|
| MySQL | SELECT /*+ MAX_EXECUTION_TIME(1500) */ 1 |
| MariaDB | SET STATEMENT max_statement_time=1.5 FOR SELECT 1 |
| PostgreSQL | LogicException — use within() |
| Unsupported | SELECT 1 |
- MySQL: the hint goes after the main SELECT — after the CTE list for
WITH … SELECT, inside the leading parenthesis of(SELECT …) UNION …, past leading comments. An existing optimizer hint is extended; an existingMAX_EXECUTION_TIMEkeeps the stricter of the two. Anything else (DML, a versioned comment/*!…*/, SQL the scanner does not recognise) is returned unchanged. - MariaDB: an existing
SET STATEMENTlist gainsmax_statement_time, or its existing value keeps the stricter of the two. - Applying twice equals applying once with the smaller budget.
- Without a deadline
$sqlis returned as is; a terminated context throws.
Sets the remaining budget as the session's statement timeout, runs the callback, and restores the previous value — also when the callback throws (a failing restore never hides the callback's error). A stricter previous value is kept: then nothing is set or restored, the callback runs after the single read.
On PostgreSQL, entered outside a transaction, a callback that returns with a
transaction still open makes within() throw LogicException — with or
without a deadline, so tests without one catch it too (the restore
would not survive that transaction's rollback, see Limitations).
Opens a transaction through PDO, runs the callback under the budget as
within() does, commits when it returns and rolls back (and rethrows) when it
throws. On PostgreSQL the limit is a SET LOCAL, which ends with the
transaction on commit and on rollback alike — also after a timeout aborted
it — so nothing is left on the session. MySQL and MariaDB session variables
are not transactional: there the limit is set and restored around the
callback.
$id = $timeout->transaction($context, static function () use ($pdo): int {
$pdo->exec("INSERT INTO report (day) VALUES (CURRENT_DATE)");
return (int) $pdo->lastInsertId();
});- A transaction already open throws
LogicException: callwithin()inside it. - The callback must not commit, roll back or open a transaction itself.
- It drives
\PDOdirectly. With a layer that counts transactions itself (yiisoft/db), callwithin()/run()inside that layer's transaction instead.
Dialect-independent: $execute receives the SQL to send. MySQL and MariaDB
get apply()'s per-statement limit, PostgreSQL runs $execute inside
within() (and so refuses a transaction $execute leaves open), an
unsupported dialect gets $sql unchanged. Returns what $execute returns; a
terminated context throws before $execute runs.
$rows = $timeout->run($sql, $context, static fn(string $sql): array => $pdo->query($sql)->fetchAll());Returns ContextExpiredException ($error as previous) when the error — or
a PDOException in its previous chain — is the server's statement timeout and the context's deadline has passed
or is within 5 ms (the server can fire early only by rounding the budget down
to whole milliseconds); any other error — or a timeout while more budget is
left, i.e. a limit set elsewhere — is returned unchanged.
yiisoft/db connections expose the PDO, and wrap driver errors in their own
exception with the PDOException as previous; translate() takes the
wrapper as is:
use Yiisoft\Db\Exception\Exception as DbException;
$timeout = StatementTimeout::for($db->getActivePdo());
try {
$value = $timeout->run($sql, $context, static fn(string $sql): mixed => $db->createCommand($sql)->queryScalar());
} catch (DbException $error) {
throw $timeout->translate($error, $context); // finds the PDOException in the chain
}This recipe is executed by tests/Integration/YiisoftDbIntegrationTest.php
on MySQL, MariaDB and PostgreSQL. For a transaction, call run()/within()
inside $db->transaction(...) — not transaction(), which would open one
behind yiisoft/db's back.
| Class | Description |
|---|---|
StatementTimeout |
for(PDO, ?Dialect), dialect(), apply(), within(), transaction(), run(), translate() |
Dialect |
MySql, MariaDb, PostgreSql, Unsupported — detected from the driver name and, for mysql, the server version |
apply() only inserts a number it computed itself — never caller input — and
returns SQL it cannot parse unchanged, so it cannot turn a valid statement
into a different one. Bind user values as parameters as usual.
Exception: MySQL sql_mode=NO_BACKSLASH_ESCAPES. The MySQL scanner that
finds the main SELECT treats \ inside a string literal as an escape, which
is the server default. Under NO_BACKSLASH_ESCAPES a literal ending in a
backslash ('C:\') is read as unterminated, and the hint can land inside a
later string literal — changing that literal's value. Do not use apply() on
MySQL connections in that mode (use within()), or keep backslashes out of
literals by binding such values as parameters. A budget that
came from another process must already be capped (see
rasuvaeff/context's WireCodec).
See examples/ for runnable scripts. Examples are expected to execute without fatal errors and stay aligned with the documented public API.
| Script | Shows | Needs server? |
|---|---|---|
rewrite.php |
What apply() produces for each dialect |
no |
server.php |
A 300 ms budget stopping a heavy query on a live server | yes (CONTEXT_DB_DSN) |
No PHP/Composer on the host — run in Docker via the composer:2 image:
docker run --rm -v "$PWD":/app -w /app composer:2 composer install
docker run --rm -v "$PWD":/app -w /app composer:2 composer build
docker run --rm -v "$PWD":/app -w /app composer:2 composer cs:fix
docker run --rm -v "$PWD":/app -w /app composer:2 composer test
docker run --rm -v "$PWD":/app -w /app composer:2 composer release-checkIntegration suite against live servers (CONTEXT_DB_TEST = mysql,
mariadb or pgsql; CONTEXT_DB_HOST, CONTEXT_DB_PORT,
CONTEXT_DB_NAME, CONTEXT_DB_PASSWORD override the defaults
127.0.0.1, 3306/3307/5432, context, context):
CONTEXT_DB_TEST=mysql vendor/bin/testo --suite=IntegrationOr with Make:
make install
make build
make cs-fix
make test
make test-coverage
make mutation
make release-checkmake test-coverage and make mutation bootstrap pcov inside the
composer:2 container because the base image has no coverage driver.