Documentation menu

Reference

taphra/db

The database layer of the Taphra framework, usable on its own. It gives you:

  • DataStore: one class per table, with create / read / update / delete, a fluent query builder, scopes, global filters, casts, mass-assignment rules, timestamps and soft deletes.
  • SqlQuery: a query builder for statements that do not map to one table (joins, CTEs, set operations, window functions, upserts).
  • SchemaBuilder: portable CREATE TABLE / ALTER TABLE / index statements.

It needs only ext-pdo and psr/log. Every example in this file runs as written, top to bottom, against SQLite.


Requirements and installation

#
  • PHP 8.2 or later, ext-pdo and the PDO driver for your database
  • taphra/container, installed with it (it holds Taphra\TaphraExceptionInterface, which every Taphra exception implements)
  • Optional: predis/predis for RedisConnection, mongodb/mongodb and ext-mongodb for MongodbConnection (not covered here)
  • MongodbConnection is experimental, and DataStores on a MongoDB connection are not supported in 1.0.
Shell
composer require taphra/db

Tested against SQLite, PostgreSQL 16 and MariaDB 11 (MySQL dialect). SQL Server statements are generated by MssqlAdapter and covered by unit tests of the generated SQL only.


Configuring connections

#

Call DataStore::configure() once, before creating any DataStore. Each key is a connection name; a DataStore picks one with its $connection property.

PHP
use Taphra\DataStore;

DataStore::configure([
    'main' => [
        'type'     => 'sqlite',
        'host'     => '',
        'port'     => '',
        'name'     => __DIR__ . '/blog.sqlite',  // or ':memory:'
        'user'     => '',
        'password' => '',
    ],
]);

Required keys: type (sqlite, mysql, postgres or mssql), host, port, name, user, password. Optional keys, with their defaults: charset (utf8mb4), persistent (false), extra ([]). A MySQL and a PostgreSQL connection look like this:

PHP
$otherConnections = [
    'mysql_main' => [
        'type' => 'mysql', 'host' => '127.0.0.1', 'port' => 3306,
        'name' => 'blog', 'user' => 'blog', 'password' => 'secret',
    ],
    'pg_reports' => [
        'type' => 'postgres', 'host' => '127.0.0.1', 'port' => 5432,
        'name' => 'reports', 'user' => 'reports', 'password' => 'secret', 'charset' => 'UTF8',
    ],
];
// DataStore::configure($otherConnections);

To read the connection settings from somewhere else (environment, container, a file), pass a callable instead: DataStore::setConfigResolver(fn (string $name): array => ...).

DatabaseConnection::load('main') returns the connection for SqlQuery, SchemaBuilder and raw SQL: for an SQL database it is the one every DataStore on main uses (one PDO handle per process, also $ds->connectionManager->getConnection()), so SQL run on it inside DataStore::transaction() is part of the transaction. DataStore::flushConnections() makes the next load() and DataStore connect again.


Creating tables

#
PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$conn   = DatabaseConnection::load('main');
$schema = new SchemaBuilder($conn);

foreach (['post_tags', 'comments', 'reactions', 'posts', 'users', 'countries'] as $table) {
    $schema->dropIfExists($table);
}

$schema->create('countries', function ($t) {
    $t->id();
    $t->string('name', 100);
});

$schema->create('users', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->string('email')->unique();
    $t->string('role', 20)->default('author');
    $t->integer('country_id')->nullable();
});

$schema->create('posts', function ($t) {
    $t->id();
    $t->integer('user_id');
    $t->string('title');
    $t->text('body')->nullable();
    $t->string('status', 20)->default('draft')->index();
    $t->integer('views')->default(0);
    $t->text('meta')->nullable();          // JSON stored as text
    $t->timestamps();                      // created_at, updated_at
    $t->softDeletes();                     // deleted_at
});

$schema->create('comments', function ($t) {
    $t->id();
    $t->integer('post_id');
    $t->text('body');
});

$schema->create('reactions', function ($t) {
    $t->id();
    $t->string('emoji', 10);
    $t->string('target_type', 50);
    $t->integer('target_id');
});

$schema->create('post_tags', function ($t) {
    $t->integer('post_id');
    $t->string('tag', 50);
});
$schema->addIndex('post_tags', ['post_id', 'tag'], 'post_tags_unique', true);

