Database component
- Comparing
- v1 to v2
- Current
- Read the document
Abstract
A I will give the engine a database component built directly on PDO. Any number of named connections are named
connections will be configured, one of them is
designated the the
primary connection and connection used whenever no name is given, and a connection is will be
injected into a parameter
parameter with the Database attribute. Queries and schema changes are will be built as objects that that
produce their own SQL and
bindingsand bound values, and a connection executes will run them, returning fetched resultsthe rows in full, a cursor a
cursor over them, or the outcome of a write resultwrite.
Motivation
The panel needs a simple database abstraction, so that queries can be built programmatically without working in SQL
directlycode without writing SQL by hand, and and
so that the database can be created and then changed as the panel and its modules modules change.
The panel also needs to be able to connect to one or more separate databasesthan one database. The core and the first-party components and
modules only ever use one, but support for supporting several is included, with takes little extra effort, effort and leaves room for a future situations
that need case that
needs it.
Proposal
PartsHow the parts fit together
| Part | Responsibility |
|---|---|
| Connections | Configuring connections, creating them, and injecting them. |
| Execution | Running SQL against a connection, returning its results, and transactions. |
| Query builder | Building SELECT, INSERT, UPDATE and DELETE queries as objects. |
| Schema builder | Building statements that create, alter and drop databases, tables, columns and indexes, as objects. |
The query builder and schema builder are distinct two builders will be separate from connections. A builder produces will produce SQL and the values bound to it,
, and knows know
nothing of the connection it is will run against. A connection accepts will accept SQL and bound values, whether written as a
string or from produced by a builder. The point where the two meet will be the expression,
described below: every builder object will be one, and a connection will accept any of them.
ConceptsConfiguring connections
| Term | Meaning |
|---|---|
| Connection | An open connection to one database, identified by name. |
| Connection name | The name a connection is configured and requested under. |
| Primary connection | The connection used whenever no connection name is given. |
| Driver | The type of database a connection talks to. Only MySQL, including compatible MariaDB, is exposed. |
| Persistent connection | A connection that PDO keeps open and reuses, rather than closing it. |
| Expression | An object that produces SQL, with a ? placeholder for each bound value, and the values bound to those placeholders. |
| Query | An expression that is a complete query, such as a select or an insert, rather than a fragment such as col = ?. |
| Schema statement | An expression that is a complete schema statement, such as creating a table. |
| Condition | One comparison in a WHERE, HAVING or join clause, joined to the one before it with AND or OR. |
| Result | The rows returned by a query, fetched in full. |
| Cursor | The rows returned by a query, fetched one at a time. |
Connections
Configuration
DatabaseConfig and ConnectionConfig are configuration objects, per RFC-0002 and
ADR-0005. Both are created through a static make(), and
both restore themselves from an exported array by passing its entries to their constructor as named arguments.
The component will have four parts. Connections will be configured, created and injected. A
connection will execute SQL, return its results and manage transactions. The query builder will build SELECT,
INSERT, UPDATE and DELETE queries as objects, and the schema builder will build, as
objects, the statements that create, alter and drop databases, tables, columns and indexes.
The component's configuration will be two configuration objects, as
RFC-0002 and ADR-0005
describe: DatabaseConfig for the component and a ConnectionConfig for each connection.
Both will be created through a static make(), and both will restore themselves from an exported array by passing its
entries to their constructor as named arguments.
$config = DatabaseConfig::make(
primary: 'main',
connections: [
'main' => ConnectionConfig::make('127.0.0.1', 3306, null, 'panel', 'panel', 'secret'),
'replica' => ConnectionConfig::make(null, null, '/var/run/mysqld/mysqld.sock', 'panel', 'panel', 'secret'),
],
persistent: false,
);
DatabaseConfig |
Holds |
|---|---|
primary |
The name of the primary connection. |
connections |
Every connection's ConnectionConfig, keyed by connection name. |
persistent |
Whether every connection is persistent. One flag applies to all of them, and it defaults to false. |
A ConnectionConfig will hold where to connect, which database configuration needs a primary connection nameto use, at least one connectionthe username and password to connect with,
and PDO options of its own. A connection will be reached either through a Unix socket or through a host and port, with
the port defaulting to 3306 when none is given. When both a socket and a connection configured under
host are given, the primary namesocket will be used.
ConnectionConfig |
Holds |
|---|---|
host |
The host to connect to, when not connecting through a socket. |
port |
The port to connect to on the host. Defaults to 3306 when not given. |
socket |
The Unix socket to connect through. Used in preference to the host when both are given. |
database |
The database to use. |
username, password |
The credentials to connect with. |
options |
PDO options for the connection, applied over the defaults. |
driver |
The driver, always mysql. It is not configurable. |
The driver is carried by every connection's configuration, so support for other database types can be added inside the component without restructuring it, but only MySQL is exposed, per ADR-0007.
Connection factory
ConnectionFactory is constructed with the DatabaseConfig, and hands out connections through make():
DatabaseConfig will hold the name of the primary connection, every connection's
configuration keyed by its connection name, and a single persistent flag. A database configuration must name a primary
connection, configure at least one connection, and configure one under the primary name. The persistent flag will
apply to every connection at once, never to one alone, and will default to false.
Every connection's configuration will also carry its driver, the type of database it talks to. The driver will
always be mysql and will not be configurable. It will be carried so that support for other database types can be
added inside the component later without restructuring it, while only MySQL is exposed, as
ADR-0007 decides.
Opening a connection
A ConnectionFactory will be constructed with the DatabaseConfig, and will hand out
connections through make(?string $name = null): Connection:
$primary = $factory->make();
$replica = $factory->make('replica');
With no name, make( ?string $name = null): Connectionfollows these steps:will use the name of the primary connection. If a connection
has already been created under the name, that connection will be returned. Otherwise the factory will look up the
configuration for the name, throwing ConnectionException when there is none, and create a PDO connection from it with
its DSN, credentials and options, throwing ConnectionException when it cannot connect. The new connection will be kept
under its name for as long as the factory lives, and returned. ConnectionException will carry the connection name, and
the underlying error as its previous exception.
- With no name, the primary connection's name is used.
- A connection already created under the name is returned.
- Otherwise the connection's configuration is looked up. With no configuration under the name, it throws.
- A PDO connection is created from the configuration, with its DSN, credentials and options. If it cannot connect, it throws.
- The connection is kept under its name for the lifetime of the factory, and returned.
For MySQL, the DSN is built as followsEvery connection will be created with these PDO options:
| Configuration | DSN |
|---|---|
| A socket | mysql:unix_socket={socket};dbname={database} |
| A host and no socket | mysql:host={host};port={port};dbname={database}, with the port defaulting to 3306 |
| Neither | Throws |
A driver other than MySQL throws.
PDO options
Every connection is created with these options:
For MySQL, the DSN will be mysql:unix_socket={socket};dbname={database} when a socket is configured, and
mysql:host={host};port={port};dbname={database} when only a host is, with the port defaulting to 3306. A
connection configured with neither a socket nor a host will throw DatabaseException, and so will a driver other
than MySQL.
| Option | Value | Configurable |
|---|---|---|
PDO::ATTR_ERRMODE |
PDO::ERRMODE_EXCEPTION |
No, always forced |
PDO::ATTR_DEFAULT_FETCH_MODE |
PDO::FETCH_ASSOC |
Yes |
PDO::ATTR_EMULATE_PREPARES |
false |
Yes |
PDO::ATTR_STRINGIFY_FETCHES |
false |
Yes |
A connection's configured options are will be applied over the these defaults, so they can change any configurable default that is
configurable and add
add options of their own. The error mode is will always be forced to throw exceptions, because because
everything built on a connection
connection relies on errors being thrown. When persistent is set, every connection will also
be created with PDO::ATTR_PERSISTENT, so that PDO keeps it open and reuses it rather than closing it.
When persistent is set on the DatabaseConfig, every connection is also created with PDO::ATTR_PERSISTENT.
Injection
A connection is injected into a parameter typed Connection with the Database attribute, which takes an optional
connection name:
Injecting a connection
A connection will be injected into a parameter typed Connection by placing the Database
attribute on it, with an optional connection name:
public function __construct(
#[Database] private Connection $primary,
#[Database('replica')] private Connection $replica,
) {}
DatabaseResolverDatabaseis the resolver will be a resolvable attribute, paired with DatabaseDatabaseResolver, the resolver in the
resolver tier of
ADR-0002, using the mechanism in
of
RFC-0001. It is The resolver will itself be resolved through the container, receiving the
which
will give it the ConnectionFactory, and returns the connection from it will return whatever make() returns for the attribute's name, so a a
parameter with no name
receives name will receive the primary connection. The parameter must be be
typed exactly Connection. The resolver will throw DatabaseException when it is given a dependency that does not
carry the Database attribute, or one that is not typed Connection.
ExecutionRunning SQL
| Component | Responsibility |
|---|---|
Connection |
A named connection, wrapping its PDO connection. Executes SQL and manages transactions. |
Result |
The rows returned by a query, fetched in full. |
Cursor |
The rows returned by a query, fetched one at a time. |
WriteResult |
The outcome of a statement that writes. |
Row |
One row, with typed access to its columns. |
Executing SQL
| Method | Effect |
|---|---|
query(Expression|string $query, array $bindings = []): Result |
Executes a query that returns rows, and returns them as a Result. |
execute(Expression|string $query, array $bindings = []): WriteResult |
Executes a statement that writes, and returns a WriteResult. |
stream(Expression|string $query, array $bindings = []): Cursor |
Executes a query that returns rows, and returns a Cursor over them. |
Each method accepts SQL as a string Every statement will be prepared, then executed with its bound values. Booleans among the values bound values will first be
converted to itthe integers 1 and 0, because MySQL treats booleans as integers. A statement that cannot be prepared
or an expressionexecuted will throw QueryException, whose which will carry its SQL and bound values are
taken from its values, through toSqlgetSql()and and
getBindings(). Bound values given alongside an expression are ignored, and the underlying error as its previous exception.
Every statement is prepared, then executed with its bound values. Booleans among the bound values are converted to
the integers 1 and 0 first, because MySQL treats booleans as integers. A statement that cannot be prepared or
executed throws QueryException, which carries its SQL and bound values.
A Connection will be a named connection wrapping its PDO connection. It will run SQL in three ways, which differ in
what they return:
query(Expression|string $query, array $bindings = []): Resultwill run a query that returns rows, and return them as a result.execute(Expression|string $query, array $bindings = []): WriteResultwill run a statement that writes, and return its outcome.stream(Expression|string $query, array $bindings = []): Cursorwill run a query that returns rows, and return a cursor over them.
Each will accept SQL as a string together with the values bound to it, or an expression,
whose SQL and bound values will be taken from its toSql() and getBindings(). Bound values passed alongside an
expression will be ignored.
$servers = $connection->query(
Select::from('servers')->where('status', '=', 'running')->orderBy('name'),
);
foreach ($servers->all() as $server) {
$name = $server->string('name');
}
$write = $connection->execute(Insert::into('servers')->values(['name' => 'Survival']));
$id = $write->lastInsertId();
Whatever is returned, a Result, a Cursor and or a WriteResult each , will carry the bound values they were it was executed with, as as
bindings.
Results
A Resultresult fetches will fetch every row the first time any row is read, and keeps keep them. It will give the
first row, or null when there are none, every row at once, each row in turn to a callback, the number of rows, and
whether there are none.
| Method | Effect |
|---|---|
first(): ?Row |
Returns the first row, or null when there are none. |
all(): array |
Returns every row. |
each(callable $callback): void |
Calls the callback with each row in turn. |
count(): int |
Returns the number of rows. |
isEmpty(): bool |
Returns whether there are no rows. |
A CursorWriteResultfetches rows one at will hold the outcome of a time as they are iteratedwrite: the number of rows the statement affected, so a large result is processed without every row being
held in memory at oncethe identifier generated
by the statement's own insert, and whether it succeeded. Its rows can lastInsertId() will report only an identifier the statement
itself generated, and return null when it generated none. wasSuccessful() will be iterated oncetrue when the statement affected
at least one row.
| Method | Effect |
|---|---|
each(callable $callback): void |
Fetches each row in turn and calls the callback with it. |
rows(): Generator |
Returns a generator that fetches and yields each row in turn. |
count(): int |
Returns the number of rows. |
isEmpty(): bool |
Returns whether there are no rows. |
A The row's typed accessors, , WriteResultstring()int(), float(), bool() holds the outcome of and array(), will cast a write.column's value, and
throw InvalidValueCastException when it cannot be cast. A missing column, or a null value, will not be castable to
any type. Each will accept:
| Method | Effect |
|---|---|
affectedRows(): int |
Returns the number of rows the statement affected. |
lastInsertId(): ?string |
Returns the identifier generated by the statement's insert, or null when it generated none. |
wasSuccessful(): bool |
Returns whether the statement affected at least one row. |
Rows
A Row holds one row's values, keyed by column name.
| Method | Effect |
|---|---|
get(string $column): mixed |
Returns the column's value, or null when the row has no such column. |
has(string $column): bool |
Returns whether the row has the column, including when its value is null. |
isNull(string $column): bool |
Returns whether the row has the column and its value is null. |
toArray(): array |
Returns every value, keyed by column name. |
string(string $column): string |
Returns the value as a string. |
int(string $column): int |
Returns the value as an integer. |
float(string $column): float |
Returns the value as a float. |
bool(string $column): bool |
Returns the value as a boolean. |
array(string $column): array |
Returns the value as an array. |
The typed accessors cast the value, and throw InvalidValueCastException when it cannot be cast. A missing column, or
a null value, cannot be cast to any type.
Reading results
A cursor will fetch rows one at a time as they are iterated, so that a large result can be
processed without every row being held in memory at once. Its rows will be iterable only once, either by passing each
row to a callback or through a generator from rows(). It will also give the number of rows and whether there are none.
A row will hold one row's values keyed by column name. get() will return a column's value, or
null when the row has no such column. has() will say whether the row has the column, including when its value is
null, and isNull() whether it has the column and the value is null. toArray() will return every value keyed by
column name.
| Accessor | Accepts |
|---|---|
string |
A string, or a number cast to a string. |
int |
An integer, or a numeric string cast to an integer. |
float |
A float, or an integer or numeric string cast to a float. |
bool |
A boolean, or an integer cast to a boolean. The strings true, 1 and yes are true, and false, 0 and no are false. |
array |
An array, or a string holding valid JSON, decoded. |
Transactions
| Method | Effect |
|---|---|
transaction(callable $callback): mixed |
Begins a transaction, calls the callback with the connection, commits, and returns the callback's result. If the callback throws, the transaction is rolled back and the exception rethrown. |
beginTransaction(): void |
Begins a transaction. |
commit(): void |
Commits the active transaction. |
rollback(): void |
Rolls back the active transaction. |
isInTransaction(): bool |
Returns whether a transaction is active. |
Transactions
transaction(callable $callback): mixed will begin a transaction, call the callback with the
connection, commit, and return what the callback returned. If the callback throws, the
transaction will be rolled back and the exception rethrown.
$connection->transaction(function (Connection $connection) {
$connection->execute(Update::table('servers')->set(['owner_id' => 2])->where('id', '=', 1));
$connection->execute(Insert::into('audit')->values(['server_id' => 1, 'action' => 'transfer']));
});
A transaction will also be manageable by hand, with beginTransaction(), commit() and rollback(), and
isInTransaction() will say whether one is active. Transactions do will not nest, and there are will be no savepoints. .
Beginning a transaction while one is active throws
will throw DatabaseException, and so does will a commit or a rollback that
the database refuses.
Expressions
Every object in the query builder and the schema builder implements will implement Expression:, which will have two methods.
toSql(): string will return the object's SQL, with a ? placeholder for each bound value, and
getBindings(): array will return the values bound to those placeholders, in the order the placeholders appear.
| Method | Returns |
|---|---|
toSql(): string |
The object's SQL, with a ? placeholder for each bound value. |
getBindings(): array |
The values bound to those placeholders, in the order the placeholders appear. |
Each object is responsible for converting itself Four contracts will extend Expression without adding anything to SQL. An it, to mark what type of expression that contains other expressions builds its
SQL from theirsa method
requires: Query for a complete query (Select, and gathers their bound values in the same orderInsert, so an expression can be used anywhere another is
accepted Update or Delete), Schema for
a complete schema statement, Column for a column definition and its bound values follow itIndex for an
index definition.
These contracts extend Expression and add nothing Values supplied to ita query will always be bound, never written into its SQL. Each exists to mark what type of expression is required:There will be two exceptions: a query's
limit and offset, which will be written as integers, and the literal values in a schema statement, such as a column's
default or comment, since schema statements have no bound values.
| Contract | Marks |
|---|---|
Query |
A complete query: Select, Insert, Update or Delete. |
Schema |
A complete schema statement. |
Column |
A column definition. |
Index |
An index definition. |
Values supplied to a query are bound, never written into its SQL. The exceptions are a query's limit and offset, which are written as integers, and the literal values in a schema statement, such as a column's default or comment, since schema statements have no bound values.
A name written into SQL as an identifier, such as Each query will be created through a static factory that names its table, column or index nameand built up with
fluent methods that return the query. A query will accumulate its clauses in whatever order they are added, is quoted with backticksand render
them in a fixed order of its own, with any
backtick inside it doubledthe bound values following that same order. A string clause with nothing added to it
will be left out. A clause that several queries share, such as their conditions or their
ordering, will be written once and composed into SQL as a literal is quoted with single quotesevery query that supports it, with any single
quote inside so it escapedbehaves the same everywhere.
Query builder
| Component | Responsibility |
|---|---|
Select |
Builds a SELECT query. |
Insert |
Builds an INSERT or REPLACE query. |
Update |
Builds an UPDATE query. |
Delete |
Builds a DELETE query. |
WhereClause |
A list of conditions, used for WHERE and HAVING. |
JoinClause |
The conditions of one join. |
Raw |
Raw SQL and the values bound to it. |
Expressions |
Static factories for the built-in expressions. |
Each query is created through a static factory naming its table, and built with fluent methods that return the query. Clauses shared between queries, such as conditions or ordering, are written once and composed into every query that supports them, so they behave the same everywhere.
Select
Each object will be responsible for turning itself into SQL. An expression that contains others will build its SQL from theirs and gather their bound values in the same order, so an expression can be used anywhere another is accepted and its bound values will follow it.
A name written into SQL as an identifier, such as a table, column or index name, will be quoted with backticks, with any backtick inside it doubled. A string written into SQL as a literal will be quoted with single quotes, with any single quote inside it escaped.
Building queries
Selecting
$query = Select::from('servers')
->columns('servers.id', 'servers.name', Expressions::count('players.id'))
->leftJoin('players', 'players.server_id', '=', 'servers.id')
->where('servers.status', '=', 'running')
->groupBy('servers.id', 'servers.name')
->havingRaw('COUNT(players.id) > ?', [0])
->orderBy('servers.name')
->limit(20)
->offset(40);
| Method | Effect |
|---|---|
from(Expression|string $table) |
Static. Creates a select from a table, or from a subquery written in parentheses. |
columns(Expression|string ...$columns) |
Sets the columns selected, replacing any set before. With no columns set, * is selected. |
addColumn(Expression|string $column) |
Adds a column to those selected. |
distinct() |
Selects only distinct rows. |
join(), leftJoin(), rightJoin(), crossJoin() |
Add joins, as described in Joins. |
where() and its variants |
Add conditions to the WHERE clause, as described in Conditions. |
groupBy(Expression|string ...$columns) |
Adds columns to group by. |
having(Closure|string $column, ?string $operator = null, mixed $value = null) |
Adds a condition to the HAVING clause, joined with AND, as where() does. |
orHaving(), havingRaw(), orHavingRaw() |
Add conditions to the HAVING clause, as orWhere(), whereRaw() and orWhereRaw() do. |
orderBy(Expression|string $column, string $direction = 'asc') |
Adds a column to order by. A direction of desc, in any case, orders descending, and any other direction ascending. |
limit(int $limit) |
Sets the maximum number of rows. |
offset(int $offset) |
Sets the number of rows to skip. |
The clauses are written in this order, whatever order they were added in, and the bound values follow the same order:
A select will render its clauses in this order:
SELECT [DISTINCT] {columns} FROM {table} {joins} WHERE {conditions} GROUP BY {columns} HAVING {conditions}
ORDER BY {columns} LIMIT {limit} OFFSET {offset}
A clause with nothing added It will select from a table, or from a subquery given as an expression and written in
parentheses. It can be made to select only distinct rows, and with no columns set it is left outwill select *. A column can be a
name or an expression, and setting the columns will replace any set before, where adding one will keep them. Grouping
columns will accumulate. The HAVING clause will take the same conditions as WHERE,
through having(), orHaving(), havingRaw() and orHavingRaw(). An ordering will be ascending by default: a
direction of desc, in any case, will order descending, and any other direction ascending. The limit and offset will be
written as integers, as Expressions describes.
Conditions
Select, Update and Delete will each have a WHERE clause, built with these methodsfrom conditions. Each method has The
first condition in a variant
prefixed orclause will have no conjunction, which joins and each later one will be joined to the condition one before it with AND,
or with OR instead of when it is added through the method's variant, such as ANDororWhere() or orWhereNull(). Every method
that adds a condition will have one.
| Method | Adds |
|---|---|
where(Closure|string $column, ?string $operator = null, mixed $value = null) |
A comparison between the column and a bound value, using the operator. Given a closure instead of a column, a group. |
whereNull(string $column) |
{column} IS NULL. |
whereNotNull(string $column) |
{column} IS NOT NULL. |
whereIn(string $column, array|Expression $values) |
{column} IN (...), with a placeholder for each value, or with the expression's SQL as a subquery. |
whereNotIn(string $column, array|Expression $values) |
{column} NOT IN (...), in the same way. |
whereRaw(string $sql, array $bindings = []) |
The SQL as given, with its bound values. |
whereFullText(array $columns, string $value, string $mode = 'natural') |
A full-text search of the columns for the bound value, as the match expression describes. |
The first condition in a clause has no conjunction, and each later one is joined to the one before it.
When The other methods will be shorthands for particular conditions. whereNull() and whereNotNull() will add IS NULL
and IS NOT NULL. whereIn() and whereNotIn() will add IN (...) and NOT IN (...), given either an array of
values, with a column is givenplaceholder for each, the operator or an expression whose SQL is requiredwritten as a subquery.
An IN or NOT IN condition given an empty array of values will throw InvalidExpressionException, however it is
added. There is no shorthand that assumes will add SQL as given, with its bound values.
=whereRaw(string $sql, array $bindings = [])whereFullText(array $columns, string $value, string $mode = 'natural') will add a full-text search of the columns for
a bound value, as Built-in expressions describes.
| Operator | SQL |
|---|---|
= |
{column} = ? |
!= |
{column} != ? |
<, >, <=, >= |
{column} < ?, and so on |
is |
{column} IS ? |
is null |
{column} IS NULL, with no value bound |
is not null |
{column} IS NOT NULL, with no value bound |
in |
{column} IN (?, ...), with a placeholder for each value in an array |
not in |
{column} NOT IN (?, ...), in the same way |
Operators are matched regardless of case. Any other operator throws InvalidExpressionException. An IN or
NOT IN condition given an empty array of values throws InvalidExpressionException, however it is added.
Given a closure, where() and orWhere() pass it a new WhereClause, to which it adds conditions with the same
methods. The group is written in parentheses and joined to the condition before it. A closure that adds no condition
throws InvalidExpressionException.
where(Closure|string $column, ?string $operator = null, mixed $value = null) will compare a column with a bound
value using an operator. When a column is given, the operator will be required: there will be no shorthand that
assumes =. The operators will be matched regardless of case, and any other operator will throw
InvalidExpressionException:
| Operator | SQL |
|---|---|
=, !=, <, >, <=, >= |
{column} = ?, and so on |
is |
{column} IS ? |
is null |
{column} IS NULL, with no value bound |
is not null |
{column} IS NOT NULL, with no value bound |
in |
{column} IN (?, ...), with a placeholder for each value in an array |
not in |
{column} NOT IN (?, ...), in the same way |
Given a closure in place of a column, where() and orWhere() will pass it a new WhereClause, to which it adds
conditions with the same methods. The group will be written in parentheses and joined to the condition before it. A
closure that adds no condition will throw InvalidExpressionException.
Select::from('servers')
->where('game', '=', 'minecraft')
->where(function (WhereClause $clause) {
$clause->where('status', '=', 'running')->orWhere('status', '=', 'starting');
});
Joins
| Method | Adds |
|---|---|
join(string $table, Closure|string $first, ?string $operator = null, ?string $second = null) |
An INNER JOIN. |
leftJoin(string $table, Closure|string $first, ?string $operator = null, ?string $second = null) |
A LEFT JOIN. |
rightJoin(string $table, Closure|string $first, ?string $operator = null, ?string $second = null) |
A RIGHT JOIN. |
crossJoin(string $table) |
A CROSS JOIN, with no conditions. |
Given two columns and an operator, a join compares the columns. Given a closure, the join passes it the A join's
s conditions will be written after , JoinClauseONto which it adds conditions:and a join with no conditions will have no ON.
| Method | Adds |
|---|---|
on(string $left, string $operator, string $right) |
A comparison between two columns, joined with AND. |
orOn(string $left, string $operator, string $right) |
A comparison between two columns, joined with OR. |
where(string $column, string $operator, mixed $value) |
A comparison between a column and a bound value, joined with AND. |
orWhere(string $column, string $operator, mixed $value) |
A comparison between a column and a bound value, joined with OR. |
A join's conditions are written after ON. A join with no conditions has no ON.
A select will be joined to another table with join() for an INNER JOIN, leftJoin() for a LEFT JOIN and
rightJoin() for a RIGHT JOIN. Each will take the table, then either two columns and the operator comparing them, or
a closure. Given a closure, the join will pass it the join's JoinClause, to which it adds
conditions. on() and orOn() will compare two columns, and where() and orWhere() will
compare a column with a bound value, joined with AND and OR respectively. crossJoin() will take only the table,
and add a CROSS JOIN with no conditions.
Select::from('servers')->join('players', function (JoinClause $join) {
$join->on('players.server_id', '=', 'servers.id')->where('players.online', '=', true);
});
InsertInserting
| Method | Effect |
|---|---|
into(string $table) |
Static. Creates an insert into the table. |
values(array $values) |
Adds a row, as values keyed by column name. Called more than once, it inserts every row in one query. |
ignore() |
Writes INSERT IGNORE, so rows that would break a unique key are skipped. |
replace() |
Writes REPLACE INTO, so rows that would break a unique key replace the rows they clash with. It takes precedence over ignore(). |
upsert(array $values) |
Adds ON DUPLICATE KEY UPDATE, setting each column to its value. A value that is an expression is written as SQL, with its bound values, so a column can be set from itself or another column. It replaces any values set before. |
Insert::into() will create an insert into a table, and values() will add a row to it, as values keyed by column
name. Called more than once, it will insert every row in one query.
Insert::into('player_visits')
->values(['server_id' => 1, 'player' => 'Ada', 'visits' => 1])
->values(['server_id' => 1, 'player' => 'Bob', 'visits' => 1])
->upsert(['visits' => Raw::from('visits + 1')]);
The first row's columns are the columns of will be the insert's columns. Every later row must have the same columns, in any order, and
each row's values are will be bound in the order of the insert's columns. A row with different whose columns throws
differ will throw
InvalidExpressionException, and so does will producing the SQL of an insert with no rows.
Three methods will change what happens to a row that would break a unique key. ignore() will write INSERT IGNORE, so
the row is skipped. replace() will write REPLACE INTO, so the row replaces the one it clashes with; it will take
precedence over ignore(). upsert() will add ON DUPLICATE KEY UPDATE, setting each column given to its value, and
replace any values given to it before. A value that is an expression will be written as
SQL, with its bound values, so a column can be set from itself or from another column. The bound values are every will be every
row's values, then the upsert's.
UpdateUpdating and deleting
| Method | Effect |
|---|---|
table(string $table) |
Static. Creates an update of the table. |
set(array $values) |
Sets columns to values, keyed by column name, merged with any set before. A value that is an expression is written as SQL, with its bound values. |
where() and its variants |
Add conditions, as described in Conditions. |
orderBy(Expression|string $column, string $direction = 'asc') |
Adds a column to order by, as for a select. |
limit(int $limit) |
Sets the maximum number of rows updated. |
Update::table() will create an update of a table. set() will set columns to values, keyed by column name and merged
with any set before, and a value that is an expression will be written as SQL, with its
bound values. An update will take conditions as a select does, and can be ordered as a
select is, with limit() setting the maximum number of rows updated. It will render as
UPDATE {table} SET {values} WHERE {conditions} ORDER BY {columns} LIMIT {limit}.
Update::table('servers')
->set(['status' => 'stopped', 'restarts' => Raw::from('restarts + 1')])
->where('id', '=', 1);
The clauses are written Delete::from() will create a delete from a table, with conditions, ordering and a limit on the rows deleted in the
same way. It will render as UPDATE DELETE FROM {table} SET {values} WHERE {conditions} ORDER BY {columns} LIMIT {limit}, and the
bound values follow the same order.
Delete
| Method | Effect |
|---|---|
from(string $table) |
Static. Creates a delete from the table. |
where() and its variants |
Add conditions, as described in Conditions. |
orderBy(Expression|string $column, string $direction = 'asc') |
Adds a column to order by, as for a select. |
limit(int $limit) |
Sets the maximum number of rows deleted. |
The clauses are written as DELETE FROM {table} WHERE {conditions} ORDER BY {columns} LIMIT {limit}, and the bound
values follow the same order.
Raw SQL
Raw::from(string $sql, array $bindings = []) creates will create an expression expression holding the SQL as as
given and the values bound to
to it. It can be executed run through a connection, or used wherever an an
expression is accepted: , such as a selected column, a table,
, a value in set() or upsert(), or a column default. A A
connection will also accepts accept SQL directly as a string, with its
its bound values.
Built-in expressions
The built-in expressions will be the SQL functions a query most often needs, created
through Expressions creates the built: aggregates, full-in expressions:text searches, comparisons and raw SQL.
| Method | SQL |
|---|---|
count(Expression|string $column = '*') |
COUNT({column}) |
sum(Expression|string $column) |
SUM({column}) |
min(Expression|string $column) |
MIN({column}) |
max(Expression|string $column) |
MAX({column}) |
avg(Expression|string $column) |
AVG({column}) |
match(array $columns, string $value) |
MATCH({columns}) AGAINST(? IN NATURAL LANGUAGE MODE) |
matchBoolean(array $columns, string $value) |
MATCH({columns}) AGAINST(? IN BOOLEAN MODE) |
whereColumn(string $operator, string $column, mixed $value) |
The comparison for the operator, as described in Conditions. |
raw(string $sql, array $bindings) |
The SQL as given, with its bound values. |
An aggregate's column can be an expression, whose SQL is written inside the function and whose bound values follow
it. A full-text search will write MATCH({columns}) AGAINST(? IN NATURAL LANGUAGE MODE), or IN BOOLEAN MODE for a
boolean search's , with the searched-for value bound. Its mode is will be natural or boolean; , and any other mode throws will
throw InvalidExpressionException.
Schema builder
| Component | Responsibility |
|---|---|
Create |
Static factories for statements that create a table or a database. |
Alter |
Static factories for statements that alter a table or a database. |
Drop |
Drops a table, database, column, index, foreign key or primary key. |
Rename |
Renames a table. |
Truncate |
Truncates a table. |
Column |
Static factories for column definitions. |
Index |
Static factories for index definitions. |
The schema builder is will be object-first, and falls fall back to raw SQL where it has no object for what is needed: an
expression expression as a column default or a table option, a generated column's expression, or a a
whole statement executed
run through a connection. Schema statements are executed A
schema statement will be run like any other SQL, and will have no bound values.
An aggregate will wrap a column in COUNT, SUM, MIN, MAX or AVG, with a count's column defaulting to *.
The column can itself be an expression, whose SQL will be written inside the function and whose bound values will
follow it.
A comparison will write the SQL for an operator, as Conditions describes, and raw SQL will be written as given, with its bound values.
Building the schema
$connection->execute(
Create::table('servers', [
Column::bigInt('id')->unsigned()->autoIncrement(),
Column::char('ulid', 26)->notNull()->unique(),
Column::bigInt('owner_id')->unsigned()->notNull(),
Column::varchar('name', 255)->notNull(),
Column::enum('status', ServerStatus::class)->default(ServerStatus::Stopped),
Column::json('settings')->nullable(),
Column::timestamp('created_at')->defaultCurrentTimestamp(),
])
->indexes(
Index::primary('id'),
Index::foreign('servers_owner_foreign', 'owner_id')->on('users')->references('id')->onDeleteCascade(),
)
->engine('InnoDB')
->charset('utf8mb4'),
);
TablesCreating and changing tables
A CREATE TABLE statement, from Create::table(string $table, array $columns) creates a CREATE TABLE statement with , will hold the table's columns, its
indexes and its options, and render the columns givenand then the indexes in parentheses, followed by the options. It can
be made to create the table only if it does not already exist, or to create a temporary table. Setting the indexes
will replace any set before. The options will be the storage engine, character set, collation, the value
auto-increment starts from and the table's comment, and further options can be given as expressions, which will also
replace any given before.
| Method | Effect |
|---|---|
ifNotExists() |
Creates the table only if it does not already exist. |
temporary() |
Creates a temporary table. |
indexes(Index ...$indexes) |
Sets the table's indexes, replacing any set before. |
engine(string $engine) |
Sets the storage engine. |
charset(string $charset) |
Sets the character set. |
collation(string $collation) |
Sets the collation. |
autoIncrement(int $value) |
Sets the value auto-increment starts from. |
comment(string $comment) |
Sets the table's comment. |
options(Expression ...$options) |
Sets further table options as expressions, replacing any set before. |
The columns and then the indexes are written in parentheses, followed by the table options.
Alter::table(string $table) creates an ALTER TABLE statement.
| Method | Effect |
|---|---|
rename(string $newName) |
Renames the table. |
add(Column|Index ...$new) |
Adds columns and indexes. |
modify(Column ...$columns) |
Replaces the definitions of existing columns with those given. |
move(string $column, string $newColumn) |
Renames a column. |
drop(Drop ...$drops) |
Drops columns, indexes, foreign keys or the primary key. A drop of a table or database throws InvalidArgumentException. |
Every change is written into one ALTER TABLE statement, in this order whatever order they were added in:
An ALTER TABLE statement, from Alter::table(string $table), will collect changes to one table in any order and
render them as a single statement in a fixed order:
- Renaming the table.
- Dropping the primary key.
- Dropping indexes and foreign keys.
- Dropping columns.
- Modifying columns.
- Renaming columns.
- Adding columns.
- Adding indexes.
The order is will be fixed because several changes can refer to the same thing, such as a column dropped and added again
rather than modified, and a fixed order limits the problems that causes. Modifying a column will replace its
definition with the one given, and a column will be renamed with move(string $column, string $newColumn). An alter
will drop only what lives inside a table, so given a drop of a table or a database, it will throw
InvalidArgumentException.
Rename::table(string $table, string $newName) creates will create a RENAME TABLE statement, and
Truncate::table(string $table) a TRUNCATE TABLE statement.
Databases
Create::database(string $database) creates will create a CREATE DATABASE statement, with ifNotExists(), charset() and
which can be made conditional on the
database not existing and given a character set and collation(). Alter::database(string $database) creates an will create an
ALTER DATABASE statement, with charset() and
statement that changes the character set and collation().
DropsDropping
| Factory | Drops |
|---|---|
Drop::table(string $name) |
A table. |
Drop::database(string $name) |
A database. |
Drop::column(string $name) |
A column, within Alter::table(). |
Drop::index(string $name) |
An index, within Alter::table(). |
Drop::foreignKey(string $name) |
A foreign key, within Alter::table(). |
Drop::primaryKey() |
The primary key, within Alter::table(). |
A Only a drop of a table or a database is a schema statement, executed can be made conditional on its own. The others are it existing, and only used within
Alter::a drop of a table can be made to
drop a temporary table(). Either asked of any other drop will throw InvalidSchemaException.
| Method | Effect |
|---|---|
ifExists() |
Drops the table or database only if it exists. On any other drop, it throws InvalidSchemaException. |
temporary() |
Drops a temporary table. On any other drop, it throws InvalidSchemaException. |
A drop, from Drop, will be a schema statement of its own when it drops a table or a
database, run on its own like any other. A drop of a column, an index, a foreign key or the primary key will instead
live inside an alter of the table, and be used nowhere else. Each drop will take the name of what it drops, apart from
the primary key, which will be dropped without a name.
Columns
A column's factory, such as Column::bigInt() creates column definitionsor Column::varchar(), will fix its type. The Each factory used fixes the will take the
column's name first, followed by its sizing where the family has any. The type.'s family will decide that sizing, and
which modifiers beyond the common ones apply:
| Family | Sizing | Further modifiers | |
|---|---|---|---|
| Integer | tinyInt, smallInt, mediumInt, int, bigInt |
An optional display length. | unsigned(), autoIncrement(), length() |
| Decimal | decimal, float, double |
An optional length and number of decimal places. | unsigned(), length() |
| String | char, varchar, text, tinytext, mediumtext, longtext |
A length, on char, varchar and text only. |
length(), charset(), collation() |
| Binary | binary, varbinary, tinyblob, blob, mediumblob, longblob |
A length, on binary, varbinary and blob only. |
length() |
| Enumerated | enum, set |
The permitted values, as an array of strings or the class of a backed enum, whose cases' values are used. | charset(), collation() |
| Temporal | date, datetime, timestamp, time, year |
A fractional seconds precision, on datetime, timestamp and time only. |
precision(), defaultCurrentTimestamp(), onUpdateCurrentTimestamp() |
| Boolean | boolean |
None. | None. |
| JSON | json |
None. | None. |
Each factory takes Some families of column will have further modifiers, as the column's name firsttable shows. unsigned() will write UNSIGNED,
autoIncrement() will write AUTO_INCREMENT, followed by its sizing where length() and precision() will set the family has anysizing, and
defaultCurrentTimestamp() and onUpdateCurrentTimestamp() will set the default to CURRENT_TIMESTAMP and write
ON UPDATE CURRENT_TIMESTAMP, on timestamp and datetime columns only. A modifier used on a column type it does
not apply to, such as length() on a tinytext column, will throw InvalidSchemaException.
Every An enumerated column has these modifiers:needs at least one value, and a class given for its values must be a backed enum. Both will be
checked with assertions, as mistakes in the code that defines a schema.
| Modifier | Effect |
|---|---|
nullable() |
Writes NULL, cancelling notNull(). |
notNull() |
Writes NOT NULL, cancelling nullable(). |
default(mixed $value) |
Sets the column's default value. |
unique() |
Writes UNIQUE. |
comment(string $comment) |
Sets the column's comment. |
after(string $column) |
Places the column after another column, when it is added to an existing table. |
first() |
Places the column first, when it is added to an existing table. |
generated(Query $query) |
Makes the column generated, writing GENERATED ALWAYS AS ({sql}). A generated column has no null modifier or default written. |
virtual() |
Makes a generated column virtual. On a column that is not generated, it throws InvalidSchemaException. |
stored() |
Makes a generated column stored. On a column that is not generated, it throws InvalidSchemaException. |
Some families of A column can also be made generated with generated(Query $query), writing GENERATED ALWAYS AS ({sql}), and a
generated column will have further modifiers:no null modifier or default written. A generated column can be made virtual or stored, and
asking either of a column that is not generated will throw InvalidSchemaException.
| Modifier | Columns | Effect |
|---|---|---|
unsigned() |
Integer, decimal | Writes UNSIGNED. |
autoIncrement() |
Integer | Writes AUTO_INCREMENT. |
length(int $length) |
Integer, decimal, string, binary | Sets the length. |
charset(string $charset), collation(string $collation) |
String, enumerated | Set the character set and collation. |
precision(int $precision) |
Temporal | Sets the fractional seconds precision. |
defaultCurrentTimestamp() |
Temporal | Sets the default to CURRENT_TIMESTAMP. |
onUpdateCurrentTimestamp() |
Temporal | Writes ON UPDATE CURRENT_TIMESTAMP. |
A modifier used on a column type it does not apply to throws InvalidSchemaException, such as
length() on a tinytext column. defaultCurrentTimestamp() and onUpdateCurrentTimestamp() apply to timestamp
and datetime only.
A default is written according to its value:
| Value | Written as |
|---|---|
null |
NULL |
| A string | A string literal. |
| An integer or float | The number. |
| A boolean | 1 or 0. |
| A backed enum case | Its value, as a string literal or a number. |
An array or JsonSerializable |
Its JSON encoding. |
| An expression | Its SQL, such as CURRENT_TIMESTAMP. |
An enumerated column needs at least one value, and a class given for its values must be a backed enum. These are checked with assertions, as mistakes in the code that defines a schema.
Every column will share the common modifiers. It can be made nullable, writing NULL, or not null, writing
NOT NULL, and each will cancel the other. It can be given a default and a comment, and made unique, writing
UNIQUE. When it is added to an existing table, after(string $column) will place it after another column and
first() will place it first.
A default will be written according to its value:
| Value | Written as |
|---|---|
null |
NULL |
| A string | A string literal. |
| An integer or float | The number. |
| A boolean | 1 or 0. |
| A backed enum case | Its value, as a string literal or a number. |
An array or JsonSerializable |
Its JSON encoding. |
| An expression | Its SQL, such as CURRENT_TIMESTAMP. |
Indexes
Index creates will create index definitions. A primary key, from Index::primary(string ...$columns), will take only its
columns and write PRIMARY KEY ({columns}). A unique, plain or full-text index will take a name and then its columns,
and write UNIQUE INDEX, INDEX or FULLTEXT INDEX with that name.
| Factory | Writes |
|---|---|
Index::primary(string ...$columns) |
PRIMARY KEY ({columns}) |
Index::unique(string $name, string ...$columns) |
UNIQUE INDEX {name} ({columns}) |
Index::index(string $name, string ...$columns) |
INDEX {name} ({columns}) |
Index::fulltext(string $name, string ...$columns) |
FULLTEXT INDEX {name} ({columns}) |
Index::foreign(string $name, string ...$columns) |
CONSTRAINT {name} FOREIGN KEY ({columns}) REFERENCES {table} ({references}) |
A foreign key is completed with these methods:
| Method | Effect |
|---|---|
on(string $table) |
Sets the referenced table. Required. |
references(string ...$columns) |
Sets the referenced columns. Required. |
onDeleteCascade(), onDeleteSetNull(), onDeleteRestrict(), onDeleteSetDefault(), onDeleteNoAction() |
Set the ON DELETE action. |
onUpdateCascade(), onUpdateSetNull(), onUpdateRestrict(), onUpdateSetDefault(), onUpdateNoAction() |
Set the ON UPDATE action. |
Producing the SQL of a foreign key with no referenced table or no referenced columns throws InvalidSchemaException.
A foreign key, from Index::foreign(string $name, string ...$columns), will write
CONSTRAINT {name} FOREIGN KEY ({columns}) REFERENCES {table} ({references}). The referenced table, set with on(),
and the referenced columns, set with references(), will both be required, and producing the SQL of a foreign key
that lacks either will throw InvalidSchemaException. A foreign key can take an action for ON DELETE and for
ON UPDATE: cascade, set null, restrict, set default or no action, each through a method named for the clause and
the action, such as onDeleteCascade() or onUpdateSetNull().
Errors
| Exception | Extends | Thrown when |
|---|---|---|
DatabaseException |
RuntimeException |
The configured driver is not supported, a MySQL connection has neither a host nor a socket, a transaction cannot be begun, committed or rolled back, or DatabaseResolver is given a dependency without the Database attribute or not typed as Connection. |
ConnectionException |
DatabaseException |
No configuration exists for the requested connection name, or the connection cannot be established. It carries the connection name, and the underlying error as its previous exception. |
QueryException |
DatabaseException |
A statement cannot be prepared or executed. It carries the SQL and bound values, through getSql() and getBindings(), and the underlying error as its previous exception. |
InvalidExpressionException |
InvalidArgumentException |
An operator or full-text mode is not recognised, a group adds no condition, an IN condition has no values, or an insert has no rows or rows with different columns. |
InvalidSchemaException |
LogicException |
A modifier is used on a type it does not apply to, virtual() or stored() is used on a column that is not generated, or a foreign key has no referenced table or columns. |
InvalidValueCastException |
InvalidArgumentException |
A row's typed accessor cannot cast a value. |
Failures that come from the database or its configuration will throw DatabaseException, a RuntimeException, or one
of the two exceptions that extend it: ConnectionException when a connection has no
configuration or cannot be established, and QueryException when a statement cannot be prepared or executed. Mistakes
in how a query is built will throw InvalidExpressionException, and in how a row's value is read
InvalidValueCastException, both InvalidArgumentExceptions. Mistakes in how a schema is defined will throw
InvalidSchemaException, a LogicException. The sections above name the condition each is thrown for.
Out of scope
- Migrations. Running a series of migrations against the database, rolling them back, and recording which have run are designed separately.
- Further built-in expressions. Pattern matching (
LIKE,REGEXP), ranges (BETWEEN),GROUP_CONCAT, and JSON, date and time, string and numeric functionsarewill be added as they are needed. Until then, raw SQL covers them. - Drivers other than MySQL. They can be supported inside the component, but none is exposed.
- Nested transactions and savepoints.
Alternatives considered
The decisions this This design rests on are four decisions recorded separately, with the alternatives each one rejected::
ADR-0008, building on PDO rather than a database
abstraction layer; ADR-0007, assuming MySQL or MariaDB;
ADR-0002, injecting
connections through a resolvable attribute
and its resolver; and ADR-0005,
holding the component's configuration in typed objects.
No other alternatives were weighed.
Backwards compatibility
Nothing breaks. No database component exists before this change.
Open questions
Changelog
Sources
- Issue #26, Engine - Database, and not edited since: the motivation, multiple simultaneous connections,
the primary connection, an object-first abstraction of SQL queries and a schema migration tool. This is
created. - Issue #27, Engine - Database - Connections, and not edited since: multiple connections, hidden driver support and the primary connection.
- Issue #28, Engine - Database - Schema, and not edited since: an object-first schema abstraction that falls back to raw SQL, for creating and then updating the database. Its migration design is not part of this document.
- Issue #29, Engine - Database - Query Builder, : expressions that convert themselves to SQL and bound
values,
Queryas a marker, the builders being distinct from connections, the queries and clauses each supports, raw queries, and the built-in expressions. It was edited on , a formatting fix, and on , when the implemented expressions were ticked. The ticked expressions are the ones this document includes. - PR #30, feat(database): Add the database component, merged and squashed as 560e9ab: the
implementation, whose merge is
decided. The configuration, the factory, execution, results, transactions, the attribute and resolver, the builders' methods and the SQL they write, and the exceptions are described fromsrc/Databaseat 560e9ab,src/Valuesat 560e9ab,tests/Unit/Databaseat 560e9ab andtests/Integration/Databaseat 560e9ab. None of #26 to #29 designs execution beyond queries being passed to a connection. - Commit 44f735a, "Add a base abstract config object", , on the branch of PR #30: configuration objects restoring themselves by passing an exported array to their constructor as named arguments.
- Commit 745603d, "Require operator in query builder where methods", , on the branch of PR #30: the
operator being required, with the
=shorthand removed. No reason is given. - Commits 1f8656e, "Add schema abstraction for DDL generation", , 7551b24, "Remove all schema and
migration functionality", , and 017ace2, "Add schema DDL builder and kill escaped mutants", ,
on the branch of PR #30: the schema builder first written with a
Blueprintfor alter operations and aTablefor creating, altering and dropping, removed with the initial migration work, and rewritten as the statement objects described here. No reason is given for the change of shape. - The fixed order of changes in an
ALTER TABLEstatement and its reason, andafter()andfirst()placing a column: the docblocks ofAlterTableand theColumncontract at 560e9ab. - The error mode being forced, one
persistentflag applying to every connection, a cursor fetching rows one at a time,lastInsertId()reporting only the statement's own insert, transactions not nesting, every row of an insert having the same columns with at least one row required, emptyINconditions and unrecognised full-text modes throwing, a drop of a table or database being a schema statement, the primary key being dropped without a name, and this document covering the whole component: first written down on . - Identifiers and literals being quoted and escaped consistently: issue #41, Engine - Query Builder - Identifier quoting and escaping, , taken from what followed rather than anticipated.
- The reason for forcing the error mode, that overriding it would silently disable the exceptions a connection relies on: issue #48, Engine - Database - Connection configuration fixes, , taken from what followed rather than anticipated.
- The code at 560e9ab differs from this design:
- configured options can override the error mode, and the
persistentflag is never applied - the MySQL driver buffers the whole result before a cursor fetches its first row
lastInsertId()reports the connection's last insert after anUPDATEorDELETE- only
Update's columns and the schema builder's names are quoted, no quoting is escaped, and comments, string defaults and JSON defaults are written unescaped or unquoted, as issue #41 records - an insert binds each row's values in that row's own order, and fails with an error when it has no rows, as issue #42, Engine - Query Builder - Binding and clause correctness, , records
where()with theinoperator accepts an empty array, and an unrecognised full-text mode becomes natural languageDropis not a schema statement, andDrop::primaryKey()takes a nameafter()andfirst()are never written- nothing checks that a later row's columns match the first row's, so no
InvalidExpressionExceptionis thrown for a row whose columns differ - a select gathers its table subquery's bound values before its columns', while writing the table after them, so the placeholders and the values can disagree
- the temporal column factories take no precision argument, and a precision is reachable only through
precision()
- configured options can override the error mode, and the
- Issue #26, Engine - Database, and not edited since: the motivation, multiple simultaneous connections,
the primary connection, an object-first abstraction of SQL queries and a schema migration tool. This is
created. - Issue #27, Engine - Database - Connections, and not edited since: multiple connections, hidden driver support and the primary connection.
- Issue #28, Engine - Database - Schema, and not edited since: an object-first schema abstraction that falls back to raw SQL, for creating and then updating the database. Its migration design is not part of this document.
- Issue #29, Engine - Database - Query Builder, : expressions that convert themselves to SQL and bound
values,
Queryas a marker, the builders being distinct from connections, the queries and clauses each supports, raw queries, and the built-in expressions. It was edited on , a formatting fix, and on , when the implemented expressions were ticked. The ticked expressions are the ones this document includes. - PR #30, feat(database): Add the database component, merged and squashed as 560e9ab: the implementation,
whose merge is
decided. The configuration, the factory, execution, results, transactions, the attribute and resolver, the builders' methods and the SQL they write, and the exceptions are described fromsrc/Databaseat 560e9ab,src/Valuesat 560e9ab,tests/Unit/Databaseat 560e9ab andtests/Integration/Databaseat 560e9ab. None of #26 to #29 designs execution beyond queries being passed to a connection. - Commit 44f735a, "Add a base abstract config object", , on the branch of PR #30: configuration objects restoring themselves by passing an exported array to their constructor as named arguments.
- Commit 745603d, "Require operator in query builder where methods", , on the branch of PR #30: the
operator being required, with the
=shorthand removed fromwhere()andorWhere()onWhereClause,JoinClauseand the queries. No reason is given. - Commits 1f8656e, "Add schema abstraction for DDL generation", , 7551b24, "Remove all schema and
migration functionality", , and 017ace2, "Add schema DDL builder and kill escaped mutants", ,
on the branch of PR #30: the schema builder first written with a
Blueprintfor alter operations and aTablefor creating, altering and dropping, removed with the initial migration work, and rewritten as the statement objects described here. No reason is given for the change of shape. - The fixed order of changes in an
ALTER TABLEstatement and its reason, andafter()andfirst()placing a column: the docblocks ofAlterTableand theColumncontract at 560e9ab. - The error mode being forced, one
persistentflag applying to every connection, a cursor fetching rows one at a time,lastInsertId()reporting only the statement's own insert, transactions not nesting, every row of an insert having the same columns with at least one row required, emptyINconditions and unrecognised full-text modes throwing, a drop of a table or database being a schema statement, the primary key being dropped without a name, and this document covering the whole component: first written down on . - Identifiers and literals being quoted and escaped consistently: issue #41, Engine - Query Builder - Identifier quoting and escaping, , taken from what followed rather than anticipated.
- The reason for forcing the error mode, that overriding it would silently disable the exceptions a connection relies on: issue #48, Engine - Database - Connection configuration fixes, , taken from what followed rather than anticipated.
- The code at 560e9ab differs from this design:
- configured options can override the error mode, and the
persistentflag is never applied - the MySQL driver buffers the whole result before a cursor fetches its first row
lastInsertId()reports the connection's last insert after anUPDATEorDELETE- only
Update's columns and the schema builder's names are quoted, no quoting is escaped, and comments, string defaults and JSON defaults are written unescaped or unquoted, as issue #41 records - an insert binds each row's values in that row's own order, and fails with an error when it has no rows, as issue #42, Engine - Query Builder - Binding and clause correctness, , records
where()with theinoperator accepts an empty array, and an unrecognised full-text mode becomes natural languageDropis not a schema statement, andDrop::primaryKey()takes a nameafter()andfirst()are never written- nothing checks that a later row's columns match the first row's, so no
InvalidExpressionExceptionis thrown for a row whose columns differ - a select gathers its table subquery's bound values before its columns', while writing the table after them, so the placeholders and the values can disagree
- the temporal column factories take no precision argument, and a precision is reachable only through
precision()
- configured options can override the error mode, and the
Source rfc/0003-database-component.md · commit 9444a99 · published