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
InsertInserting while ignoring conflicts.will beON CONFLICT DO NOTHINGwill replace, in place ofINSERT IGNORE.Replace.ReplacingThiswill be removed withno replacementnothing in its place.DeletingIt deletes the conflicting row andinsertinginserts a newone firesone, which fires delete triggers and loses every column not mentioned; an. An upsert is what is wanted instead.Upsert.An upsertItwill beON CONFLICTwith an explicit target, either acolumnlist of columns or a named constraint,followed by eitherfollowed by doing nothing or by an update with an optional condition. The excluded row will beavailableavailable to the update,sincesince referring tothethe value that failed to insert is the point of the construct.Returning.Returning rowsThiswill be available oninsertinserts,updateupdates anddeletedeletes. Asking foritthem will change the type of the node, so that the statementis runruns as a query and yields rows,which keepsand the write resulta simplestays a simple value.ItThis will be the answer to the removedlastInsertIdlast inserted identifier, and unlike it, it will work formulti-row inserts, which lastInsertId never didan insert of several rows.Multi-table writes.Writes across tablesAnwill be possible without a correlated subquery: an update may take aFROM, and a deleteaaUSING, so neither needs a correlated subquery.- Ordering and
limiting writes.limitingThesewill be removed fromupdateupdates anddeletedeletes,whichsince PostgreSQLdoes not support. The replacement will besupports neither on a write. A subquery selecting the keys to actonon will take their place. Unguarded writes.An unguarded write, meaning an update or delete compiled with noconditioncondition, will be refused unless the callerhashas saidthatthat is what they meant. This is possible only because the compilerwill seesees the whole statement first.
Reads
- Locking
.will offerFOR UPDATE,FOR NO KEY UPDATE,FOR SHAREandFOR KEY SHAREwill be available, each able toskip lockedskip locked rows, refuse to wait, or name the tables it applies to. Skipping locked rows iswhathow a job queueclaims work withwill claim work. Select constructs.A selectA selectwill gain distinct on named expressions, common tableexpressionsexpressions, includingrecursive andrecursive and data-modifying ones, lateral joins, and window functions with partitions and frames.- Pattern matching
.Casewill gain case-insensitive matching and the regular expressionoperators will be availableoperators. - JSON
.Accesswill gain the access and containment operators overjsonbwill be available. Existence will beexpressedtested throughthe function formsthe function forms rather than the operators, because the operators collide with the placeholdermarker andmarker: a query containingthemone eitherfailsfails to parse or has the operator taken as a parameter. - Arrays
.Containment and overlapwillbe availablegain containment and overlap,along withand comparison against any or all of their elements. - Full-text search
.Awill match a text search vectorwill be matchedagainst a query parsed from what people actually type, with, with ranking available for ordering. It will replacethe MySQLMySQL's full-text expression, which will be removed. Offset.An offsetAn offsetwithout 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
.Thewill lose the storage engine and the table-level character set andcollation will be removedcollation, since encodingbelongsbelongs tothethe database.UnloggedThey will gain unlogged tables, for data that is genuinelydisposable datadisposable, and creation only whenabsent will be addedthe table is absent. Altering.Altering a tableAn alterwill take several actions in one statement, and atypechange of type will carry an explicit conversion where the cast is not implicit.- Dropping and truncating
.Bothwill both gain cascading and restricting, andtruncationtruncating will be able torestart identityrestart identity columns. Indexes.An indexA methodmaybe chosenchoose its method, andan indexmay be on an expression, partial, covering, unique with nullsnotnot distinct,oror use an operator class.- Constraints
.Primarywill cover primary keys, uniqueness, foreign keys with their actions and deferability, checks,and exclusion constraints will be availableand exclusion constraints.Exclusion constraints haveAn exclusion constraint has no MySQLequivalentequivalent, andletlets the database guarantee thatno twono two rows overlap. Objects.Schemas, enumerated types andextensionsextensions will be able to be created and dropped, which the native. The native enumeration pathneedsneeds this, andwhich makes qualifyingit is what will later make it possible to qualify names with a schemaperfor each modulepossible 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
.Sendingwill beemitted assent 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 onlyon commit. Awhen it commits. A listener willtake its own dedicatedhold a connection of its own and block with a timeout rather than polling. - Advisory locks
.A lockwillbe takenlast forthe duration ofa transaction, soita lock cannot outlive its unit of workoror leak when a process dies. A. Taking a locktakenoutside a transaction will open one. Keys will be namespacedperby subsystem,soso two subsystemscannotcannot collide, though two names within one namespace still can. - Bulk copying
.Rowswillberead andwrittenwrite rows in bulk, in a format that handles quoting and embedded delimiters, which is, anorderorder of magnitude faster thanmany-row insertsinserting many rows. Itwill beis for moving rows, where streaming isforfor processing them. - Session variables
.Eachwill be set for thedurationlength of a transaction, through a function so that the value is bound, and, and will carry the request identity that row-level policies read. Beingtransaction-scoped to the transaction is what stopsit leakingone request's value leaking into the nextrequeston 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.Thesession variable makes them possible, but they belong with whoever designs installation. Thesubsystems the primitives exist for.These are: delivering events durably, the job queue, the scheduler,and anyand 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.
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
methodsmethods will compilethethe 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