Documentation menu

Data

Database

This page covers connections, migrations, seeders and factories, transactions and raw SQL. Reading and writing rows is in DataStores; building SQL by hand is in SqlQuery.

Every PHP example below marked as runnable runs as written, in order, against SQLite; the commands in bash blocks run against the same app.

Contents

#

Connections

#

Connections are declared per environment in app/Config/databases.yml, under dev, stg and prod. Each key (here app_master) is a connection name; the skeleton's AppDataStore uses app_master, and a DataStore can name another one in its $connection property.

app/Config/databases.yml
dev:
  app_master:
    type: sqlite
    host: ""
    port: ""
    name: tmp/app.sqlite      # relative paths start at app/
    user: ""
    password: ""

prod:
  app_master:
    type: mysql               # mysql | postgres | sqlite | mssql
    host: 127.0.0.1
    port: 3306
    name: myapp
    user: myapp
    password: ""
    charset: utf8mb4
    persistent: true

Nothing connects until the first query. mysql (also MariaDB) needs pdo_mysql, postgres needs pdo_pgsql, sqlite needs pdo_sqlite, and mssql uses pdo_dblib. Redis and MongoDB connections are covered in DataStores.

The YAML files are not templated: to keep a production password out of the repository, set it from the environment in app/bootstrap.php, which runs on every request after the configuration is loaded:

PHP
// app/bootstrap.php
\Taphra\Config::set('databases.app_master.password', (string) getenv('DB_PASSWORD'));

DatabaseConnection::load('app_master') returns the connection object for code that needs it directly (the SchemaBuilder, SqlQuery, raw SQL). All DataStores on one connection name share one PDO handle per process, and load() returns that same connection: SQL run on it inside a transaction is part of the transaction. It stays open for the process (in FrankenPHP worker mode, for the request) until DataStore::flushConnections(). Do not close() it while DataStores still use it: they hold the same object. After a close(), the next load() and the DataStores created after it open a new connection.

Taphra's database lock, queue and session drivers open separate connections of their own, so their work stays out of the application's transactions. With persistent: true, PDO can hand such a connection the same pooled handle, which then shares an open transaction anyway; set persistent: false on a connection that needs separate handles.

Migrations

#

A migration is a PHP class in app/Migrations/ that changes the schema one step forward (up) and back (down). Create one with:

Shell
php taphra make:migration create_posts_table

The file is named migration_<id>_<Description>.php, where the id is a timestamp (YYYYMMDDHHMMSS) by default. Fill in up() and down() with the SchemaBuilder:

app/Migrations/migration_20261201090000_CreatePostsTable.php
<?php
// app/Migrations/migration_20261201090000_CreatePostsTable.php

use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

class Migrate_migration_20261201090000_CreatePostsTable
{
    public $up = '';
    public $down = '';
    public $connection = '';

    public function up(array $args): void
    {
        $schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
        $schema->create('posts', function ($t) {
            $t->id();
            $t->string('title');
            $t->text('body')->nullable();
            $t->string('status', 20)->default('draft')->index();
            $t->timestamps();
        });
    }

    public function down(array $args): void
    {
        (new SchemaBuilder(DatabaseConnection::load('app_master')))->dropIfExists('posts');
    }
}

For a change that is a single SQL statement, set the properties instead and leave the methods out: $up and $down hold the SQL, $connection the connection name.

app/Migrations/migration_20261201090100_CreateTagsTable.php
<?php
// app/Migrations/migration_20261201090100_CreateTagsTable.php

class Migrate_migration_20261201090100_CreateTagsTable
{
    public $up = 'CREATE TABLE tags (id INTEGER PRIMARY KEY, name VARCHAR(50) NOT NULL)';
    public $down = 'DROP TABLE tags';
    public $connection = 'app_master';
}

Optional hooks run around each direction: beforeUp(array $args), afterUp(), beforeDown(), afterDown().

Shell
php taphra migrate                 # run every pending migration
php taphra migrate 20261201090000  # run pending migrations up to this id
php taphra migrate:status          # which ran, which are pending
php taphra migrate:rollback        # roll back the last migration that ran
php taphra migrate:down 20261201090000   # roll back every migration after this id
php taphra migrate:down reset      # roll back all of them
php taphra migrate:reset           # roll back all, then run all again
php taphra migrate --dry-run       # any of these with --dry-run shows what would run

migrate:status after the two migrations above:

Text
  ID                      Status    Description
  ------------------------------------------------------------
  20261201090000          Ran       CreatePostsTable
  20261201090100          Ran       CreateTagsTable