$schema->hasTable('posts');                 // true
$schema->hasColumn('posts', 'status');      // true

More of the schema API is listed in SchemaBuilder.


Defining a DataStore

#

One class per table. $connection and $objectName must be public.

PHP
use Taphra\DataStore;
use Taphra\DataStoreQueryBuilder;
use Taphra\Traits\SoftDeletes;
use Taphra\Traits\Timestamps;

class UserDataStore extends DataStore
{
    public $connection = 'main';
    public $objectName = 'users';
    protected $fillable = ['name', 'email', 'country_id'];
}

class CountryDataStore extends DataStore
{
    public $connection = 'main';
    public $objectName = 'countries';
    protected $fillable = ['name'];

    // Two hops: countries -> users (country_id) -> posts (user_id)
    public function posts()
    {
        return $this->hasManyVia(PostDataStore::class, UserDataStore::class, 'country_id', 'user_id');
    }
}

class PostDataStore extends DataStore
{
    use Timestamps;     // sets created_at / updated_at on save
    use SoftDeletes;    // delete() sets deleted_at; queries skip deleted rows

    public $connection = 'main';
    public $objectName = 'posts';

    // Fields that fill(), create() and save($data) accept from input.
    protected $fillable = ['user_id', 'title', 'body', 'status', 'meta'];

    // Converted on read (and back on save).
    protected $casts = ['views' => 'int', 'meta' => 'json'];

    // A scope that receives the builder as its first parameter...
    public function scopePublished(DataStoreQueryBuilder $q): DataStoreQueryBuilder
    {
        return $q->where('status', 'published');
    }

    // ...or one that starts its own query.
    public function scopeByUser(int $userId): DataStoreQueryBuilder
    {
        return $this->query()->where('user_id', $userId);
    }

    // Relations used by DataStoreCollection::load() (see Relations).
    public function comments()
    {
        return $this->hasMany(CommentDataStore::class, 'post_id');
    }

    public function reactions()
    {
        return $this->polymorphicChildren(ReactionDataStore::class, 'target');
    }

    public function topReaction()
    {
        return $this->polymorphicChild(ReactionDataStore::class, 'target');
    }
}

class CommentDataStore extends DataStore
{
    public $connection = 'main';
    public $objectName = 'comments';
    protected $fillable = ['post_id', 'body'];
}

class ReactionDataStore extends DataStore
{
    public $connection = 'main';
    public $objectName = 'reactions';
    protected $fillable = ['emoji', 'target_type', 'target_id'];
}

class PostTagDataStore extends DataStore
{
    public $connection = 'main';
    public $objectName = 'post_tags';
    public $primaryKey = ['post_id', 'tag'];   // a table without a primary key in the schema
    protected $fillable = ['post_id', 'tag'];
}

The primary key is read from the schema. Declare $primaryKey when the schema has none (views, keyless tables) or to override it: 'id', ['id'] and ['post_id', 'tag'] are all accepted.


Creating, reading, updating and deleting

#

Creating rows

#
PHP
$country = CountryDataStore::create(['name' => 'France']);
$alice   = UserDataStore::create(['name' => 'Alice', 'email' => '[email protected]', 'country_id' => $country['id']]);
$bob     = UserDataStore::create(['name' => 'Bob', 'email' => '[email protected]']);

// create() fills through $fillable, saves, and returns the stored row (a DataStoreRow).
$post = PostDataStore::create([
    'user_id' => $alice['id'],
    'title'   => 'Hello',
    'status'  => 'published',
    'meta'    => ['color' => 'blue', 'size' => ['w' => 3]],
]);
echo $post['id'], ' ', $post->title, ' ', $post['created_at'];

// insert() and save() take an array and return the new primary key. save() runs
// the beforeSave() hooks (casts, Timestamps); insert() does not.
$ds = new PostDataStore();
$id = $ds->insert(['user_id' => $bob['id'], 'title' => 'Second', 'status' => 'draft']);
$id = $ds->save(['user_id' => $bob['id'], 'title' => 'Third', 'status' => 'published']);

// The active-record style: resetRecord() + fill() + save().
$ds->resetRecord();
$ds->fill(['user_id' => $alice['id'], 'title' => 'Fourth', 'status' => 'published', 'views' => 999]);
$id = $ds->save();   // 'views' is not in $fillable, so it was not written

Reading rows

