Skip to content

Developer Guide Database and Models

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

Database queries, models and schema

Developer Guide · Package lifecycle

Internals: Database, Models, DatabaseManager, Model, QueryBuilder, TableWizard.

The inspected application uses explicit database repositories and installer schema definitions. AWT also supplies Model for hydrated records. Choose DatabaseManager for row arrays and repository operations; choose Model when attribute casts, relations, serialization and persistence on an object are useful. Neither API creates your schema automatically.

Define package-owned schema

Replace the earlier empty Install hook with complete DemoSite/install.php:

<?php
namespace DemoSite;

use database\creator\ColumnCreator;
use database\creator\TableWizard;
use installer\interfaces\package\actions\IPostInstall;

final class Install implements IPostInstall
{
    public function postInstall(int $packageId): bool
    {
        $wizard = TableWizard::create($packageId);
        if ($wizard->tableExists('demo_message')) return true;
        $ok = $wizard
            ->addColumn(ColumnCreator::INT('id')->unsigned()->autoIncrement()->primary())
            ->addColumn(ColumnCreator::VARCHAR('body', '255'))
            ->addColumn(ColumnCreator::DATETIME('created_at')->default('CURRENT_TIMESTAMP'))
            ->createTable('demo_message');
        if (!$ok) throw new \RuntimeException('Could not create demo_message.');
        return true;
    }
}

Run this as part of a new installation, or adapt it into update.php when DemoSite is already installed. Use the hook's package ID so schema registry ownership supports cleanup. Do not use headless() for ordinary package schema; it bypasses registry checks/registration and is intended for framework bootstrap tables.

ColumnCreator provides INT/TINYINT/SMALLINT/BIGINT, BOOLEAN, FLOAT/DOUBLE/DECIMAL, VARCHAR/CHAR/TEXT variants, DATE/DATETIME/TIMESTAMP, ENUM/SET, BLOB and JSON constructors. Chain nullable(), unsigned(), autoIncrement(), primary(), unique(), index(), default(), comment(), after() and foreignKey(). ColumnDefinition is the built value object; ColumnSQLBuilder produces MySQL fragments. Treat all identifiers, ENUM values and DDL inputs as trusted package code, not request input.

TableWizard supports tableExists()/columnExists(), addColumnToTable(), modifyColumn(), dropColumn(), renameColumn(), dropTable(), renameTable(), addIndex()/dropIndex(). It tracks schema through awt_table/awt_table_structure rather than discovering every physical table. Guard migrations with registry checks as the inspected package does. DDL and registry changes are not one atomic migration transaction. The column queue normally clears after createTable returns; thrown exceptions/early duplicate-table returns can leave queued state, so use a fresh wizard after a failed create. renameTable currently recreates registry metadata and does not preserve all column entries; review before using it.

Query rows

Excerpt in an initialized controller action or repository method, after demo_message exists:

$db = new \database\DatabaseManager();
$id = $db->table('demo_message')->insert(['body' => 'Hello AWT'])->executeInsert();
$rows = $db->table('demo_message')->select(['id', 'body'])
    ->where(['id' => $id])->orderBy('id', 'DESC')->get(10, 0);
$changed = $db->table('demo_message')->where(['id' => $id])->update(['body' => 'Updated']);

insert() only prepares; executeInsert() runs it and returns an ID or null. get(limit, offset) returns associative row arrays; first() returns one row or null. update() returns whether rows changed, not whether an identical update was valid. delete() requires a WHERE clause and returns whether rows were removed. Executing an operation resets query-builder state; configure table()/select()/filters again for the next operation.

where() replaces the predicate and bindings; andWhere()/orWhere() append grouped predicates. like() also replaces the current predicate. Null values use IS NULL/IS NOT NULL for equality/inequality. where(..., useNot: true) uses inequality. orderBy() accepts validated identifiers and defaults invalid directions to ASC. Negative limit/offset fails; offset is emitted only when a limit is present.

join(table, on, type) accepts a trusted SQL ON expression. Prefer joinOn(table, leftColumn, rightColumn, type) for validated identifier equality. Values are bound parameters, but select column expressions and legacy ON strings are trusted SQL. Bind values in a provider's execute(sql, bindings) if you need custom SQL. Close PDOStatement cursors after use, as the inspected repository does.

UPDATE with no WHERE is allowed and affects all rows; DELETE with no WHERE is refused. For intentional whole-table deletion only, where(['1' => 1]) forms the explicit unconditional predicate. Do not copy it into normal request mutation code.

SqlExpression permits only DEFAULT and CURRENT_TIMESTAMP for update expressions. QueryBuilder treats the literal string 'DEFAULT' as SQL in update(); use new BoundValue('DEFAULT') to force literal data. Models wrap that reserved string when updating attributes. These wrappers are not a general raw-SQL expression API.

Define and persist a model

Complete DemoSite/models/Message.php:

<?php
namespace DemoSite\models;

use model\Model;

final class Message extends Model
{
    public ?int $id = null;
    public string $body = '';
    public ?string $created_at = null;