php taphra migrate:diff [connection] compares the DataStores that declare a $dataDefinition with the live tables and lists the columns that differ. It only reports; write a migration for the change.

Foreign keys

#

Declare a foreign key with foreign() inside create(). It becomes part of the CREATE TABLE statement, which works on SQLite as on MySQL, PostgreSQL and SQL Server:

PHP
// in a migration's up()
$schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
$schema->create('projects', function ($t) {
    $t->id();
    $t->integer('client_id');
    $t->string('title');
    $t->foreign('client_id', 'clients', 'id', 'CASCADE');   // ON DELETE CASCADE ON UPDATE RESTRICT
});

foreign($columns, $refTable, $refColumns = 'id', $onDelete = 'RESTRICT', $onUpdate = 'RESTRICT', $name = null) takes the same arguments as addForeignKey() without the table. Pass arrays for a key of several columns. The actions are CASCADE, RESTRICT, SET NULL, SET DEFAULT and NO ACTION. SQL Server has no RESTRICT, so there it is written NO ACTION, which also refuses the change. MySQL (InnoDB) rejects SET DEFAULT, so create() on a MySQL connection throws an InvalidArgumentException for it instead of putting another action in its place. The constraint is named fk_<table>_<columns> unless you give a name; a default name longer than 63 bytes is shortened with a hash, at a character boundary, to fit PostgreSQL and MySQL. Give the column the type of the column it references: integer() for a table whose key is id().

To add a foreign key to a table that exists, $schema->addForeignKey('projects', 'client_id', 'clients', 'id', 'CASCADE') works on MySQL, PostgreSQL and SQL Server. SQLite cannot add one to an existing table, so there it throws an InvalidArgumentException that points to foreign(): declare the key when the table is created, or create the table again.

SQLite checks foreign keys only when they are turned on. SQLite stores the foreign key with the table but enforces it only on a connection that ran PRAGMA foreign_keys = ON, and each new connection starts with it off. Taphra leaves SQLite's default as it is. To turn the checks on, add the pragma to the connection's extra settings; Taphra runs PRAGMA foreign_keys = ON each time it opens that connection:

YAML
# app/Config/databases.yml
dev:
  app_master:
    type: sqlite
    host: ""
    port: ""
    name: tmp/app.sqlite
    user: ""
    password: ""
    extra:
      pragma.foreign_keys: "ON"

Any pragma.<name> key of an SQLite connection's extra runs PRAGMA <name> = <value> the same way. MySQL (InnoDB), PostgreSQL and SQL Server enforce foreign keys by default.

Where the migration state lives

#

app/Config/migrations.yml chooses where the list of migrations that ran is kept:

YAML
path: null              # null: app/Migrations/
id_format: timestamp    # or sequential (1, 2, 3 ...)
state:
  backend: file         # file: app/Migrations/migration_state.json
  database:             # backend: database keeps it in a table instead
    connection: app_master
    table: schema_migrations

The file backend suits one developer. With backend: database the state travels with the database, so every developer and every deploy sees the same list; the table is created on first use. Switching backends does not copy the existing state.

Migrations from more folders

#

A Composer package can ship migrations, and an app can keep some of its own in another folder (a module, say). Each extra folder has a name. A package adds its folder from its service provider, which the console boots before a command runs:

PHP
<?php
// src/BlogServiceProvider.php in the acme/blog package
namespace Acme\Blog;

use Taphra\Migration;
use Taphra\ServiceProvider;

class BlogServiceProvider extends ServiceProvider
{
    public function register(): void {}

    public function boot(): void
    {
        Migration::addPath('acme_blog', dirname(__DIR__) . '/migrations');
    }
}

The app lists folders of its own under paths in migrations.yml; a relative folder starts at the project root:

YAML
# app/Config/migrations.yml
paths:
  reports: modules/reports/migrations
  • Every command covers every folder: migrate, migrate:down, migrate:rollback, migrate:reset and migrate:status. make:migration still writes to app/Migrations/.
  • Order: migrations run by ID across the folders, so timestamp IDs run in the order they were written. For the same ID, the app's migration runs first, then the folders in the order they were added (paths first, then addPath() calls). migrate:down and migrate:rollback go back in the reverse order: migrate:rollback rolls back the last migration in that order, whichever folder it is in.
  • State: each folder keeps its own list of what ran. The file backend writes migration_state.<name>.json next to the app's state file; the database backend uses the table <table>_<name> (schema_migrations_acme_blog). The app's own state is unchanged, so an app with one folder works as before.
  • Same file names: a file with the same name in two folders is two migrations. PHP cannot load two classes with the same name, so a package declares a namespace in its migration files (namespace Acme\Blog\Migrations;); the class is then Acme\Blog\Migrations\Migrate_migration_<id>_<Description>. Two files of the same name without a namespace stop the command with an error that says so.
  • Names: lower-case letters, digits and underscores, starting with a letter, at most 40 characters, and not app. One name is one folder; a missing folder stops the command with an error.