#
PHP
$post  = PostDataStore::findById(1);                          // ?DataStoreRow
$tag   = PostTagDataStore::create(['post_id' => 1, 'tag' => 'php']);
$tag   = PostTagDataStore::findById(['post_id' => 1, 'tag' => 'php']);   // composite key
$first = PostDataStore::firstWhere(['status' => 'published']);  // ?DataStoreRow
$all   = PostDataStore::all(['status' => 'published']);         // DataStoreCollection

$ds    = new PostDataStore();
$rows  = $ds->find(['status' => 'published'], 10, 0, 'created_at', 'DESC');  // conditions, limit, offset, order column, direction
$one   = $ds->findOne(['title' => 'Hello']);
$count = $ds->findCount(['status' => 'published']);
$any   = $ds->exists(['user_id' => 2]);
$names = $ds->pluck('title', ['status' => 'published']);       // ['Hello', 'Third', 'Fourth']

// Operators go in the key: =, !=, <>, <, >, <=, >=, like, in, not in, between, is, is not
$recent = $ds->find(['views >=' => 0, 'title like' => 'H%', 'status in' => ['draft', 'published']]);

// The active-record style: read() loads a row into the DataStore.
$ds->read(1);
echo $ds->get('title');

// findOrFail() throws when nothing matches.
try {
    $ds->findOrFail(['id' => 12345]);
} catch (\Taphra\Db\RecordNotFoundException $e) {
    echo 'not found';
}

Updating rows

#
PHP
// Through the row: only changed columns are written, Timestamps updates updated_at.
$post = PostDataStore::findById(1);
$post->title = 'Hello again';
$post->isDirty('title');        // true
$post->getDirty();              // ['title' => 'Hello again']
$post->getOriginal('title');    // 'Hello'
$post->save();
$post->refresh();               // reload from the database

// update(key, data) updates one row by its primary key...
(new PostDataStore())->update(['id' => 2], ['title' => 'Second (edited)']);

// ...and update(conditions, data) every matching row.
// (save($data) with the key in $data updates that row only when the key is fillable,
// or when the DataStore declares neither $fillable nor $guarded; otherwise it inserts.)
(new PostDataStore())->update(['status' => 'draft'], ['body' => 'Work in progress']);

// Insert, or update on a unique-key conflict, in one statement.
(new UserDataStore())->upsert(['name' => 'Alice B.', 'email' => '[email protected]'], ['email']);

// Find or create
$row = (new UserDataStore())->firstOrCreate(['email' => '[email protected]'], ['name' => 'Carol']);

Deleting rows

#
PHP
$ds = new CommentDataStore();
$ds->insert(['post_id' => 1, 'body' => 'First!']);
$ds->insert(['post_id' => 1, 'body' => 'Nice post']);
$ds->insert(['post_id' => 2, 'body' => 'Spam']);

$ds->delete(['body' => 'Spam']);                 // DELETE ... WHERE body = ?
CommentDataStore::firstWhere(['body' => 'First!'])->delete();

// With SoftDeletes, delete() sets deleted_at and queries leave the row out.
$posts = new PostDataStore();
$posts->delete(['title' => 'Fourth']);
$posts->onlyTrashed()->findCount();              // 1
$posts->restore(['title' => 'Fourth']);          // deleted_at back to NULL
$posts->delete(['title' => 'Fourth']);
$posts->forceDelete(['title' => 'Fourth']);      // a real DELETE

Batch writes

#
PHP
$ds = new PostDataStore();
$ds->insertBatch([
    ['user_id' => 2, 'title' => 'Batch 1', 'status' => 'draft'],
    ['user_id' => 2, 'title' => 'Batch 2', 'status' => 'draft'],
]);                                       // one INSERT per 500 rows; returns the row count

(new UserDataStore())->upsertBatch([
    ['name' => 'Bob', 'email' => '[email protected]'],
    ['name' => 'Dan', 'email' => '[email protected]'],
], ['email']);                            // conflict columns; the other columns are updated

insertBatch($rows, $chunkSize, $skipConflicts) skips duplicate rows when $skipConflicts is true (INSERT IGNORE on MySQL, INSERT OR IGNORE on SQLite, ON CONFLICT DO NOTHING on PostgreSQL). Batch writes do not apply $fillable.

Transactions

