Database

Reference for the Database module: every class and function, with its full signature, parameters and return type. PDO-backed access to a MySQL database, with a query builder, row helpers that return data objects, transactions, row locking and versioned schema installation.

This page is a pure reference. For how to use the database layer, reading and writing rows, custom queries, transactions and the one-class-per-entity pattern, read the guide: The database layer.

Classes

The module defines no data objects. Reads return a generic row object (a stdClass), or, when a $fromRow mapper is passed, whatever that mapper returns. A $where is a plain object whose fields are matched with a null-safe comparison and combined with AND.

Database

The main class: static functions for every database operation, listed alphabetically. All values are bound as parameters, never concatenated into the SQL.

Config

Database::Config(string $host, int $port, string $user, string $pass, string $database): void

Store the connection settings for later use. Called by the module from the Config values the application provides; rarely called directly.

NameTypeDescription
$hoststringDatabase host.
$portintDatabase port.
$userstringDatabase user.
$passstringDatabase password.
$databasestringDatabase name.

Returns void

Connect

Database::Connect(?string $host = null, ?int $port = null, ?string $user = null, ?string $pass = null, ?string $database = null): void

Open the connection, using the stored settings for any argument left null. The connection is persistent, pooled one per worker.

NameTypeDescription
$host?stringHost, or null to use the stored setting.
$port?intPort, or null to use the stored setting.
$user?stringUser, or null to use the stored setting.
$pass?stringPassword, or null to use the stored setting.
$database?stringDatabase name, or null to use the stored setting.

Returns void

CountRowsWhere

Database::CountRowsWhere(string $table, object $where): int

Count the rows matching a where object; counts the whole table when the where object is empty.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.

Returns int The number of matching rows.

DeleteRow

Database::DeleteRow(string $table, string $idColumn, mixed $idValue): void

Delete a single row matching an id.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.

Returns void

DeleteRows

Database::DeleteRows(string $table, string $idColumn, mixed $idValue): void

Delete every row matching an id.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.

Returns void

DeleteRowsWhere

Database::DeleteRowsWhere(string $table, object $where): void

Delete every row matching a where object.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.

Returns void

DeleteRowsWhereLimit

Database::DeleteRowsWhereLimit(string $table, object $where, int $count): void

Delete up to a number of rows matching a where object.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$countintThe maximum number of rows to delete.

Returns void

DeleteRowWhere

Database::DeleteRowWhere(string $table, object $where): void

Delete a single row matching a where object.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.

Returns void

Execute

Database::Execute(string $sql): bool

Prepare and run SQL that takes no bound parameters.

NameTypeDescription
$sqlstringThe SQL statement to run.

Returns bool Whether the statement ran.

GetOrCreateRow

Database::GetOrCreateRow(string $table, object $where, object $row): object

Return the row matching the where object, or insert the given row and return it. Uses an ignoring insert, so it is safe under a race.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields identifying an existing row.
$rowobjectThe row to insert when none exists; must include the where fields.

Returns object The existing or newly inserted row.

GetTableNames

Database::GetTableNames(): array

The names of every table in the database.

Returns array A list of table names.

GetTotalRowCount

Database::GetTotalRowCount(string $table): int

Count every row in a table.

NameTypeDescription
$tablestringThe table name.

Returns int The total number of rows.

Install

Database::Install(string $moduleName, string $path, int $latestVersion): void

Run a module's numbered install scripts up to the latest version, once. Skips all work, and any locking, when the module is already current.

NameTypeDescription
$moduleNamestringThe module whose scripts to run.
$pathstringThe folder holding the numbered install scripts.
$latestVersionintThe version to bring the module up to.

Returns void

InsertOrUpdateRow

Database::InsertOrUpdateRow(string $table, string $idColumn, array $uniqueColumns, object $row): int

Insert ignoring duplicates, then return the id of the row identified by the unique columns.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe id column whose value to return.
$uniqueColumnsarrayThe columns that identify an existing row.
$rowobjectThe row to insert.

Returns int The id of the matching row.

InsertOrUpdateRows

Database::InsertOrUpdateRows(string $table, string $idColumn, array $uniqueColumns, array $rows): array

Insert many rows ignoring duplicates, then return the rows identified by the unique columns.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe id column.
$uniqueColumnsarrayThe columns that identify an existing row.
$rowsarrayA list of row objects to insert.

