The Game Panel Design record
The Game Panel
RFC-0012 Proposed

PostgreSQL database layer

Comparing
v1 to v2
Current
Read the document

Abstract

We I will move the database component to onto PostgreSQL and behind put a compiler between its objects and the SQL they become. Each query and and schema object will become be a node describing what is wanted, and and the compiler registered for a node's its class will turn it into SQL and its bound values together. Connections will use the PostgreSQL driver, transactions will nest through savepointsConnections, the transactions, the type model and DDL schema statements will become PostgreSQL's, and the the engine will gain the the PostgreSQL features its later subsystems are built on, each as a a primitive.

Motivation

The database component assumes MySQL, and its every query and schema objects produce their object produces its own SQL, as RFC-0003 describes. ADR-0016 makes PostgreSQL the only supported database, and ADR-0017 has moves SQL produced by production into a compiler.

Both changes reach the same classes, so they will arrive together: the dialect changes what SQL is produced, and the compiler changes what produces it.

Proposal

The compiler seamSQL behind a compiler

Every object Anything the compiler compiler understands will implement Node, and Querybe a node. Queries, Schemaschema statements, Column columns and Index indexes will extend it. all be nodes. An expression will be narrowed narrow to what the word means, a fragment producing that produces a value, such as raw SQL. A NodeCompiler node compiler will compile turn one type type of nodenode into SQL, given and is handed the compiler for compiler so that it can compile the nodes it contains.:

interface Node {}
interface Expression extends Node {}

interface NodeCompiler
{
    public function compile(Node $node, Compiler $compiler): CompiledSql;
}

Compiler::compile(Node $node): CompiledSql will own no syntax of its own. It will resolve look up the node compiler registered for registered for the node's class from the in a catalogue , and pass itselfitself along, so a compiling recurses: the compiler recurses for the nodes it contains: a table's compiler table will never need to know how a column renders. Compilers will be collected in a registry and sealed into that catalogue, as ADR-0003 decides.

CompilerRegistry What a compiler returns will be the registry that collects compilers, sealed into CompilerCatalogue, following ADR-0003compiled SQL: a string of SQL together with the values bound to it.

final readonly class CompiledSql
{
    public string $sql;
    public array $bindings;

    public static function of(string $sql, mixed ...$bindings): self;
    public function append(string $sql, CompiledSql ...$fragments): self;
}

A fragment of compiled SQL will carry its own bound values, and composing fragments will will concatenate the their SQL and the their values in the the same order, so . There will be no way to produce a placeholder and its value cannot be produced separately.

Every name written into SQL The compiler will go through Identifier, be the only place a value object that quotes and escapes itcomplete statement exists before it becomes a string, whether so it is qualified or will carry a wildcard:hook where a statement can be refused.

  • It will be rendered in double quotes, with any embedded quote doubled.
  • It will be quoted unconditionally, so names are case sensitive exactly as written. The engine's own names are lower snake case, so the folding difference never arises in practice, though a table declared otherwise needs quoting by hand thereafter.
  • Qualified names and wildcards will be handled, which is what allows a schema to qualify a name later without the compilers changing.
  • A name containing a null byte will be rejected, and so will one over 63 bytes, because PostgreSQL truncates silently at that length and two long generated index names could otherwise collide.

Names and literals

Every name written into SQL will go through Identifier, a value object that quotes and escapes it:

  • A name will be rendered in double quotes, with any double quote inside it doubled.
  • Names will be quoted unconditionally, so they are case sensitive exactly as written. The engine's own names are lower snake case, so the difference in case folding never arises for them, but a table declared with any other case has to be quoted by hand from then on.
  • Qualified names and wildcards will be handled, which is what will let a name be qualified with a schema later without any compiler changing.
  • A name containing a null byte will be rejected, and so will a name longer than 63 bytes. PostgreSQL truncates longer names silently, so two long generated index names could otherwise collapse into one.

A matching quoter will handle comments and any other literal that cannot be a bound value.

The compiler will be the only point at which a complete statement exists before it becomes a string, so it will carry a hook for refusing one.

Connections and transactions