The output names the folder of each migration that is not the app's:

Text
Running UP migration 20260101000000: CreatePostsTable
Running UP migration 20260115000000 (acme_blog): CreateBlogPosts

and migrate:status adds a Folder column:

Text
-- state: 2 migration(s) ran | latest: 20260115000000 | batch: 1 | backend: file | folders: app, acme_blog

  ID                      Status    Folder     Description
  ---------------------------------------------------------------------
  20260101000000          Ran       app        CreatePostsTable
  20260115000000          Ran       acme_blog  CreateBlogPosts

Seeders and factories

#

A factory describes a typical row; a seeder uses factories (or plain inserts) to fill tables. Both are generated:

Shell
php taphra make:factory Post   # app/Factories/PostFactory.php
php taphra make:seeder Post    # app/Seeds/PostSeeder.php
app/DataStores/PostDataStore.php
<?php
// app/DataStores/PostDataStore.php
namespace App\DataStores;

use Taphra\Traits\Timestamps;

class PostDataStore extends AppDataStore
{
    use Timestamps;

    public $objectName = 'posts';
    protected $fillable = ['title', 'body', 'status'];
}
app/Factories/PostFactory.php
<?php
// app/Factories/PostFactory.php
namespace App\Factories;

use App\DataStores\PostDataStore;
use Taphra\Database\DataStoreFactory;

class PostFactory extends DataStoreFactory
{
    protected $dataStore = PostDataStore::class;

    public function definition(): array
    {
        static $n = 0;
        $n++;

        return [
            'title'  => "Post number $n",
            'body'   => 'Lorem ipsum.',
            'status' => 'draft',
        ];
    }

    public function published(): self
    {
        return $this->state(fn (array $attrs) => ['status' => 'published']);
    }
}

make() returns the attributes without saving (an array of arrays after count()); create() fills a DataStore through $fillable and saves it. state() returns a copy with overrides applied after definition(); arguments to make() and create() are applied last.

app/Seeds/PostSeeder.php
<?php
// app/Seeds/PostSeeder.php
namespace App\Seeds;

use App\Factories\PostFactory;
use Taphra\Database\Seeder;

class PostSeeder extends Seeder
{
    public function run(): void
    {
        (new PostFactory())->count(5)->create();
        (new PostFactory())->published()->count(2)->create();
        $this->info('7 posts seeded.');
    }
}

php taphra db:seed runs App\Seeds\DatabaseSeeder, which calls the others in order:

app/Seeds/DatabaseSeeder.php
<?php
// app/Seeds/DatabaseSeeder.php
namespace App\Seeds;

use Taphra\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([PostSeeder::class]);
    }
}
Shell
php taphra db:seed                     # DatabaseSeeder
php taphra db:seed --class=PostSeeder  # one seeder
php taphra migrate:reset && php taphra db:seed   # start again from empty tables

After php taphra db:seed:

PHP
use App\DataStores\PostDataStore;
use App\Factories\PostFactory;

echo PostDataStore::all()->count(), "\n";                        // 7
echo PostDataStore::where('status', 'published')->count(), "\n"; // 2

$attrs = (new PostFactory())->make(['title' => 'Not saved']);
echo $attrs['title'], ' / ', $attrs['status'], "\n";            // Not saved / draft

DataStore or SqlQuery

#

Use a DataStore (one class per table) for application data: it binds values, applies $fillable, casts, timestamps and soft deletes, and loads relations. Use SqlQuery when a query does not belong to one table: reports, joins across many tables, CTEs, window functions, set operations. Both bind every value. Each has its own page: DataStores, SqlQuery.

Transactions

#

DataStore::transaction() runs a callable inside a transaction on the DataStore's connection: it commits when the callable returns, and rolls back and rethrows when it throws. It returns what the callable returns.

PHP
use App\DataStores\PostDataStore;

