Skip to content
Belikhun edited this page Sep 15, 2026 · 1 revision

🌍 Terra

Terra describes the schema as a stack of layers, each a PHP file that raises a change and knows how to drop it again. Blink's own tables come from layers under core/db/terra/; the application's live in db/terra/. The same layer compiles for MySQL and SQLite.

A layer

php core/blink terra:make create_orders_table --table=orders

writes db/terra/2026_03_14_101500_create_orders_table.php:

<?php

use Blink\Terra\Layer;
use Blink\Terra\Schema;
use Blink\Terra\Table;

return new class extends Layer {
	public function raise(): void {
		Schema::create("orders", function (Table $table) {
			$table -> id();
			$table -> bigInteger("customer_id") -> unsigned() -> index();
			$table -> string("reference", 64) -> unique();
			$table -> decimal("total", 12, 2) -> default(0);
			$table -> string("status", 32) -> default("draft") -> index();
			$table -> json("meta") -> nullable();
			$table -> timestamps();

			$table -> index([ "status", "created" ]);
		});
	}

	public function drop(): void {
		Schema::dropIfExists("orders");
	}
};

A layer's identifier is its file name without the extension. Files sort by name, so the timestamp prefix is what orders them; core and application layers share one sequence. Two files with the same identifier are an error, even in different directories.

drop() is optional; a layer without one is applied but cannot be reverted. shouldRun() can return false to skip a layer on some sites.

Columns

Method Type
id($name = "id") Unsigned auto-incrementing primary key
integer, bigInteger, tinyInteger Integers
boolean Stored as a tiny integer
float, decimal($name, $total, $places) Floating point and fixed point
string($name, $length = 255) Variable-length text with a limit
text, mediumText, longText Text without a limit
json JSON text; validated by MySQL, plain text on SQLite
timestamp An integer epoch, blink's convention; never a database date
timestamps() The created and updated pair every model expects
binary Raw bytes

Modifiers on a column: nullable(), default($value), unsigned(), unique(), index(), primary(), autoIncrement(), after($column), comment($text).

On the table: index($columns, $name), unique($columns, $name), foreign($columns), primary($columns), dropColumn(...$names), dropIndex($name), renameColumn($from, $to), change($name, $type, $options).

Indexes are always separate CREATE INDEX statements on both engines and are named {table}_{columns}_idx, or _uix for a unique one, so the same name exists on MySQL and SQLite and a later dropIndex() finds it on either.

Altering

Schema::table("orders", function (Table $table) {
	$table -> string("channel", 32) -> default("web") -> after("status");
	$table -> dropColumn("meta");
	$table -> renameColumn("reference", "number");
});

Schema::rename("orders", "sales_orders");
Schema::hasTable("orders");
Schema::hasColumn("orders", "channel");
Schema::hasIndex("orders", "orders_status_created_idx");
Schema::run("UPDATE orders SET channel = 'web' WHERE channel IS NULL");

SQLite limits are enforced when the layer compiles, so they fail on your machine rather than on a server: an added column cannot be PRIMARY KEY or UNIQUE (a unique() becomes a follow-up CREATE UNIQUE INDEX), a NOT NULL addition needs a default, dropping a column needs SQLite 3.35, and changing a column's type raises TerraUnsupported with what to do instead.

Applying

php core/blink terra:status            # every layer and when it was applied
php core/blink terra:status --pending
php core/blink terra:apply             # raise what is pending
php core/blink terra:apply --step=1
php core/blink terra:revert            # drop the last batch
php core/blink terra:revert --step=2
php core/blink terra:reset             # drop everything
php core/blink terra:rebuild           # reset, then apply

Applied layers are recorded in the terra table with a batch number; revert drops one batch at a time, newest first, in reverse order within the batch. Applying takes a file lock (Lock::file("terra")), since the locks table is itself created by a layer.

Auto-apply

With CONFIG::$TERRA_AUTO_APPLY on (the default), a web request raises pending layers itself, between the module phases: after every module has declared its layer directories in define(), and before any of them assumes in attach() that its tables exist. A hash of what is on disk is cached in DATA_ROOT/caches/terra.state, so a site with nothing pending never touches the database for this. When another process holds the lock, the request waits up to CONFIG::$TERRA_WAIT seconds, then reports DatabaseNotUpgraded on the error page.

The console never auto-applies. Run terra:apply and read what it says.

A deployment with several hosts sharing a database should turn auto-apply off and run terra:apply once at deploy time; the file lock only serializes workers on one host.

Where layers come from

Core: core/db/terra. Application: db/terra. Anything more, a module adds from define():

public function define(): void {
	$this -> layers(__DIR__ . "/../db/terra");
}

Directories in CONFIG::$TERRA_PATHS are included as well.

Configuration

Setting Default Meaning
CONFIG::$TERRA_AUTO_APPLY true Raise pending layers during web requests
CONFIG::$TERRA_WAIT 10 Seconds a request waits for another process's apply
CONFIG::$TERRA_PATHS [] Extra layer directories

Clone this wiki locally