ConnectionFactory will produce connections that use the PostgreSQL driver, which gives the engine access to notifications, bulk copying and large objects without a second extension. A connection will hold its options, run its transactions and provide each primitive.

  • Connection string. It will gain the SSL mode, a connection timeout and an application name. The application name will make it possible to tell which part of the panel holds a lock.
  • Sockets. A socket setting will mean the directory PostgreSQL's socket lives in, rather than a path to a socket file.
  • Options. These will be split into overridable defaults and a forced set, so nothing reachable from configuration can disable the error mode the connection depends on. Emulated prepares will be dropped, since the driver always prepares natively.
  • Timeouts. Statement, lock and idle-in-transaction timeouts will become connection configuration, applied when the connection is made.
  • Persistent connections. These will be applied, with the session reset on connect so a reused connection inherits no prepared statements, temporary tables, search path or session locks. They are incompatible with a transaction-mode pooler.
  • Passwords. These may be empty, which is what socket peer authentication uses.

Transactions will become savepoint-aware, which is the sharpest change in behaviour in this design. PostgreSQL aborts an entire transaction when any statement fails, and every later statement fails until it is rolled back. A nested transaction will therefore issue a savepoint, a failure inside it will roll back to that savepointThe driver returns native integers, floats and only the outermost call will commit. Without thatbooleans where MySQL's returned strings, code catching a query failure and carrying so the typed accessors on inside a row from RFC-0003 will carry weight they have not carried before. What the same unit of work is silently brokendriver returns for each type will be pinned by tests rather than assumed.

lastInsertId will be removed from the write result rather than fixed, and RETURNING will replace it.

The driver returns native integersThis is the sharpest change in behaviour in the design. When any statement fails, floats PostgreSQL aborts the whole transaction, and booleans where MySQL returned stringsevery statement after it fails until the transaction is rolled back. A nested transaction will therefore issue a savepoint, so a failure inside it will roll back to that savepoint, and only the typed accessors on a row from RFC-0003 outermost transaction will carry weight they did not beforecommit. Their representations will be pinned by tests rather than assumedWithout this, code that catches a failed query and carries on within the same unit of work would be silently broken.

Connections

ConnectionFactory will produce connections on the PostgreSQL driver, which gives the engine notifications, bulk copying and large objects without a second extension. A connection will hold its options, run its transactions and provide each primitive.

  • The connection string will gain the SSL mode, a connection timeout and an application name. The application name is what will make it possible to tell which part of the panel holds a lock.
  • A socket setting will name the directory PostgreSQL's socket lives in, rather than the socket file.
  • Options will be split into overridable defaults and a forced set, so that nothing reachable from configuration can turn off the error mode the connection depends on. Emulated prepares will be dropped, since the driver always prepares natively.
  • Statement, lock and idle-in-transaction timeouts will be connection configuration, applied when the connection is made.
  • Persistent connections will be applied, and the session reset on connect, so that a reused connection inherits no prepared statements, temporary tables, search path or session locks. They are incompatible with a pooler running in transaction mode.
  • A password may be empty, since socket peer authentication uses none.

The last inserted identifier will be removed from the write result rather than fixed. Returning rows from the statement itself will replace it.

Transactions nest through savepoints

Queries

Each query object will keep its builder methods and lose its rendering. SelectSelects, Insert, Updateinserts, Delete updates, deletes and the raw expression raw expressions will each become a nodes, the clause objects clauses they share will gain gain compilers of their own compilersown, and the the traits that compose shared those clauses will keep only their fluent methods.

Connection::query(), execute() and stream() will accept a node or a string string, and compile it a node through the compiler they are the connection is given, so being . Being executable will then mean that a compiler is is registered for the node, , rather than that the object having has a method that returns returning SQL.

Moving the query nodes behind the compiler will change no SQL except that names are quoted. Every dialect change is separate of dialect will be made separately from that move.

Writes

  • Insert Inserting while ignoring conflicts. will be ON CONFLICT DO NOTHING will replace , in place of INSERT IGNORE.
  • Replace.Replacing This will be removed with no replacementnothing in its place. Deleting It deletes the conflicting row and inserting inserts a new one fires one, which fires delete triggers and loses every column not mentioned; an . An upsert is what is wanted instead.
  • Upsert.An upsert It will be ON CONFLICT with an explicit target, either a column list of columns or a named constraint, followed by either followed by doing nothing or by an update with an optional condition. The excluded row will be availableavailable to the update, since since referring to the the value that failed to insert is the point of the construct.
  • Returning.Returning rows This will be available on insertinserts, update updates and deletedeletes. Asking for it them will change the type of the node , so that the statement is run runs as a query and yields rows, which keeps and the write result a simple stays a simple value. It This will be the answer to the removed lastInsertIdlast inserted identifier, and unlike it, it will work for multi-row inserts, which lastInsertId never didan insert of several rows.
  • Multi-table writes.Writes across tables An will be possible without a correlated subquery: an update may take a FROM, and a delete a a USING, so neither needs a correlated subquery.
  • Ordering and limiting writes.limiting These will be removed from update updates and deletedeletes, which since PostgreSQL does not support. The replacement will be supports neither on a write. A subquery selecting the keys to act onon will take their place.
  • Unguarded writes. An unguarded write, meaning an update or delete compiled with no condition condition, will be refused unless the caller has has said that that is what they meant. This is possible only because the compiler will see sees the whole statement first.

