Skip to content

Database

Every database driver that works in PHP works in PAM: PDO (MySQL, PostgreSQL, SQLite), mysqli and pgsql are all compiled into the default runtime. What changes is the lifetime of your connection. Under PHP-FPM a connection opens and closes with each request; in PAM the worker stays alive, so a connection you open at boot is reused by thousands of requests. That is a large performance win, and it brings a few responsibilities covered below.

PAM adds two database tools of its own:

  • pam-pg, a native PostgreSQL client exposed as pam_pg_* functions and used by Nimbus with DB_DRIVER=pam-pg;
  • Pam\Database\IsolatedPdoPool, which runs blocking PDO queries in child processes so the request Fiber can suspend instead of blocking the worker.

Most applications use an ORM on top: Nimbus ships with the Arcano ORM and Laravel applications keep Eloquent. This page focuses on what the runtime provides and how persistent workers affect any of them.

Open the connection once per worker, lazily, and reuse it:

app/Database.php
<?php
declare(strict_types=1);
namespace App;
use PDO;
final class Database
{
private static ?PDO $pdo = null;
public static function connection(): PDO
{
return self::$pdo ??= new PDO(
(string) getenv('DB_DSN'),
(string) getenv('DB_USERNAME'),
(string) getenv('DB_PASSWORD'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
}
public static function reset(): void
{
self::$pdo = null;
}
}
  • Unfinished transactions. An exception between beginTransaction() and commit() leaves the transaction open for the next request on that worker. Always pair them in try/finally and roll back on failure.
  • Session state leaks. SET search_path, SET time_zone, temporary tables and advisory locks outlive the request. Reset them, or scope them to a transaction (SET LOCAL in PostgreSQL).
  • Dropped connections. The database (or a proxy) closes idle connections and restarts happen. Catch the “server has gone away”/connection errors, call Database::reset() and retry once when the operation is safe to repeat.
  • Connection count. Each worker holds its own connection, so --workers 16 across 4 servers means 64 connections. Size your database max_connections (or put PgBouncer in front) accordingly.
  • Forked workers. When PAM boots your application once and forks workers from it (the post-boot zygote, used by the Laravel host), it disconnects sockets still open at fork time so two processes never share one. Close connections in a pam_before_fork() callback and let each worker reconnect lazily:
pam_before_fork(static fn () => App\Database::reset());

PDO, mysqli and pam-pg wait for the database on the worker’s PHP thread. While a query runs, no other request on that worker makes progress. That is usually fine for short queries; for slow reports, run more workers, move the query to a task worker, or use the isolated pool below.

pam-pg is a PostgreSQL client written in Rust and linked into the runtime. It speaks the extended query protocol only, always binds values as parameters (SQL text is never built from values), prepares each statement once per session and returns values exactly as pdo_pgsql would. It supports SCRAM-SHA-256 and MD5 authentication and TLS through rustls with sslmode up to verify-full.

You rarely call it directly. In Nimbus, set the driver and keep using Arcano:

.env
DB_CONNECTION=pgsql
DB_DRIVER=pam-pg

Outside the PAM runtime (for example in a plain php test run), Nimbus falls back to PDO.

Function Description
pam_pg_connect(array $options): int Open a session and return its handle
pam_pg_execute(int $session, string $sql, array $params = [], int $flags = 0): array|int Run a statement and return [$affected, $columns, $rows]
pam_pg_transaction(int $session, int $operation): void 0 begin, 1 commit, 2 rollback
pam_pg_status(int $session): int -1 unusable, 0 idle, 1 in a transaction, 2 failed transaction
pam_pg_parameter(int $session, string $name): ?string A server parameter such as server_version
pam_pg_release(int $session, string $sql): void Close the statement prepared for $sql
pam_pg_close(int $session): void Close the session

pam_pg_connect() takes libpq option names: host (or hostaddr), port, dbname, user, password, application_name, options, connect_timeout, sslmode (disable, allow, prefer, require, verify-ca, verify-full), sslrootcert and client_encoding (UTF-8 only). Any other option is rejected with a message pointing you to the PDO driver.

bin/report.php
<?php
declare(strict_types=1);
$session = pam_pg_connect([
'host' => '127.0.0.1',
'dbname' => 'acme',
'user' => 'acme',
'password' => (string) getenv('DB_PASSWORD'),
'sslmode' => 'prefer',
]);
[$affected, $columns, $rows] = pam_pg_execute(
$session,
'SELECT id, name FROM users WHERE created_at > :since ORDER BY id',
['since' => '2026-01-01'],
);
foreach ($rows as $row) {
echo "{$row['id']}: {$row['name']}\n";
}
pam_pg_close($session);

Parameters may be null, bool, int, float, string or Stringable, keyed by position or by name (name or :name). A one-element array [$bytes] is sent as binary (like PDO::PARAM_LOB). Rows are keyed by column name; int, float and bool columns come back typed, bytea as a read-only memory stream, everything else as strings.

$flags is a bit mask. There are no PHP constants for it, so define your own:

Value Meaning
1 Simple query protocol: no parameters, returns only the affected row count (useful for multi-statement DDL)
2 Rows as positional arrays instead of keyed by column name

Errors throw PDOException (or RuntimeException when ext-pdo is absent) with the SQLSTATE as the code and in errorInfo, the way pdo_pgsql reports them. A session cannot be used in a forked child; open it after the fork.

Some drivers cannot cooperate with an event loop at all (a vendor ODBC driver, a slow legacy database). Pam\Database\IsolatedPdoPool runs each query in a short-lived child process, so the calling Fiber suspends and the worker keeps serving other requests:

index.php
<?php
declare(strict_types=1);
use Pam\Database\IsolatedPdoPool;
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
$pool = new IsolatedPdoPool('sqlite:' . __DIR__ . '/database.sqlite', maxWorkers: 2);
$pool->query('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
Server::create(static function (Request $request, Response $response) use ($pool): Response {
$insert = $pool->query('INSERT INTO users (name) VALUES (?)', ['Alice']);
$result = $pool->query('SELECT id, name FROM users WHERE name = :name ORDER BY id', ['name' => 'Alice']);
return $response->json(['inserted' => $insert->affectedRows, 'rows' => $result->rows]);
})->listen(3000, '127.0.0.1');
{"inserted":1,"rows":[{"id":1,"name":"Alice"}]}
public function __construct(
string $dsn,
?string $username = null,
?string $password = null,
int $maxWorkers = 4, // 1..64 concurrent child processes
int $maxQueue = 128, // queries waiting for a slot before "queue is full"
float $timeout = 30.0, // per query, including the wait for a slot
int $maxResultBytes = 16 * 1024 * 1024,
);

query(string $sql, array $parameters = []): PdoResult returns rows (a list of associative arrays) and affectedRows. Parameters must be scalars or null. Errors are rethrown as RuntimeException with the driver’s message.

  • Redis: a cooperative Redis client.
  • Memory & State: what survives between requests.
  • Nimbus: the Arcano ORM, migrations and transactions.