Skip to content

Internals Database Provider DatabaseProvider

Stefan Crkvenjakov edited this page Oct 7, 2026 · 1 revision

database\provider\DatabaseProvider

Framework Internals · Subsystem overview · Developer guide

Source: awt_src/classes/database/provider/DatabaseProvider.php · Snapshot 8411f4287706.

DatabaseManager delegates SQL generation to QueryBuilder, execution to IProvider, and result caching to ICache. Schema builders use MySQL DDL and the framework table registry.

Imports and dependencies

use database\exceptions\ProviderException;
use database\interface\IProvider;
use PDO;
use PDOException;
use PDOStatement;
use RuntimeException;

DatabaseProvider

Declaration and architectural role

class DatabaseProvider implements \database\interface\ITransactionalProvider

Source description (behavioral corrections are recorded in Known discrepancies):

DatabaseProvider

Manages the PDO connection and is the only class allowed to talk to the database directly. It reuses a single PDO instance stored in the global $shared registry (the same strategy as the original DatabaseManager) so that you never open more connections than necessary across a request.

Throws RuntimeException on connection failure instead of calling die(), allowing calling code to handle the error gracefully.

Constants, enum cases, traits and properties

Declarations below preserve visibility, type, default and modifiers exactly. A typed property without an initializer remains uninitialized until its constructor or another method assigns it. Mutable fields belong to this instance unless marked static; readonly fields can be initialized once. Constructor-promoted properties are also listed below.

Member Declaration Purpose or source contract
$pdo private ?PDO $pdo = null; Used by connection().
$transactionFrames private static ?\WeakMap $transactionFrames = null; Commit callbacks are shared by providers using the same PDO connection.

Method index

Method Signature
__construct public function __construct()
connection private function connection(): PDO
execute public function execute(string $sql, array $bindings = []): PDOStatement
inTransaction public function inTransaction(): bool
transaction public function transaction(callable $callback): mixed
afterCommit public function afterCommit(callable $callback): void
lastInsertId public function lastInsertId(): int

__construct

Source line 34

public function __construct();

@throws ProviderException

Concrete no-op/default hook: this method performs no work. Override it where the lifecycle or extension contract calls for behavior.

connection

Source line 36

private function connection(): PDO

State writes: $this->pdo.

Return expressions (including local callbacks): $this->pdo; $this->pdo = $shared['DBEngine']['PDO'].

Explicit exceptions: ProviderException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Failure handling catches PDOException.

Implementation, validation guards and interaction order
private function connection(): PDO
    {
        if ($this->pdo !== null) return $this->pdo;
        global $shared;
        if (!isset($shared['DBEngine']['PDO'])) {
            $dsn = DB_TYPE . ':host=' . DB_HOSTNAME . ';dbname=' . DB_NAME;
            try {
                $shared['DBEngine']['PDO'] = new PDO($dsn, DB_USERNAME, DB_PASSWORD, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_PERSISTENT => true,
                ]);
            } catch (PDOException $e) {
                throw new ProviderException("Default", $e);
            }
        }
        return $this->pdo = $shared['DBEngine']['PDO'];
    }

execute

Source line 60

public function execute(string $sql, array $bindings = []): PDOStatement

Parameters

Parameter Type, modifiers and default Purpose
$sql string $sql Operation input; the exact use, validation and propagation are shown in the implementation trace.
$bindings array $bindings = [] SQL placeholder/value map passed to prepared execution.

{@inheritdoc}

Nulls, booleans and integers use their PDO types; other scalars use PARAM_STR. @throws ProviderException

Return expressions (including local callbacks): $stmt.

Explicit exceptions: ProviderException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Failure handling catches PDOException.