Reads

  • Locking. will offer FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE will be available, each able to skip locked skip locked rows, refuse to wait, or name the tables it applies to. Skipping locked rows is what how a job queue claims work withwill claim work.
  • Select constructs.A select A select will gain distinct on named expressions, common table expressions expressions, including recursive and recursive and data-modifying ones, lateral joins, and window functions with partitions and frames.
  • Pattern matching. Casewill gain case-insensitive matching and the regular expression operators will be availableoperators.
  • JSON. Access will gain the access and containment operators over jsonb will be available. Existence will be expressed tested through the function formsthe function forms rather than the operators, because the operators collide with the placeholder marker and marker: a query containing them one either fails fails to parse or has the operator taken as a parameter.
  • Arrays. Containment and overlap will be availablegain containment and overlap, along with and comparison against any or all of their elements.
  • Full-text search. A will match a text search vector will be matched against a query parsed from what people actually type, with , with ranking available for ordering. It will replace the MySQL MySQL's full-text expression, which will be removed.
  • Offset.An offset An offset without a limit will be valid, which it was not under MySQL.

SchemaTypes

The type model

Today Becomes
The four integer sizes smallint, integer, bigint
Unsigned integers Removed. Widen the type, or add a check constraint
DECIMAL, FLOAT, DOUBLE numeric, real, double precision
The six character types char, varchar, text
The six binary types bytea
Enumerations Text with a check constraint, or a native type by opting in
Sets and years Removed
The four temporal types date, time, timestamptz
JSON jsonb
New uuid, interval, the network address types, and a text search vector

Timestamps will always be carry a time zone awarezone. A naive timestamp in a panel scheduling that schedules restarts across time zones with a naive timestamp is a bug waiting for the clocks to change.

The per-family column Column classes will remainstay grouped by family, since they are that is what makes the shared templates work, but their membership which types belong to each family will change and new families will arrive. An array will be a modifier on any column rather than a family family of its own, , because almost any type can be an array.

Modifiers Columns will gain a collation, a check constraint, an identity columnidentity, a stored generated columnvalues, and default default expressions alongside beside default literals. They will lose column placement, unsigned, per-column a character setsset per column, and and virtual generated columns, values, which need a version above the minimum the panel supportspanel's minimum.

An enumeration will be text with a check constraint by default, because changing the permitted values is then a constraint a swap of one constraint for another inside a transaction. Opting into a native type will give something compact and introspectablethat can be introspected, at the the cost of a schema object with a lifecycle of its own.

DDL takes no bound values

PostgreSQL accepts no placeholders in schema statements, so a default, a check expression and an enumeration's values are all literal text. Every literal will go through the quoter, and a schema node will compile to a statement with no bound values by construction.

Schema statements

Literals, never bound values

PostgreSQL accepts no placeholders in a schema statement, so a default, a check expression and an enumeration's values all have to be literal text. Every literal will go through the quoter, and a schema node will compile to a statement with no bound values by construction.

One node, several statements

A table's definition will no longer compile to one string. Only primary keys and uniqueness can be expressed declared inline, so , so every other index is a separate statementstatement of its own, and so is a comment on a table or a column is a statement of its owncolumn.

Compiling a schema node will therefore produce a statement list, executed in order inside one transaction. PostgreSQL runs schema changes inside transactions, so a migration failing at the that fails at its seventh statement rolls back the first six. The exceptions are creating an index concurrently and creating a database, neither of which can run inside a transaction, so a node will advertise that say so in advance rather than failing when it is executed.

Tables, indexes and other objects

  • Tables. The will lose the storage engine and the table-level character set and collation will be removedcollation, since encoding belongs belongs to the the database. Unlogged They will gain unlogged tables, for data that is genuinely disposable datadisposable, and creation only when absent will be addedthe table is absent.
  • Altering.Altering a table An alter will take several actions in one statement, and a type change of type will carry an explicit conversion where the cast is not implicit.
  • Dropping and truncating. Both will both gain cascading and restricting, and truncation truncating will be able to restart identity restart identity columns.
  • Indexes.An index A method may be chosenchoose its method, and an index may be on an expression, partial, covering, unique with nulls not not distinct, or or use an operator class.
  • Constraints. Primary will cover primary keys, uniqueness, foreign keys with their actions and deferability, checks, and exclusion constraints will be availableand exclusion constraints. Exclusion constraints have An exclusion constraint has no MySQL equivalent equivalent, and let lets the database guarantee that no two no two rows overlap.
  • Objects. Schemas, enumerated types and extensions extensions will be able to be created and dropped, which the native . The native enumeration path needs needs this, and which makes qualifying it is what will later make it possible to qualify names with a schema per for each module possible later.