#
PHP
$newId = PostDataStore::transaction(function () {
    $post = PostDataStore::create(['user_id' => 1, 'title' => 'In a transaction', 'status' => 'draft']);
    (new CommentDataStore())->insert(['post_id' => $post['id'], 'body' => 'Same transaction']);
    return $post['id'];
});

try {
    PostDataStore::transaction(function () {
        PostDataStore::create(['user_id' => 1, 'title' => 'Rolled back', 'status' => 'draft']);
        throw new \RuntimeException('something failed');
    });
} catch (\RuntimeException $e) {
    // the insert was rolled back
}

All DataStores on the same connection name share one PDO handle, so writes made by any of them inside the callback are part of the transaction.


The query builder

#

Static calls on a DataStore class start a builder; (new PostDataStore())->query() returns one too.

PHP
$posts = PostDataStore::where('status', 'published')       // field = value
    ->where('views', '>=', 0)                               // field, operator, value
    ->whereIn('user_id', [1, 2])
    ->whereNull('deleted_at')
    ->orderBy('created_at', 'desc')
    ->limit(20)
    ->offset(0)
    ->get();                                                // DataStoreCollection of DataStoreRow

$first   = PostDataStore::where('status', 'draft')->first();               // ?DataStoreRow
$either  = PostDataStore::where('status', 'draft')->orWhere('views', '>', 100)->get();
$any     = PostDataStore::where('user_id', 1)->exists();
$titles  = PostDataStore::where('user_id', 1)->pluck('title');
$matches = (new PostDataStore())->query()->whereContains(['title', 'body'], 'hello')->get();  // LIKE %hello%, wildcards in the term match literally
$hits    = (new PostDataStore())->query()->whereAny(['title', 'body'], 'LIKE', '%batch%')->get();

// Aggregates
$count = PostDataStore::where('status', 'published')->count();
$views = PostDataStore::where('user_id', 1)->sum('views');
$avg   = (new PostDataStore())->query()->avg('views');
$max   = (new PostDataStore())->query()->max('views');

// Grouping
$perStatus = (new PostDataStore())->query()
    ->selectRaw('status, COUNT(*) AS n')
    ->groupBy('status')
    ->orderBy('status')
    ->get()
    ->toArray();                  // [['status' => 'draft', 'n' => 4], ...]

// Raw SQL with bound values
$rows = PostDataStore::where('status', 'published')
    ->whereRaw('LENGTH(title) > ?', [3])
    ->orderByRaw('user_id * ? DESC', [1])
    ->get();

// Process large tables in batches
(new PostDataStore())->query()->orderBy('id')->chunk(2, function ($batch) {
    foreach ($batch as $row) {
        // ...
    }
});

// The SQL, with values inlined (for logs and debugging)
echo PostDataStore::where('status', 'published')->toSql();

JSON columns

#
PHP
$blue   = PostDataStore::jsonPath('meta', 'color', '=', 'blue')->get();   // column, path, operator, value
$wide   = PostDataStore::jsonPath('meta', 'size.w', '>', 2)->get();       // nested path
$tagged = PostDataStore::jsonHas('meta', 'color')->get();                 // the path exists
$sorted = PostDataStore::jsonHas('meta', 'size')->orderByJson('meta', 'size.w', 'desc')->get();

jsonContains($column, $path, $value) matches a value inside a JSON array at $path on MySQL (JSON_CONTAINS); on the other databases it compares the value at $path. Path segments may contain only letters, digits and _; an all-digit segment is an array index (tags.0).

#
PHP
$withComments = PostDataStore::whereHas('comments', 'post_id')->get();                // EXISTS (...)
$busy         = PostDataStore::whereHasCount('comments', 'post_id', '>=', 2)->get();  // (SELECT COUNT(*) ...) >= 2
$counted      = PostDataStore::withCount('comments', 'post_id')->get();               // adds comments_count to each row

$authors = (new UserDataStore())->query()->selectRaw('id')->where('name', 'Alice');
$byAlice = PostDataStore::whereInSubquery('user_id', $authors)->get();

Scopes and global filters

#
PHP
$published = PostDataStore::published()->orderBy('id')->get();
$mine      = PostDataStore::byUser(1)->count();

