Skip to content

Core\Db\Schema::planAgainst

Compares a schema with a database and returns the changes that would make the database match.

Core\Db\Schema::planAgainst reads the tables that the database has and compares them with the schema you wrote. It returns a Core\Db\Plan. Its steps() are the changes, in the order they must run. An empty plan means that the database already matches.

Making a plan only reads. Nothing in the database changes, so a program can make a plan as often as it needs. Each step has the SQL for the change, a grade that says how risky it is, and a sentence that explains the grade. Core\Db\Schema::applySafe runs a plan.

Good to know: a plan never removes a table or a column. When the database has one that the schema does not have, the step is in the plan and its isRefused() is true. No call runs that step.

The examples below show what a schema would change in an empty database, read the grade of each step, and run the check that a program does when it starts.

Parameters

  • $connectionCore\Db\ConnectionThe database to compare with. Planning only reads, so it needs only the db.connect capability this connection was opened with.

Return value

Returns Core\Db\Plan. The plan. Each of its steps() has a grade, Safe, Locking or Destructive, and the complete SQL for the change. A table or column that the database has and this schema does not is a report. It is in the plan with the SQL that would remove it, but no apply ever runs it.

Errors

  • LogicErrorThe database has a type, a default or an identifier that a schema cannot describe, so a plan could not cover every difference.

Examples

The examples below run with this configuration file.

nvs.toml
# The `notes` database is kept in memory. It is deleted when the program ends.
[db.notes]
driver = "sqlite"
path = ":memory:"
# The programs may open the `notes` database and read a plan for it.
[capabilities.db]
connect = ["notes"]

See what a schema would change

<?nvs
// Shows what a schema would change in a database. `planAgainst` compares the
// two and returns the steps. The database is not changed by this.
use Core\Db;
use Core\Db\Plan\Step;
use Core\Db\Schema;
var $db = Db::connect('notes');
var $schema = Schema::fromArray([
'tables' => [
[
'name' => 'notes',
'columns' => [
['name' => 'id', 'type' => 'int64', 'identity' => true],
['name' => 'title', 'type' => 'text(200)'],
],
'primary_key' => ['id'],
],
],
]);
// The database is empty, so the plan has one step: create the table.
var $plan = $schema->planAgainst($db);
echo 'steps: ', Core\Arr::count($plan->steps()), "\n";
// Every step carries the whole statement that makes it.
foreach ($plan->steps() as Step $step) {
echo $step->sql(), "\n";
}
$db->close();
Output
steps: 1
CREATE TABLE "notes" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"title" VARCHAR(200) NOT NULL
);

Read the grade of every step

<?nvs
// Shows how to read what each step of a plan risks before anything runs. A
// `Safe` step cannot lose data. Every step also carries a sentence saying why
// it has the grade it has.
use Core\Db;
use Core\Db\Plan\Step;
use Core\Db\Schema;
var $db = Db::connect('notes');
// The table an earlier release created.
$db->execute('create table notes (id integer not null primary key autoincrement, title varchar(200) not null)', []);
var $schema = Schema::fromArray([
'tables' => [
[
'name' => 'notes',
'columns' => [
['name' => 'id', 'type' => 'int64', 'identity' => true],
['name' => 'title', 'type' => 'text(200)'],
['name' => 'body', 'type' => 'text', 'null' => true],
['name' => 'author', 'type' => 'text(80)'],
],
'primary_key' => ['id'],
],
],
]);
// The schema adds two columns. A column that is allowed to have no value is
// safe to add, and a column that must have one is not.
foreach ($schema->planAgainst($db)->steps() as Step $step) {
if ($step->grade() == Step::Grade::Safe) {
echo 'safe: ', $step->reason(), "\n";
} else {
echo 'not safe: ', $step->reason(), "\n";
}
}
$db->close();
Output
safe: A nullable column with no default is a catalog write on all four: every existing row already has its value, and it is null.
not safe: A NOT NULL column with no default has no value for the rows that are already there, so it fails outright on a table that is not empty. SQLite cannot express this alter, so it is a create-copy-drop-rename rebuild, which copies every row — destructive unconditionally, whatever the change would have cost elsewhere.

Check at start up that the database is up to date

<?nvs
// Shows the check a program runs when it starts. An empty plan means the
// database matches the schema. When it does not, the program prints the
// statements that are missing and stops instead of serving.
use Core\Db;
use Core\Db\Plan\Step;
use Core\Db\Schema;
var $db = Db::connect('notes');
// The table the release before this one created.
$db->execute('create table notes (id integer not null primary key autoincrement, title varchar(200) not null)', []);
var $schema = Schema::fromArray([
'tables' => [
[
'name' => 'notes',
'columns' => [
['name' => 'id', 'type' => 'int64', 'identity' => true],
['name' => 'title', 'type' => 'text(200)'],
['name' => 'written_at', 'type' => 'instant', 'null' => true],
],
'primary_key' => ['id'],
],
],
]);
array<Step> $steps = $schema->planAgainst($db)->steps();
if (Core\Arr::count($steps) == 0) {
echo "the database is up to date\n";
} else {
echo 'the database is behind by ', Core\Arr::count($steps), " step(s):\n";
foreach ($steps as Step $step) {
echo ' ', $step->sql(), "\n";
}
}
$db->close();
Output
the database is behind by 1 step(s):
ALTER TABLE "notes" ADD COLUMN "written_at" TIMESTAMPTZ;