StreamingStreaming through a cursor

stream() will become use a real server-side cursor: the query will be declared as a cursor, its rows will be fetched forward in forward in batches, and the cursor will be closed. Memory will then stay flat whatever the size of the result, where before the today the driver retrieved everything retrieves every row before the first row was is handed back.

A cursor lives inside a transaction, so streaming will either join the caller's transaction or open one for as long as the as the cursor is open. This will have That has two consequences: a . A long stream will hold holds a transaction open, which holds back back vacuuming, and a . And a slow consumer can be killed by the idle-in-transaction timeout that protects the panel from wedged wedged connections.

The cursor will be closed and the transaction resolved however However iteration ends, including a consumer breaking out early early or a callback throwing, because a the cursor will be closed and the transaction resolved. A leaked cursor holds its transaction transaction, and a leaked transaction eventually holds holds everything.

Primitives

Each primitive will exist because a designed subsystem already designed needs it. Each , and each will be a thin wrapper, a thin wrapper with no policypolicy of its own.

  • Notifications. Sending will be emitted as sent through a function call, so the channel and the payload are bound values rather than interpolated text. Delivery is transactional, so a notification sent inside a transaction fires only on commit. A when it commits. A listener will take its own dedicated hold a connection of its own and block with a timeout rather than polling.
  • Advisory locks. A lock will be taken last for the duration of a transaction, so it a lock cannot outlive its unit of work or or leak when a process dies. A . Taking a lock taken outside a transaction will open one. Keys will be namespaced per by subsystem, so so two subsystems cannot cannot collide, though two names within one namespace still can.
  • Bulk copying. Rows will be read and written write rows in bulk, in a format that handles quoting and embedded delimiters, which is , an order order of magnitude faster than many-row insertsinserting many rows. It will be is for moving rows, where streaming is for for processing them.
  • Session variables. Each will be set for the duration length of a transaction, through a function so that the value is bound, and , and will carry the request identity that row-level policies read. Being transaction-scoped to the transaction is what stops it leaking one request's value leaking into the next request on a reused connection.

TestingProving statements against a server

Every construct the compiler can produce will have a fixture, and one integration test will prepare each fixture's SQL against a real PostgreSQL server, so the . The test will then prove that the database accepts the statement the statement, rather than proving than that the compiler produced what the test test's author typed. The fixture set fixtures will be shared with the the unit tests, so a a construct cannot be added with a string comparison alone.

Out of scope

  • The migration runner. It inherits the two statements that cannot run inside a transaction.
  • Splitting database roles and row-level policies. The session variable makes them possible, but they belong with whoever designs installation. The subsystems the primitives exist for. These are : delivering events durably, the job queue, the scheduler, and any and any policy.
  • Reconnection and backoff for a listener. This belongs , which belong to whatever consumes notifications.
  • Declarative partitioning. It , which has no consumer yet.
  • MERGE. It is available at the minimum supported version, but it is the wrong tool for an upsert.

Alternatives considered

The decisions this This design rests on are four decisions recorded separately: ADR-0003, with which seals mutable registries into immutable catalogues; ADR-0008, which builds database access directly on PDO; ADR-0016, which makes PostgreSQL 16 and above the alternatives each one rejected:only supported database; and ADR-0017, which produces SQL with a compiler.

  • sealing mutable registries into immutable catalogues, in ADR-0003
  • database access built directly on PDO, in ADR-0008
  • PostgreSQL as the only supported database, in ADR-0016
  • SQL produced by a compiler, in ADR-0017

Escaping Fixing the JSON existence operators rather than using their function forms.last inserted identifier We rather than removing it. I rejected this because, although doubling because asking the marker works on this driverconnection after the statement cannot answer for an insert of several rows, it puts and reports a driver quirk into generated SQL stale value after an update or delete, where returning rows from the statement that anyone reading a log has to decodegenerated them answers both.