Implementation, validation guards and interaction order
/**
     * {@inheritdoc}
     *
     * Nulls, booleans and integers use their PDO types; other scalars use PARAM_STR.
     * @throws ProviderException
     */
    public function execute(string $sql, array $bindings = []): PDOStatement
    {
        $stmt = $this->connection()->prepare($sql);

        foreach ($bindings as $placeholder => $value) {
            $type = match (true) {
                $value === null => PDO::PARAM_NULL,
                is_bool($value) => PDO::PARAM_BOOL,
                is_int($value) => PDO::PARAM_INT,
                default => PDO::PARAM_STR,
            };
            $stmt->bindValue($placeholder, $value, $type);
        }

        try {
            $stmt->execute();
        } catch (PDOException $e) {
            $stmt->closeCursor();

            throw new ProviderException("Default", $e);
        }

        return $stmt;
    }

inTransaction

Source line 85

public function inTransaction(): bool

Return expressions (including local callbacks): $this->connection()->inTransaction().

Implementation, validation guards and interaction order
public function inTransaction(): bool { return $this->connection()->inTransaction(); }

transaction

Source line 87

public function transaction(callable $callback): mixed

Parameters

Parameter Type, modifiers and default Purpose
$callback callable $callback Synchronous callback; its result/failure follows the return/transaction trace below.

State writes: self::$transactionFrames.

Return expressions (including local callbacks): $result.

Explicit exceptions: \LogicException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Failure handling catches \Throwable.

Implementation, validation guards and interaction order
public function transaction(callable $callback): mixed
    {
        $pdo = $this->connection();
        self::$transactionFrames ??= new \WeakMap();
        $frames = self::$transactionFrames[$pdo] ?? [];
        $depth = count($frames);
        if ($depth === 0 && $pdo->inTransaction()) {
            throw new \LogicException('A transaction is already active outside the provider.');
        }
        $savepoint = 'awt_transaction_' . $depth;
        if ($depth === 0) $pdo->beginTransaction();
        else $pdo->exec('SAVEPOINT ' . $savepoint);
        $frames[] = [];
        self::$transactionFrames[$pdo] = $frames;
        try {
            $result = $callback();
            if ($depth === 0) $pdo->commit();
            else $pdo->exec('RELEASE SAVEPOINT ' . $savepoint);
        } catch (\Throwable $e) {
            if ($pdo->inTransaction()) {
                if ($depth === 0) $pdo->rollBack();
                else {
                    $pdo->exec('ROLLBACK TO SAVEPOINT ' . $savepoint);
                    $pdo->exec('RELEASE SAVEPOINT ' . $savepoint);
                }
            }
            $frames = self::$transactionFrames[$pdo];
            array_pop($frames);
            self::$transactionFrames[$pdo] = $frames;
            throw $e;
        }
        $frames = self::$transactionFrames[$pdo];
        $callbacks = array_pop($frames);
        if ($depth > 0) $frames[$depth - 1] = [...$frames[$depth - 1], ...$callbacks];
        self::$transactionFrames[$pdo] = $frames;
        // Callback failures happen after commit and must never trigger rollback.
        $failure = null;
        if ($depth === 0) foreach ($callbacks as $afterCommit) {
            try { $afterCommit(); } catch (\Throwable $e) { $failure ??= $e; }
        }
        if ($failure !== null) throw $failure;
        return $result;
    }

afterCommit

Source line 131

public function afterCommit(callable $callback): void

Parameters

Parameter Type, modifiers and default Purpose
$callback callable $callback Synchronous callback; its result/failure follows the return/transaction trace below.

Delegates to connection().

Implementation, validation guards and interaction order
public function afterCommit(callable $callback): void
    {
        $pdo = $this->connection();
        $frames = self::$transactionFrames[$pdo] ?? [];
        if ($frames === []) { $callback(); return; }
        $frames[count($frames) - 1][] = $callback;
        self::$transactionFrames[$pdo] = $frames;
    }

lastInsertId

Source line 141

public function lastInsertId(): int

{@inheritdoc}

Return expressions (including local callbacks): (int) $this->connection()->lastInsertId().

Implementation, validation guards and interaction order
/** {@inheritdoc} */
    public function lastInsertId(): int
    {
        return (int) $this->connection()->lastInsertId();
    }

Related types

Clone this wiki locally