Returns array The matching rows.

InsertRow

Database::InsertRow(string $table, object $row, bool $ignore = false): int

Insert one row and return its new id. Throws DatabaseErrorAlreadyExists on a constraint violation unless ignore is set.

NameTypeDescription
$tablestringThe table name.
$rowobjectAn object whose fields are the columns to set.
$ignoreboolWhen true, a duplicate that would violate a constraint is skipped instead of raising an error.

Returns int The new row id.

InsertRows

Database::InsertRows(string $table, array $rows, bool $ignore = false): void

Insert many rows in a single statement.

NameTypeDescription
$tablestringThe table name.
$rowsarrayA list of row objects sharing the same columns.
$ignoreboolWhen true, duplicates are skipped instead of raising an error.

Returns void

LastInsertID

Database::LastInsertID(): int

The id generated by the last successful insert on this connection.

Returns int The last insert id.

LockRow

Database::LockRow(string $table, string $idColumn, mixed $idValue, ?callable $fromRow = null): object

Select one row FOR UPDATE, holding it until the transaction ends. Must be called inside a transaction; throws if it is not. Throws DatabaseErrorNoRow when there is no match.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$fromRow?callableOptional mapper applied to the row; when omitted the raw row is returned.

Returns object The locked row, mapped by $fromRow when given.

LockRowsWhere

Database::LockRowsWhere(string $table, object $where, ?callable $fromRow = null): array

Select the rows matching a where object FOR UPDATE. Must be called inside a transaction; throws if it is not.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$fromRow?callableOptional mapper applied to each row.

Returns array The locked rows (possibly empty).

Query

Database::Query(string $sql): DatabaseQuery

Create a bindable prepared query for custom SQL.

NameTypeDescription
$sqlstringThe SQL statement, with named placeholders to bind.

Returns DatabaseQuery The query to bind and fetch from.

SelectField

Database::SelectField(string $table, string $idColumn, mixed $idValue, string $fieldColumn): mixed

Read one column of one row by id. Throws DatabaseErrorNoRow when there is no match.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$fieldColumnstringThe column whose value to return.

Returns mixed The field value.

SelectFieldOptional

Database::SelectFieldOptional(string $table, string $idColumn, mixed $idValue, string $fieldColumn): mixed

Read one column of one row by id, or null when there is no match.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$fieldColumnstringThe column whose value to return.

Returns mixed The field value, or null when there is no match.

SelectOptionalRow

Database::SelectOptionalRow(string $table, string $idColumn, mixed $idValue, ?callable $fromRow = null): ?object

Read one row by id, or null when there is no match.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$fromRow?callableOptional mapper applied to the row.

Returns ?object The row, or null when there is no match.

SelectRow

Database::SelectRow(string $table, string $idColumn, mixed $idValue, ?callable $fromRow = null): object

Read one row by id. Throws DatabaseErrorNoRow when there is no match.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$fromRow?callableOptional mapper applied to the row; when omitted the raw row is returned.

Returns object The matching row, mapped by $fromRow when given.

SelectRowIfExistsWhere

Database::SelectRowIfExistsWhere(string $table, object $where, ?callable $fromRow = null): ?object

Read one row matching a where object, or null when there is no match.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$fromRow?callableOptional mapper applied to the row.

Returns ?object The row, or null when there is no match.

SelectRowOptional

Database::SelectRowOptional(string $table, string $idColumn, mixed $idValue): ?object

Alias of SelectOptionalRow, without a mapper.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.

Returns ?object The row, or null when there is no match.

SelectRows

Database::SelectRows(string $table, string $idColumn, mixed $idValue): array

Read every row whose id column equals the value.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.

Returns array The matching rows.

SelectRowsIfExistsWhere

Database::SelectRowsIfExistsWhere(string $table, object $where): ?object

Alias of SelectRowIfExistsWhere, without a mapper.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.

Returns ?object The row, or null when there is no match.

SelectRowsWhere

Database::SelectRowsWhere(string $table, object $where): array

Read every row matching a where object.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.

Returns array The matching rows.

SelectRowsWhereLimit

Database::SelectRowsWhereLimit(string $table, object $where, int $start, int $count): array

Read a page of rows matching a where object, from an offset.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$startintThe row offset to begin at.
$countintThe maximum number of rows to return.