Fixing the last inserted identifier rather than removing itHolding a cursor beyond its transaction. We It is possible. I rejected this because asking it materialises the connection afterwards cannot answer for a multi-row insert and reports a stale value after an update or deletewhole result when the transaction commits, where returning rows from which is the statement that generated them answers bothcost streaming exists to avoid.

Holding a cursor beyond its transaction. We rejected this because, although it is possible, it materialises the whole result when the transaction commits, which is the cost streaming exists to avoid.

No other alternatives were weighed.

Escaping the JSON existence operators by doubling the placeholder marker, rather than using the function forms. It works on this driver. I rejected this because it puts a driver quirk into generated SQL that anyone reading a log has to decode.

Backwards compatibility

  • MySQL and MariaDB will no longer be supported, and everything written against their dialect will change: the upsert and replace constructs, full-text search, the type model, and ordering or limiting a write.
  • A query or schema object will no longer produce its own SQL, so anything calling those methods methods will compile the the node instead, and a connection will need a compiler.
  • Names will be quoted, so generated SQL will differ from today's even where the construct is unchanged.
  • The last inserted identifier will be gone from the write result, replaced by returning rows.
  • A socket setting will name a directory rather than a file.

Open questions

  • The shape of a compiled result carrying several statements. The column model and the table work agree it is needed and that the table work delivers it, but neither settles what it looks like.
  • How a caller opts out of the unguarded-write guard.
  • The builder methods for an upsert, which the record describes by behaviour rather than by name.
  • Whether writes needing ordering get a helper, or only a documented subquery pattern.
  • How a module registers a node and its compiler, which the compiler seam makes possible but does not describe.
  • The namespace values for advisory locks, one per subsystem.
  • The default batch size for a cursor.

The shape of a compiled result carrying several statements

The column model and the table work agree it is needed and that the table work delivers it, but neither settles what it looks like.

How a caller opts out of the unguarded-write guard

The builder methods for an upsert

The record describes them by behaviour rather than by name.

Whether writes needing ordering get a helper

Or only a documented subquery pattern.

How a module registers a node and its compiler

The compiler seam makes it possible but does not describe it.

The namespace values for advisory locks

One per subsystem.

The default batch size for a cursor

Changelog

  • : Reworded in the readable house style, and the project's own vocabulary linked to the glossary. The design is unchanged.
  • : Rewrote the document in full, with no change to the design.
  • : Removed splitting database roles and row-level policies from Out of scope, since neither belongs to this design.

Sources

  • Issue #51, Engine - Database - PostgreSQL, , whose revisions only reformatted its list of cards: the scope, the architecture and what it buys, what changes across types, queries and connections, each primitive with the consumer that needs it, and the issues it absorbs.
  • Issue #52, Engine - Database - Compiler seam, : the contracts, the compiled result, the identifier value object and its rules, the literal quoter, and the hook for refusing a statement.
  • Issue #53, Engine - Database - PostgreSQL connections and transactions, : the driver, the connection string, socket semantics, the option split, session timeouts, savepoint-aware transactions, persistent connections with a session reset, empty passwords, and the fetch representations to pin.
  • Issue #54, Engine - Database - PostgreSQL test infrastructure and CI, : the fixture registry and the harness that prepares every construct against a real server.
  • Issue #55, Engine - Database - Query compilers at parity, : moving the query nodes behind the compiler with quoting as the only intended difference, the connection gaining a compiler, and what being executable then means.
  • Issue #56, Engine - Database - Query: PostgreSQL write features, : the removals, the upsert, returning rows, multi-table writes, and the unguarded-write guard.
  • Issue #57, Engine - Database - Query: PostgreSQL read features, : locking, the select constructs, pattern matching, the JSON operators and the placeholder collision, arrays, full-text search, and the bare offset.
  • Issue #58, Engine - Database - Schema: column and type model, : the type catalogue, time zone aware timestamps, the class shape and arrays as a modifier, the modifiers gained and lost, DDL taking no bound values, comments being separate statements, and both enumeration paths.
  • Issue #59, Engine - Database - Schema: tables, indexes and DDL objects, : the ordered statement list, the table, index, constraint and object changes, and the two statements that cannot run inside a transaction.
  • Issue #60, Engine - Database - Server-side cursor streaming, : the cursor, its transaction, the vacuuming and timeout trade-offs, and cleanup on early termination.
  • Issue #61, Engine - Database - PostgreSQL primitives, : each primitive's shape, why the function forms are used, transaction-scoped locks and their key derivation, bulk copying, and transaction-scoped session variables.

Source rfc/0012-postgresql-database-layer.md · commit 9444a99 · published