Skip to content

Internals Database Cache DatabaseCache

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

database\cache\DatabaseCache

Framework Internals · Subsystem overview · Developer guide

Source: awt_src/classes/database/cache/DatabaseCache.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\interface\ICache;
use vfs\cache\Cache;
use vfs\cache\enums\ECacheValidation;
use vfs\transient\enums\ETransientType;
use vfs\transient\interfaces\ITransientStorage;
use vfs\transient\interfaces\ITransientStorageEntry;
use vfs\transient\TransientStorage;

DatabaseCache

Declaration and architectural role

class DatabaseCache implements ICache

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

DbCache

Implements CacheInterface backed by the vfs Cache + TransientStorage layers.

Cache invalidation is condition-aware: each cached query is stored alongside the raw WHERE column/value pairs that produced it. A subsequent CUD operation supplies its own WHERE conditions, and only the cached queries whose conditions overlap are evicted — rather than blindly evicting by row ID.

This means UPDATE … WHERE name = 'Alice' correctly flushes every SELECT that was filtered by name = 'Alice', without touching unrelated cache entries for the same table.

Index structure (stored per table in linked_conditions.php):

[ 'SELECT …' => [ 'column' => 'name', 'value' => 'Alice', ], 'SELECT …' => [], // empty = full-table scan, always invalidated … ]

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
const INDEX_FILENAME private const INDEX_FILENAME = 'linked_conditions'; State or definition consumed by the methods below; reads and writes are preserved in their implementation traces.
const INDEX_FILE private const INDEX_FILE = 'linked_conditions.php'; State or definition consumed by the methods below; reads and writes are preserved in their implementation traces.
$cache private Cache $cache; Used by __construct(), get(), set(), invalidate(), invalidateTable().

Method index

Method Signature
__construct public function __construct()
get public function get(string $table, string $query): array|false
set public function set(string $table, string $query, array $result, array $conditions): void
invalidate public function invalidate(string $table, array $cudConditions): void
invalidateTable public function invalidateTable(string $table): void
shouldInvalidate private function shouldInvalidate(array $cachedConditions, array $cudConditions): bool
makeStorage private function makeStorage(string $table): ITransientStorage
loadIndex private function loadIndex(ITransientStorage $storage): array
saveIndex private function saveIndex(ITransientStorage $storage, array $index): void

__construct

Source line 45

public function __construct()

State writes: $this->cache.

Implementation, validation guards and interaction order
public function __construct()
    {
        $this->cache = new Cache();
    }

get

Source line 55

public function get(string $table, string $query): array|false

Parameters

Parameter Type, modifiers and default Purpose
$table string $table Operation input; the exact use, validation and propagation are shown in the implementation trace.
$query string $query Operation input; the exact use, validation and propagation are shown in the implementation trace.

{@inheritdoc}

Return expressions (including local callbacks): is_array($result) ? $result : false.

Implementation, validation guards and interaction order
// -------------------------------------------------------------------------
    // CacheInterface
    // -------------------------------------------------------------------------

    /** {@inheritdoc} */
    public function get(string $table, string $query): array|false
    {
        $result = $this->cache->pool($table)->getCache($query);
        return is_array($result) ? $result : false;
    }

set

Source line 62

public function set(string $table, string $query, array $result, array $conditions): void

Parameters

Parameter Type, modifiers and default Purpose
$table string $table Operation input; the exact use, validation and propagation are shown in the implementation trace.
$query string $query Operation input; the exact use, validation and propagation are shown in the implementation trace.
$result array $result Operation input; the exact use, validation and propagation are shown in the implementation trace.
$conditions array $conditions Column/value predicate map; values are bound and identifiers validated by QueryBuilder.

{@inheritdoc}

Delegates to makeStorage(), loadIndex(), saveIndex().

Implementation, validation guards and interaction order
/** {@inheritdoc} */
    public function set(string $table, string $query, array $result, array $conditions): void
    {
        // 1. Store the result rows.
        $this->cache->pool($table)->createConfig(ECacheValidation::EXPIRE, [])->setCache($query, $result);

        // 2. Update the condition index so we can later invalidate by column/value.
        $storage = $this->makeStorage($table);
        $index   = $this->loadIndex($storage);

        $index[$query] = $conditions;   // column → value map (may be empty for full-table SELECTs)

        $this->saveIndex($storage, $index);
    }

invalidate

Source line 77

public function invalidate(string $table, array $cudConditions): void

Parameters

Parameter Type, modifiers and default Purpose
$table string $table Operation input; the exact use, validation and propagation are shown in the implementation trace.
$cudConditions array $cudConditions Operation input; the exact use, validation and propagation are shown in the implementation trace.

{@inheritdoc}

Delegates to makeStorage(), loadIndex(), shouldInvalidate(), saveIndex().

Implementation, validation guards and interaction order
/** {@inheritdoc} */
    public function invalidate(string $table, array $cudConditions): void
    {
        $storage = $this->makeStorage($table);
        $index   = $this->loadIndex($storage);

        if (empty($index)) {
            return;
        }

        $pool = $this->cache->pool($table);

        foreach ($index as $query => $cachedConditions) {
            if ($this->shouldInvalidate($cachedConditions, $cudConditions)) {
                $pool->deleteCache($query);
                unset($index[$query]);
            }
        }

        $this->saveIndex($storage, $index);
    }

invalidateTable

Source line 99

public function invalidateTable(string $table): void

Parameters

Parameter Type, modifiers and default Purpose
$table string $table Operation input; the exact use, validation and propagation are shown in the implementation trace.

{@inheritdoc}

Delegates to makeStorage(), loadIndex(), saveIndex().

Implementation, validation guards and interaction order
/** {@inheritdoc} */
    public function invalidateTable(string $table): void
    {
        $storage = $this->makeStorage($table);
        $index   = $this->loadIndex($storage);
        $pool    = $this->cache->pool($table);

        foreach (array_keys($index) as $query) {
            $pool->deleteCache($query);
        }

        $this->saveIndex($storage, []);
    }

shouldInvalidate

Source line 122

private function shouldInvalidate(array $cachedConditions, array $cudConditions): bool

Parameters

Parameter Type, modifiers and default Purpose
$cachedConditions array $cachedConditions column → value map recorded when the query was cached.
$cudConditions array $cudConditions column → value map from the CUD WHERE clause.

Decide whether a cached query should be evicted given the CUD conditions.

@param array $cachedConditions column → value map recorded when the query was cached. @param array $cudConditions column → value map from the CUD WHERE clause.

Return expressions (including local callbacks): true; false.

Implementation, validation guards and interaction order
// -------------------------------------------------------------------------
    // Invalidation logic
    // -------------------------------------------------------------------------

    /**
     * Decide whether a cached query should be evicted given the CUD conditions.
     *
     * @param array $cachedConditions  column → value map recorded when the query was cached.
     * @param array $cudConditions     column → value map from the CUD WHERE clause.
     */
    private function shouldInvalidate(array $cachedConditions, array $cudConditions): bool
    {
        // Bulk CUD (no WHERE) → everything on this table is stale.
        if (empty($cudConditions)) {
            return true;
        }

        // Full-table SELECT (no WHERE when cached) → always stale after any CUD.
        if (empty($cachedConditions)) {
            return true;
        }

        // Overlap check: invalidate if any column+value pair matches.
        foreach ($cudConditions as $column => $value) {
            if (
                array_key_exists($column, $cachedConditions) &&
                $cachedConditions[$column] == $value
            ) {
                return true;
            }
        }

        return false;
    }

makeStorage

Source line 151

private function makeStorage(string $table): ITransientStorage

Parameters

Parameter Type, modifiers and default Purpose
$table string $table Operation input; the exact use, validation and propagation are shown in the implementation trace.

Return expressions (including local callbacks): $storage.

Implementation, validation guards and interaction order
// -------------------------------------------------------------------------
    // Index persistence helpers
    // -------------------------------------------------------------------------

    private function makeStorage(string $table): ITransientStorage
    {
        $storage = new TransientStorage();
        $storage->setPool('cache')->setSubPool($table);
        return $storage;
    }

loadIndex

Source line 164

private function loadIndex(ITransientStorage $storage): array

Parameters

Parameter Type, modifiers and default Purpose
$storage ITransientStorage $storage Operation input; the exact use, validation and propagation are shown in the implementation trace.

Load the condition index for a table. Returns an empty array when no index file exists yet.

@return array<string, array<string, mixed>>

Return expressions (including local callbacks): []; is_array($data) ? $data : [].

Implementation, validation guards and interaction order
/**
     * Load the condition index for a table.
     * Returns an empty array when no index file exists yet.
     *
     * @return array<string, array<string, mixed>>
     */
    private function loadIndex(ITransientStorage $storage): array
    {
        $file = $storage->getFile(self::INDEX_FILE);

        if ($file === null) {
            return [];
        }

        $data = require $file->getPath();
        return is_array($data) ? $data : [];
    }

saveIndex

Source line 183

private function saveIndex(ITransientStorage $storage, array $index): void

Parameters

Parameter Type, modifiers and default Purpose
$storage ITransientStorage $storage Operation input; the exact use, validation and propagation are shown in the implementation trace.
$index array $index Operation input; the exact use, validation and propagation are shown in the implementation trace.

Persist the condition index back to disk.

Creates the file on first write; overwrites on subsequent writes.

@param array<string, array<string, mixed>> $index

Return expressions (including local callbacks): ' . var_export($index, true) . '.

Implementation, validation guards and interaction order
/**
     * Persist the condition index back to disk.
     *
     * Creates the file on first write; overwrites on subsequent writes.
     *
     * @param array<string, array<string, mixed>> $index
     */
    private function saveIndex(ITransientStorage $storage, array $index): void
    {
        $export  = '<?php return ' . var_export($index, true) . ';';
        $file    = $storage->getFile(self::INDEX_FILE);

        if ($file === null) {
            $storage->createFile(self::INDEX_FILENAME, ETransientType::PHP, $export);
        } else {
            $file->write($index);
        }
    }

Related types

Clone this wiki locally