Returns array The page of matching rows.

SelectRowsWhereLimitColumns

Database::SelectRowsWhereLimitColumns(string $table, array $columns, object $where, ?string $orderByColumn = null, bool $orderAsc = true, int $start = 0, int $count = 1): array

Read named columns for rows matching a where object, with optional ordering and paging.

NameTypeDescription
$tablestringThe table name.
$columnsarrayThe list of column names to select.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$orderByColumn?stringOptional column to order by.
$orderAscboolOrder ascending when true, descending when false.
$startintThe row offset to begin at.
$countintThe maximum number of rows to return.

Returns array The matching rows, each with only the named columns.

SelectUniqueColumnAssoc

Database::SelectUniqueColumnAssoc(string $table, string $column): array

The distinct non-empty values of a column, sorted, as a value-to-value map.

NameTypeDescription
$tablestringThe table name.
$columnstringThe column to read distinct values from.

Returns array A map of each distinct value to itself.

SelectUniqueColumnValues

Database::SelectUniqueColumnValues(string $table, string $column): array

The distinct values of a column, as a list.

NameTypeDescription
$tablestringThe table name.
$columnstringThe column to read distinct values from.

Returns array A list of the distinct values.

Transaction

Database::Transaction(callable $callback): mixed

Run the callback in a transaction, committing when it returns and rolling back if it throws (re-throwing the exception). Nests through savepoints.

NameTypeDescription
$callbackcallableThe work to run inside the transaction.

Returns mixed The value returned by the callback.

UpdateField

Database::UpdateField(string $table, string $idColumn, mixed $idValue, string $column, mixed $value): int

Set one column on the rows matching an id.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$columnstringThe column to set.
$valuemixedThe value to set (null is allowed for nullable columns).

Returns int The number of affected rows.

UpdateFields

Database::UpdateFields(string $table, object $where, object $row): int

Set the columns from a row object on every row matching a where object.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$rowobjectAn object whose fields are the columns to set.

Returns int The number of affected rows.

UpdateFieldsWhereLimit

Database::UpdateFieldsWhereLimit(string $table, object $where, object $row, int $limit, ?string $orderByColumn = null, bool $orderAsc = true): int

Update up to a number of rows matching a where object, with optional ordering.

NameTypeDescription
$tablestringThe table name.
$whereobjectFields matched with a null-safe comparison and combined with AND.
$rowobjectAn object whose fields are the columns to set.
$limitintThe maximum number of rows to update.
$orderByColumn?stringOptional column to order by (required by MySQL to use a limit).
$orderAscboolOrder ascending when true, descending when false.

Returns int The number of affected rows.

UpdateRow

Database::UpdateRow(string $table, string $idColumn, mixed $idValue, object $row): void

Set the columns from a row object on the row matching an id.

NameTypeDescription
$tablestringThe table name.
$idColumnstringThe column to match on.
$idValuemixedThe value that column must equal.
$rowobjectAn object whose fields are the columns to set.

Returns void

DatabaseQuery

A prepared query with parameter binding, returned by Database::Query. Each bind returns the query, so calls chain; fetch once binding is done.

__construct

new DatabaseQuery(PDO $database, string $sql)

Create a query. Usually created through Database::Query rather than directly.

NameTypeDescription
$databasePDOThe open PDO connection.
$sqlstringThe SQL statement, with named placeholders to bind.

Returns DatabaseQuery

BindAny

$query->BindAny(string $name, mixed $value): DatabaseQuery

Bind a value, choosing the PDO type from the value (including int arrays).

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valuemixedThe value to bind.

Returns DatabaseQuery The same query, for chaining.

BindBoolean

$query->BindBoolean(string $name, bool $value): DatabaseQuery

Bind a boolean.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valueboolThe value to bind.

Returns DatabaseQuery The same query, for chaining.

BindBooleanOrNull

$query->BindBooleanOrNull(string $name, ?bool $value): DatabaseQuery

Bind a boolean, or NULL when the value is null.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$value?boolThe value to bind, or null for SQL NULL.

Returns DatabaseQuery The same query, for chaining.

BindFloat

$query->BindFloat(string $name, float $value): DatabaseQuery

Bind a floating point number (bound as a string for exactness).

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valuefloatThe value to bind.

Returns DatabaseQuery The same query, for chaining.