// A filter is applied to every query-builder query on that class.
PostDataStore::addFilter('published', fn ($q) => $q->where('status', 'published'));
$visible = PostDataStore::where('user_id', 1)->get();          // only published rows
$every   = PostDataStore::unfiltered()->get();                 // all filters skipped
$some    = PostDataStore::unfiltered('published')->get();      // just this one skipped
PostDataStore::getFilters();                                   // ['published' => Closure]
PostDataStore::removeFilter('published');
PostDataStore::flushFilters();

Filters apply to query-builder calls (where(), get(), count(), sum(), paginate() and so on), not to find(), findById() or all().


Values, identifiers and mass assignment

#
  • Values are always bound. where(), whereIn(), orWhere(), JSON queries, array conditions (find(['email' => $x])), Criteria and the array conditions of update() and delete() (['id' => $id], or the older ['id' => '=' . $id] form) send values as ? parameters. toSql() inlines them with the driver's own quoting, for display.
  • Names are checked. Condition-array keys, orderBy(), groupBy() and JSON columns and paths must be column names (table.column allowed). Operators must be comparison operators; LIMIT and OFFSET are integers. Use orderByRaw(), groupByRaw() (on SqlQuery), whereRaw() and selectRaw() for expressions.
  • Raw SQL is for code you write. String conditions (find('views > 10')), where('raw expression'), having(), the extra condition of whereHas() and the *Raw() methods are passed through as SQL. Never build them from request data.
  • Condition arrays need column-name keys. An integer key may only carry a Criteria object; a string there ([0 => '1=1'], or a decoded body such as {"0": "..."}) throws DbException.
  • Ids. findById() and read() take a scalar, or for a composite key a map naming exactly the primary-key columns. Other arrays, such as a ?id[]= or ?id[secret]= request value, throw DataStoreException. A non-integer value for an integer key finds nothing.
  • $fillable and $guarded always filter fill() and create() (by default nothing is fillable). They also filter the data passed to save($data), insert($data), update($conditions, $data) and upsert($data, ...) when the DataStore declares either list; DataStores that declare neither write every field there. With a list declared, a primary key in save($data) that is not fillable is dropped, so the call inserts a new row instead of updating that one. Values you set on a DataStoreRow and save(), or pass through forceFill($data) and save(), are not filtered.
PHP
$ds = new PostDataStore();
$ds->save(['user_id' => 1, 'title' => 'From a form', 'status' => 'draft', 'views' => 1000000]);  // views dropped

$row = PostDataStore::firstWhere(['title' => 'From a form']);
$row->views = 5;          // trusted code: written
$row->save();

Collections and rows

#

find(), all() and get() return a DataStoreCollection; each item is a DataStoreRow.

PHP
$posts = PostDataStore::where('status', 'published')->orderBy('id')->get();

count($posts);                                    // Countable
$posts->isEmpty();
$posts->first();                                  // ?DataStoreRow
$posts->last();
$posts->filter(fn ($p) => $p['views'] > 0);       // DataStoreCollection
$posts->map(fn ($p) => $p['title']);              // DataStoreCollection of whatever the callback returns
$posts->keyBy('id');                              // DataStoreCollection keyed by id
$posts->each(function ($p) { /* ... */ });
$posts->toArray();                                // array of DataStoreRow
$posts->toJson();                                 // JSON array of objects
foreach ($posts as $post) {
    echo $post['title'], $post->title;            // array and property access
}

$post = $posts->first();
$post->only(['id', 'title']);                     // plain array
$post->except(['body']);
$post->toArray();
json_encode($post);
$post->isPersistable();                           // true for rows loaded through a DataStore

Pagination and ListQuery

#
PHP
use Taphra\Http\ListQuery;

$page = PostDataStore::paginate(2);                 // reads ?page from $_GET, default 1
$page = PostDataStore::paginate(2, 1, ['status' => 'published']);
$page = PostDataStore::where('status', 'published')->paginate(2, 1);

$page->items;          // array of rows on this page
$page->total;          // rows matching, on every page
$page->perPage;
$page->currentPage;
$page->lastPage;
$page->hasMore;
$page->from();         // 1-based position of the first row on the page
$page->to();
$page->nextPageUrl('/posts');   // '/posts?page=2' or null
$page->meta();         // total, per_page, current_page, last_page, has_more (no rows)