    public function __construct(?int $id = null)
    {
        parent::__construct();
        $this->model_source = 'demo_message';
        $this->id_column = 'id';
        if ($id !== null) $this->selectByID($id);
    }

    protected function fillableAttributes(): array { return ['body']; }
    protected function writableAttributes(): ?array { return ['body']; }
    protected function attributeCasts(): array { return ['id' => 'int']; }
}

Excerpt in an initialized controller action, with schema installed:

$message = (new \DemoSite\models\Message())->fill(['body' => 'Hello models']);
$id = $message->saveModel();
$loaded = new \DemoSite\models\Message($id);
$loaded->body = 'Edited';
$dirty = $loaded->getDirty();
$changed = $loaded->save();
$recent = (new \DemoSite\models\Message())->newQuery()
    ->orderBy('id', 'DESC')->getModels(10);

saveModel() inserts and returns int|null, updating the object's key. save() updates an existing key, while deleteModel() deletes it and clears key state. Both wrap failures in ModelCRUDException; selectByID() wraps retrieval failures in ModelCreationException. A missing row does not throw by itself: inspect existsInDatabase(). firstModelOrFail() explicitly throws OutOfBoundsException.

get() still returns rows; getModels() hydrates model clones. newQuery() preserves the provider/cache but resets attributes and query state. selectByID() with null does nothing. When table is not configured, inferTableName() converts the class's short name to snake_case; it does not strip a “Model” suffix or pluralize it. Configure model_source explicitly for package-prefixed tables.

Attribute controls and serialization

Hook/API Use
fillableAttributes() / fill() Explicit allowlist for untrusted input; default allowlist is empty. Validate values separately.
writableAttributes() Persistence allowlist. null retains legacy blacklist-based behavior; a list narrows database columns.
hiddenAttributes() Exclude fields from toArray()/JSON, not from persistence.
attributeCasts() int/integer, float, string, bool/boolean, json/array conversions. Unsupported casts fail.
fromArray() Trusted-data assignment; does not apply fill allowlist.
getParam() Public initialized property or dynamicData value, else null.
syncOriginal(), getDirty(), isDirty(), getChanges() Attribute snapshot, current differences and last successful persistence changes.
toArray(), jsonSerialize(), __toString() Public/dynamic attributes with internal and hidden exclusions. __toString() returns JSON.

Use writableAttributes() for models with additional public service state or helpers. save() currently updates the full allowed persistence set, rather than only dirty fields. If a registered updated_on column exists it receives CURRENT_TIMESTAMP. Missing-key updates/deletes fail. Relation values are excluded from persistence. Hydration clears previously loaded attributes/relations to prevent stale row data, then tracks originals.

Relationships

Implement IRelationBelongs::belongsTo(), IRelationWith::with() or IRelationHasMany::hasMany(), each returning its configuration array. A related class must extend Model. Single-object configuration excerpt inside a model class that implements IRelationBelongs, assuming a real Author model/table:

public function belongsTo(): array
{
    return [
        'model' => \DemoSite\models\Author::class,
        'column' => 'author_id',
        'table' => 'demo_author',
        'key' => 'id',
        'as' => 'author',
    ];
}

column is the current row's foreign-key field; key is the related primary key. The relation is available as $message->author. Optional inConstructor delegates lookup to a constructor accepting the key; prefer the default hydrate/load path so the inherited provider/cache is reused before querying.

Has-many configuration uses model (one class or list), column (related table's foreign key), optional localKey (current row key), table, key, as and inConstructor. Example: an Author's hasMany() returns ['model' => Message::class, 'column' => 'author_id', 'localKey' => 'id', 'table' => 'demo_message', 'as' => 'messages']. This requires author_id schema/model attributes added to the first example. Hydration loads declared relations; recursion guards stop cyclic eager hydration. No many-to-many relation builder, arbitrary eager-load list or relation query proxy is supplied.

Collections, transactions and cache

Subclass ModelCollection, implement getModel(): string, and optionally override getTable(): string. Construction loads all table rows; iteration/counting works and obCollection offers object sorting. It hydrates rows without a second constructor query. There is no built-in pagination on its constructor; use a fluent model query for bounded results.

Excerpt in an initialized repository method:

$db = new \database\DatabaseManager();
$result = $db->transaction(function (\database\DatabaseManager $connection): ?int {
    return $connection->table('demo_message')
        ->insert(['body' => 'Committed together'])->executeInsert();
});

transaction() requires ITransactionalProvider, returns the callback result, and rolls back on a thrown Throwable. The default provider supports nested savepoints and defers cache invalidation through afterCommit callbacks. Use the same injected/shared connection for every operation in a transaction. Read caching is bypassed inside transactions and for JOIN queries. Other reads cache by SQL plus bindings/types; successful writes invalidate the affected table after commit. use database\trait\DoNotCache; on a DatabaseManager subclass disables its read cache. Raw provider writes do not automatically invalidate DatabaseManager caches.

Clone this wiki locally