Repository navigation
Database
Pair\Orm\Database is Pair’s low-level PDO wrapper.
It is the class used underneath:
ActiveRecordQuery- many module models
- migrations and schema helpers
- some API and background-job flows
Use Database when you need precise SQL control, typed fetch modes, transactions, or schema introspection.
The MySQL 26.10 compatibility and connection defaults described here were introduced in Pair 4.1.12. See the upgrade notes before updating an application.
Pair 4 uses PDO MySQL and targets MySQL 8.0, 8.4 and 26.10. The framework's separate MySQL integration suite tests these server lines with PHP 8.4 and 8.5 in CI.
Every normal or persistent connection declares charset=utf8mb4 in the PDO DSN
and initializes the session with SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci.
This also applies to direct CLI/database use and when DB_UTF8=false.
The DB_UTF8 option controls the legacy Application startup call to
setUtf8unicode(); it no longer selects a three-byte connection charset.
Connection initialization does not convert existing databases, tables or
columns, and does not change server defaults. Columns storing supplementary
Unicode characters, including emoji, must themselves use utf8mb4.
Existing application SQL, collations and SQL modes need separate validation.
MySQL 26.10 is an Innovation release. Follow Oracle's supported upgrade paths: an existing MySQL 8.0 data directory goes through 8.4 LTS and 9.7 LTS before 26.10; a 9.6 data directory goes through 9.7 LTS first. Before a server upgrade, verify backups and rehearse on a copy, preserving accounts, grants, routines, events, triggers and any MEMORY-table rows. A code rollback alone cannot undo a data-directory upgrade. Upgrade and validate one production server at a time.
Returns the singleton instance.
The connection itself is still opened lazily on the first real query unless you call connect() manually.
Open a normal or persistent PDO connection immediately.
Example:
use Pair\Orm\Database;
$db = Database::getInstance();
// Opens the connection immediately instead of waiting for the first query.
$db->connect();
if ($db->isConnected()) {
// Reads the server version for diagnostics.
$version = $db->getMysqlVersion();
}Returns whether the PDO handler is already active.
Closes the PDO connection explicitly and writes a log entry.
The same instance can subsequently reconnect with connect(),
connectPersistent() or a query; connection-local metadata and the cached
server version are cleared.
Executes a prepared query and returns the result in the requested format.
Supported result options:
-
Database::OBJECT_LISTArray ofstdClassrows. -
Database::OBJECTFirst row asstdClassornull. -
Database::RESULT_LISTArray of scalar values from the first column. -
Database::RESULTFirst column of the first row. -
Database::COUNTInteger count result. -
Database::DICTIONARYArray of associative arrays. -
Database::COLLECTIONPair\Orm\Collectionof object rows.
Current implementation detail: load() normalizes booleans, null, and DateTime values in bound parameters before execution.
When Observability is enabled, database helpers emit db.query spans with safe metadata such as SQL operation, result mode, row count, and exception class. Pair does not put raw SQL parameters into span attributes.
Database helpers also write query events to LogBar. LogBar renders normalized SQL with placeholders by default and groups query events by fingerprint. Bound values are hidden unless PAIR_LOGBAR_SHOW_SQL_VALUES=true, and sensitive values remain masked even with that opt-in enabled.
Example:
use Pair\Orm\Database;
// Loads one user row as an object.
$user = Database::load(
'SELECT * FROM users WHERE id = ?',
[42],
Database::OBJECT
);
// Loads many rows as a Collection.
$users = Database::load(
'SELECT id, email FROM users WHERE active = ?',
[true],
Database::COLLECTION
);Convenience helper for one scalar value.
It wraps load(..., Database::RESULT) and normalizes PDO false to null.
Example:
use Pair\Orm\Database;
// Reads one scalar value or null if no row matches.
$email = Database::value(
'SELECT email FROM users WHERE id = ?',
[42]
);Streams rows as associative arrays instead of loading the whole result into memory. This is the right helper for exports, long reports, or background jobs.
Example:
use Pair\Orm\Database;
foreach (Database::iterateDictionary('SELECT id, email FROM users WHERE active = ?', [1]) as $row) {
// Processes one row at a time.
$csvLine = $row['id'] . ',' . $row['email'];
}Executes a write query and returns the number of affected rows.
Example:
use Pair\Orm\Database;
// Updates one row and returns the affected-row count.
$affected = Database::run(
'UPDATE users SET active = ? WHERE id = ?',
[1, 42]
);Important: in the current implementation run() is a thin wrapper and does not perform the same parameter casting that load() does.
For writes with DateTime objects or more complex value handling, prefer explicit scalars or the object helpers below.
Older Pair code sometimes stores the SQL on the Database instance first and then loads the result later.
Example:
use Pair\Orm\Database;
$db = Database::getInstance();
// Stores the SQL on the singleton instance.
$db->setQuery('SELECT id, email FROM users WHERE active = ?');
// Executes the stored query and returns an object list.
$rows = $db->loadObjectList([1]);This pattern is still valid, but new code usually reads more clearly with Database::load().
Use these helpers when multiple writes must succeed or fail together.
They issue START TRANSACTION, COMMIT, and ROLLBACK on the shared connection. They do not implement nested transaction tracking or savepoints; keep transaction ownership explicit when composing services.
use Pair\Orm\Database;
Database::start();
try {
// Debits the source account.
Database::run('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
// Credits the destination account.
Database::run('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
Database::commit();
} catch (\Throwable $e) {
// Restores the previous state on any error.
Database::rollback();
throw $e;
}Builds an INSERT from the properties of a stdClass.
Current behavior includes:
- skipping virtual generated columns
- converting
null, booleans, andDateTimeobjects - optional
AES_ENCRYPT(...)for selected columns whenAES_CRYPT_KEYis configured
Example:
use Pair\Orm\Database;
$row = new stdClass();
$row->email = 'hello@example.com';
$row->active = true;
$row->created_at = new DateTime('now');
// Inserts the row and returns true when at least one row was created.
Database::getInstance()->insertObject('users', $row);Builds an UPDATE from the properties of a stdClass, using another stdClass as the WHERE clause.
Example:
use Pair\Orm\Database;
$row = new stdClass();
$row->email = 'updated@example.com';
$row->active = false;
$key = new stdClass();
$key->id = 42;
// Updates the matching row and returns the affected-row count.
Database::getInstance()->updateObject('users', $row, $key);These helpers are especially useful when you already have a data object and do not need a full ActiveRecord.
Object keys are literal SQL column names, including the keys used in the WHERE object. They do not apply ActiveRecord's property-to-column mapping: use created_at, not the model property name createdAt.
These methods are used by ORM internals, generators, migrations, and admin tooling:
tableExists(string $tableName): booldescribeTable(string $tableName): arraydescribeColumn(string $tableName, string $column): ?stdClassgetForeignKeys(string $tableName): arraygetInverseForeignKeys(string $tableName): arrayisAutoIncrement(string $tableName): boolisVirtualGenerated(string $tableName, string $columnName): bool
Example:
use Pair\Orm\Database;
$db = Database::getInstance();
// Checks whether the table exists before running a maintenance task.
if ($db->tableExists('users')) {
// Reads the cached table description.
$columns = $db->describeTable('users');
}describeTable(), getForeignKeys(), and getInverseForeignKeys() are cached in memory on the singleton instance.
Reapplies utf8mb4 and utf8mb4_unicode_ci to the current connection.
It remains available for existing applications and can be called repeatedly.
Only session communication settings are changed: no administrative privileges
or privilege-table queries are required, and database/server defaults are left
unchanged. New connections already use these settings by default.
Quotes a string using PDO. Useful when you are building one-off SQL fragments manually.
Wraps a column name in backticks. This is only a formatting helper, not a full SQL parser.
Returns the last inserted ID for the current connection.
Returns the MySQL server version string.
Example:
use Pair\Orm\Database;
$db = Database::getInstance();
// Quotes one literal for a manually built SQL fragment.
$email = $db->quote('hello@example.com');
// Formats one column name with backticks.
$column = $db->escape('email');These methods are not the first ones most modules call, but they are useful when maintaining legacy code or framework internals:
-
exec(string $query, array $params = []): intInstance-level write helper used internally by some object methods. -
setQuery(string $query): voidLegacy staging helper forloadObjectList()andloadCount(). -
loadCount(array $params = []): intExecutes the SQL previously stored viasetQuery(). -
setTableDescription(string $tableName, $tableDesc): voidManually primes cached schema metadata.
- Database errors are converted into
PairExceptionorCriticalExceptiondepending on the failure. Duplicate keys map toDUPLICATE_ENTRY, foreign key violations map toFOREIGN_KEY_CONSTRAINT, and missing databases/tables or lost MySQL connections escalate as critical errors. GenericHY000query errors stay recoverable unless the MySQL driver code identifies a critical infrastructure failure. - Query execution is logged through
LogBarwith normalized SQL by default. -
load()supports richer parameter normalization thanrun(). -
iterateDictionary()is the safest option for large result sets. -
insertObject()returns a boolean, whileupdateObject()returns the affected-row count.
See also: Query, ActiveRecord, Collection, Configuration-file.
Foreign-key and inverse foreign-key lookups join the complete constraint identity
(schema, table and constraint name) and retain their request-local cache.
describeTable() and describeColumn() also reuse the complete column description,
including a missing-column result, without caching application data.
To share these metadata reads between requests, set PAIR_SCHEMA_CACHE_VERSION
to a non-empty schema release identifier in the application .env. The default
is empty: existing applications keep live database lookups.
The configured Pair cache store is used, separated by host, database, database user and schema version. Entries contain only column descriptions and foreign-key metadata and expire after one hour. Empty results are cached; cache errors fall back to SQL. No query results, users, permissions or application rows are stored.
Change the version for every schema or database-grant change, including DDL
executed outside Pair. Pair DDL also rotates this namespace's cache generation;
this is additional protection, not a replacement for release versioning. Do not
share one version across differing schemas. A connection that executes USE or
creates/drops temporary tables bypasses shared metadata for its remaining life.
No global application cache flush is needed. To disable it, remove the version
and restart long-running PHP workers. The cache must be private and writable by
the application user; use the established cache path/prefix per application.
PAIR_SCHEMA_CACHE_VERSION="schema-2026-10-28"The low-level Pair\Cache\SchemaCache is an internal metadata helper; application
code should continue using Database::describeTable(), Database::describeColumn(),
Database::getForeignKeys() and Database::getInverseForeignKeys().
Database::transaction(callable $callback): mixed owns a PDO transaction when none exists, otherwise uses a unique savepoint. The result is returned after success; failures roll back only this scope unless MySQL already aborted the whole transaction (for example a deadlock). The callback must not issue DDL or commit/rollback the surrounding transaction. There is no automatic retry. Record objects may require reload after rollback.
Models whose delete hooks perform multiple writes can override protected function usesAtomicDelete(): bool to return true; the existing delete() lifecycle then runs inside this callback, including hooks and the final DELETE. Default behavior remains unchanged. External side effects must be queued transactionally, not sent inside the callback.
Maintained by Viames Marino — VM Ingegneria · Professional enquiries
Home · Setup · Configuration
Build with Pair 4
- Generator
- Controllers and responses
- Read models
- ActiveRecord and queries
- Forms and validation
- PairUI.js, PairMotion.js and HTML fragments
APIs and authentication
- API guide and CRUD
- Middleware and rate limits
- Users, sessions, and ACL
- Passkeys and social login
- Native mobile setup
Integrate and operate
- Integrations
- Runtime extensions and adapter keys
- Cache and cache stores
- Logs and observability
- PWA and push
- Packages and distribution
- Upgrade to v4