// ListQuery builds an index query from ?search, ?sort, ?dir and ?page.
$_GET = ['search' => 'hello', 'sort' => 'title', 'dir' => 'desc', 'page' => '1'];
$result = ListQuery::fromRequest()
    ->searchable(['title', 'body'])                       // LIKE %term% on these columns
    ->sortable(['title', 'created_at'], 'created_at', 'desc')   // only these; then default column, direction
    ->where('status', 'published')                        // always applied
    ->paginate(new PostDataStore(), 20);
$rows = ListQuery::fromRequest()->searchable(['title'])->apply(new PostDataStore())->get();   // no pagination
$_GET = [];

Relations

#

hasMany(), hasOne() and belongsTo() declare a relation; DataStoreCollection::load() fetches it for a whole collection in one query. Name the related DataStore by class (CommentDataStore::class) or by short name ('comment' finds CommentDataStore in the same namespace, then the global one).

PHP
$posts = PostDataStore::where('status', 'published')->get();
$posts->load('comments');
foreach ($posts as $post) {
    $comments = $post->getRelation('comments');    // DataStoreCollection
}

// polymorphicChildren() / polymorphicChild(): rows of another table that point back with
// <name>_type and <name>_id. The type value comes from a registered alias, never a class name.
\Taphra\DataStore::registerPolymorphicTypes(['post' => PostDataStore::class]);
(new ReactionDataStore())->insert(['emoji' => '+1', 'target_type' => 'post', 'target_id' => 1]);

$ds = new PostDataStore();
$ds->read(1);
$reactions = $ds->reactions();      // DataStoreCollection
$top       = $ds->topReaction();    // ?DataStoreRow

// hasManyVia(): two hops through an intermediate table
$country = new CountryDataStore();
$country->read(1);
$postsInFrance = $country->posts();   // posts written by users of country 1

polymorphicParent('target') does the reverse: it reads target_type and target_id from the active record and returns the parent row.


SqlQuery

#

For statements that do not map to one DataStore. Rows come back flat when fetch() gets false as its second argument.

PHP
use Taphra\Criteria;
use Taphra\DatabaseConnection;
use Taphra\SqlQuery;
use Taphra\WindowSpec;

$conn = DatabaseConnection::load('main');

$rows = (new SqlQuery($conn))
    ->select(['users.name', 'COUNT(posts.id) AS post_count'])
    ->from('users')
    ->leftJoin('posts', 'posts.user_id = users.id')
    ->where(new Criteria('users.role', '=', 'author'))
    ->groupBy('users.name')
    ->orderBy('post_count', 'DESC')
    ->limit(10)
    ->fetch(true, false);           // [['name' => 'Alice', 'post_count' => 4], ...]

$one = (new SqlQuery($conn))->select('*')->from('posts')->where(['id' => 1])->fetch(false, false);

// Raw fragments with bound values
$rows = (new SqlQuery($conn))
    ->select('*')
    ->from('posts')
    ->whereRaw('views >= ? AND status = ?', [0, 'published'])
    ->fetch(true, false);

// Grouped conditions: status = 'published' AND (user_id = 1 OR views > 100)
$c = new Criteria('status', '=', 'published');
$c->orGroup(function (Criteria $g) {
    $g->add('user_id', '=', 1);
    $g->add('views', '>', 100);
});
$rows = (new SqlQuery($conn))->select('*')->from('posts')->where($c)->fetch(true, false);

// A common table expression
$published = (new SqlQuery($conn))->select(['id', 'title'])->from('posts')->where(['status' => 'published']);
$rows = (new SqlQuery($conn))->with('published', $published)->select('*')->from('published')->fetch(true, false);

// Set operations: union(), unionAll(), intersect(), except()
$drafts = (new SqlQuery($conn))->select('title')->from('posts')->where(['status' => 'draft']);
$rows = (new SqlQuery($conn))->select('title')->from('posts')->where(['status' => 'published'])
    ->union($drafts)
    ->fetch(true, false);

// Window functions
$spec = (new WindowSpec())->partitionBy('user_id')->orderBy('id', 'ASC');
$rows = (new SqlQuery($conn))->select(['id', 'user_id'])->selectWindow('ROW_NUMBER()', $spec, 'n')
    ->from('posts')->fetch(true, false);