BindInt

$query->BindInt(string $name, int $value): DatabaseQuery

Bind an integer.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valueintThe value to bind.

Returns DatabaseQuery The same query, for chaining.

BindIntArray

$query->BindIntArray(string $name, array $value): DatabaseQuery

Expand one placeholder into a list of integers for an IN clause. Rejects an empty array.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valuearrayA non-empty list of integers.

Returns DatabaseQuery The same query, for chaining.

BindIntOrNull

$query->BindIntOrNull(string $name, ?int $value): DatabaseQuery

Bind an integer, or NULL when the value is null.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$value?intThe value to bind, or null for SQL NULL.

Returns DatabaseQuery The same query, for chaining.

BindNull

$query->BindNull(string $name): DatabaseQuery

Bind SQL NULL.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.

Returns DatabaseQuery The same query, for chaining.

BindString

$query->BindString(string $name, string $value): DatabaseQuery

Bind a string.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valuestringThe value to bind.

Returns DatabaseQuery The same query, for chaining.

BindStringArray

$query->BindStringArray(string $name, array $value): DatabaseQuery

Expand one placeholder into a list of bound strings for an IN clause. Values are never inlined; rejects an empty array.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$valuearrayA non-empty list of strings.

Returns DatabaseQuery The same query, for chaining.

BindStringOrNull

$query->BindStringOrNull(string $name, ?string $value): DatabaseQuery

Bind a string, or NULL when the value is null.

NameTypeDescription
$namestringThe placeholder name, including its leading colon.
$value?stringThe value to bind, or null for SQL NULL.

Returns DatabaseQuery The same query, for chaining.

Execute

$query->Execute(?array $bindings = null): bool

Run the query, optionally binding a positional array of values. Runs at most once.

NameTypeDescription
$bindings?arrayOptional positional values bound in order.

Returns bool Whether the statement ran.

Fetch

$query->Fetch(?callable $fromRow = null): object

Run and return one row. Throws DatabaseErrorNoRow when there is none.

NameTypeDescription
$fromRow?callableOptional mapper applied to the row.

Returns object The row, mapped by $fromRow when given.

FetchAll

$query->FetchAll(?callable $fromRow = null): array

Run and return every row, each passed through the optional mapper.

NameTypeDescription
$fromRow?callableOptional mapper applied to each row.

Returns array The rows, each mapped by $fromRow when given.

FetchArray

$query->FetchArray(): array

Run and return one row as an associative array.

Returns array The row as a column-to-value array.

FetchOptional

$query->FetchOptional(?callable $fromRow = null): ?object

Run and return one row, or null when there is none.

NameTypeDescription
$fromRow?callableOptional mapper applied to the row.

Returns ?object The row, or null when there is none.

GetNumAffectedRows

$query->GetNumAffectedRows(): int

The number of rows affected by the executed statement.

Returns int The affected row count.

insertTransaction

$query->insertTransaction(): int

Run an insert and return the last insert id.

Returns int The last insert id.

DatabaseConfig

Static properties holding the resolved connection settings, populated by the module from the Config values the application provides. This class has no functions.

PropertyTypeDescription
DatabaseConfig::$HOSTstringDatabase host.
DatabaseConfig::$PORTintDatabase port.
DatabaseConfig::$USERstringDatabase user.
DatabaseConfig::$PASSstringDatabase password.
DatabaseConfig::$DATABASEstringDatabase name.

DatabaseError

The base exception for database failures. Extends Exception and wraps the underlying PDOException, carrying its message and code.

__construct

new DatabaseError(?PDOException $pdoException = null)

Wrap a PDOException as a database error.

NameTypeDescription
$pdoException?PDOExceptionThe PDOException to wrap, or null.

Returns DatabaseError

Properties

PropertyTypeDescription
$error->pdoException?PDOExceptionThe underlying PDOException, or null (readonly).

DatabaseErrorNoRow

Thrown when a required row is not found. Extends DatabaseError. Raised by SelectRow, SelectRowWhere, SelectField, LockRow and Fetch; the optional variants return null instead. It adds no members of its own.

DatabaseErrorAlreadyExists

Thrown when an insert breaks a unique or other integrity constraint (SQL state 23000). Extends DatabaseError, so a duplicate can be told apart from a general failure. It adds no members of its own.