$id = PostDataStore::transaction(function () {
    $post = PostDataStore::create(['title' => 'Kept', 'status' => 'draft']);
    PostDataStore::create(['title' => 'Kept too', 'status' => 'draft']);
    return $post['id'];
});

try {
    PostDataStore::transaction(function () {
        PostDataStore::create(['title' => 'Rolled back', 'status' => 'draft']);
        throw new RuntimeException('payment failed');
    });
} catch (RuntimeException $e) {
    echo $e->getMessage(), "\n";                                     // payment failed
}

echo PostDataStore::where('title', 'Rolled back')->count(), "\n";   // 0
echo PostDataStore::all()->count(), "\n";                           // 9

Every DataStore on the same connection shares the transaction, because they share one PDO handle; so does raw SQL on DatabaseConnection::load() for that connection name. Transactions do not nest: call transaction() once, at the outer level. On the connection object the same steps are beginTransaction(), commit() and rollback().

Raw SQL on the connection

#

For a statement neither API covers, the connection runs SQL with ? placeholders and binds the values:

PHP
use Taphra\DatabaseConnection;

$db = DatabaseConnection::load('app_master');

// query($sql, $returnAll = true, $withAliases = true, array $params = [])
$rows = $db->query('SELECT status, COUNT(*) AS n FROM posts WHERE id > ? GROUP BY status ORDER BY status', true, false, [0]);
print_r($rows);
// [['status' => 'draft', 'n' => 7], ['status' => 'published', 'n' => 2]]

$one = $db->query('SELECT title FROM posts WHERE id = ?', false, false, [1]);
echo $one['title'], "\n";                                          // Post number 1

// execute($sql, array $params = []) for writes: returns the number of rows changed
echo $db->execute('UPDATE posts SET status = ? WHERE title = ?', ['published', 'Kept']), "\n";        // 1
echo $db->execute('UPDATE posts SET status = ? WHERE title = ?', ['published', 'No such post']), "\n"; // 0

Pass false as $withAliases to get flat rows; with true (the default) each row is grouped by table name.

execute() returns the number of rows the statement changed, as the database reports it, with or without parameters. A conditional update can use it to tell whether it applied: UPDATE ... WHERE status = 'pending' returns 0 when another request changed the row first. MySQL counts the rows whose values actually changed, so an UPDATE that sets the values a row already has returns 0 there.

Input safety

#

The database layer is built so that request data cannot change the shape of a query:

  • Values are always bound as parameters: in DataStore conditions, the query builder, Criteria, SqlQuery, and the raw SQL methods above.
  • Identifiers and operators are checked. Column names in conditions, orderBy(), groupBy() and JSON paths must be plain names (title, posts.title); operators must come from a fixed list (=, <, LIKE, IN, BETWEEN, IS NULL ...). Anything else throws before a query is built.
  • SQL text goes in only where you write it: the *Raw() methods (whereRaw(), selectRaw(), orderByRaw() ...), string conditions such as find('views > 10'), and the connection's query() and execute(). Write those in code; pass request values as their bindings.
  • $fillable and $guarded decide which keys fill(), create() and the write methods accept from an input array.
PHP
use App\DataStores\PostDataStore;
use Taphra\Db\DataStoreException;
use Taphra\Db\DbException;

$sort = 'title; DROP TABLE posts';   // as if it came from ?sort=
try {
    PostDataStore::where('status', 'draft')->orderBy($sort)->get();
} catch (DataStoreException $e) {
    echo "refused: invalid column name\n";
}

try {
    PostDataStore::where('title', 'OR 1=1 --', 'x')->get();
} catch (DbException $e) {
    echo "refused: operator not allowed\n";
}

// A value is only ever a value:
echo PostDataStore::where('title', "' OR '1'='1")->count(), "\n";   // 0

findOrFail() throws Taphra\Db\RecordNotFoundException when nothing matches, and the framework answers an uncaught one with 404 Not Found:

PHP
// app/Controllers/PostController.php
namespace App\Controllers;

use App\DataStores\PostDataStore;
use Taphra\RestController;

class PostController extends RestController
{
    public function show(int $id): string
    {
        $post = (new PostDataStore())->findOrFail(['id' => $id])->first();
        return $this->json($post);
    }
}
app/Config/routes.yml
GET:
  /posts/{id:\d+}: post/show
PHP
echo docs_request('GET', '/posts/1')->getStatusCode(), "\n";     // 200
echo docs_request('GET', '/posts/999')->getStatusCode(), "\n";   // 404

The full list of input rules, including what $fillable does and does not filter, is in DataStores: input safety.