// Writes. update() and delete() need a condition: a selector argument or where().
(new SqlQuery($conn))->insert('comments', ['post_id' => 1, 'body' => 'From SqlQuery'])->execute();
(new SqlQuery($conn))->update('comments', ['body' => 'Edited'])->where(new Criteria('body', '=', 'From SqlQuery'))->execute();
(new SqlQuery($conn))->delete('comments')->where(new Criteria('body', '=', 'Edited'))->execute();
(new SqlQuery($conn))->upsert('users', ['email' => '[email protected]', 'name' => 'Daniel'], ['email'])->execute();

// RETURNING (PostgreSQL and SQLite 3.35+)
$returned = (new SqlQuery($conn))->insert('comments', ['post_id' => 1, 'body' => 'Returned'])->returning(['id'])->execute();

// The statement: SQL with ? placeholders and the values to bind
$st = (new SqlQuery($conn))->select('*')->from('posts')->where(['status' => 'draft'])->toString();
// ['sqlWithParams' => 'SELECT * FROM posts WHERE ... = ?', 'values' => ['draft']]

Other SqlQuery methods: join(), rightJoin(), crossJoin(), fullOuterJoin(), distinct(), having(), havingRaw(), selectRaw(), orderByRaw(), groupByRaw(), whereSubquery(), whereExists(), withRecursive(), lockForUpdate() and sharedLock() (MySQL and PostgreSQL), onConflictWhere() (PostgreSQL and SQLite), getBindings(), toSqlString().

The connection itself runs SQL with bound values:

PHP
$conn->execute('UPDATE posts SET views = views + ? WHERE id = ?', [1, 1]);     // affected rows
$rows = $conn->query('SELECT id, title FROM posts WHERE views > ?', true, false, [0]);   // flat rows

SchemaBuilder

#
PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$schema = new SchemaBuilder(DatabaseConnection::load('main'));

$schema->dropIfExists('notes');
$schema->create('notes', function ($t) {
    $t->id();
    $t->string('title', 200);
    $t->string('slug', 200)->unique();
    $t->text('body')->nullable();
    $t->boolean('pinned')->default(false);
    $t->decimal('score', 8, 2)->default(0);
    $t->json('data')->nullable();
    $t->enum('kind', ['note', 'todo'])->default('note');
    $t->timestamps();
});
$schema->addColumn('notes', function ($t) {
    $t->integer('priority')->default(0);
});
$schema->renameColumn('notes', 'priority', 'rank');
$schema->addIndex('notes', 'rank');
$schema->dropIndex('notes', 'idx_notes_rank');   // the default name: idx_<table>_<columns>
$schema->dropColumn('notes', 'rank');
$schema->drop('notes');

Column types: id, string, char, text, mediumText, longText, integer, bigInteger, tinyInteger, boolean, float, double, decimal, date, time, dateTime, timestamp, json, jsonb, uuid, enum, binary, vector (pgvector), tsvector, plus timestamps() and softDeletes(). Modifiers: nullable(), default(), unique(), index(), primary(), unsigned() (MySQL), comment() (MySQL), generatedAs().

Foreign keys are declared inside create(), which works on every driver, SQLite included:

PHP
$schema->create('comments', function ($t) {
    $t->id();
    $t->integer('post_id');
    $t->text('body');
    $t->foreign('post_id', 'posts', 'id', 'CASCADE');   // ON DELETE CASCADE ON UPDATE RESTRICT
});

SQLite enforces them only on a connection with PRAGMA foreign_keys = ON: add 'extra' => ['pragma.foreign_keys' => 'ON'] to the connection's settings to have it run on every new connection.

Also: modifyColumn() (not SQLite), addForeignKey() (an existing table; not SQLite), ginIndex(), createExtension() and vectorIndex() (PostgreSQL), and the where: (partial index), using: and opclass: arguments of addIndex().


Query log

#
PHP
use Taphra\QueryLog;

QueryLog::enable();
PostDataStore::where('status', 'published')->get();
QueryLog::all();          // [['sql' => 'SELECT ...', 'duration_ms' => 0.1, 'trace' => null], ...]
QueryLog::stats();        // count, total_ms, max_ms, slow_count
QueryLog::disable();
QueryLog::reset();

Exceptions

#
Class Thrown by
Taphra\Db\DbException connections, SqlQuery, adapters, SchemaBuilder: SQL errors, invalid names or operators
Taphra\Db\DataStoreException DataStore, DataStoreCollection, the query builder
Taphra\Db\RecordNotFoundException DataStore::findOrFail() (extends DataStoreException)

All of them extend \RuntimeException.