Skip to content

Core\Db\Schema::applySafe

$schema->applySafe(Core\Db\Connection $connection): void$schema->applySafe(
    Core\Db\Connection $connection,
): void

Runs the steps a schema needs, as long as every one of them is safe.

Core\Db\Schema::applySafe plans the schema against the database and then runs that plan. A step is safe when it cannot lose data and cannot lock the table: creating a table, adding a column that may be null, adding an index. If one step of the plan is not safe, nothing at all runs. The method throws a LogicError that names the step it refused and the method that would run it.

This is the method a deployment calls. It needs the db.schema capability for the connection's block, which is granted apart from db.connect. Reaching a database is not enough to change its shape.

A table the database has and the schema does not describe is never dropped. The plan reports it, and applySafe leaves it where it is.

The examples below create the tables of a new database, show the refusal of a step that is not safe, and add a column to a table that already holds rows.

Parameters

  • $connectionCore\Db\ConnectionThe database to change. db.schema is granted for the name of its [db.<name>] block. So you cannot use a connection from Core\Db::open here.

Return value

Returns void. Nothing. Afterwards the database matches the schema. Only what the schema does not declare is different: it is reported and not changed.

Errors

  • LogicErrorThe plan has a step that is not Safe, and the message names it. It is also thrown when the connection has no block to grant db.schema for, and for every error that planAgainst throws.
  • RuntimeErrorThe db.schema capability is not granted for this connection's block.

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 change its tables.
# Changing the tables needs the `schema` permission.
[capabilities.db]
connect = ["notes"]
schema = ["notes"]

Create the tables a new database needs

<?nvs
// Shows how a program creates the tables it needs. `applySafe` plans the
// schema against the database and runs the steps. Creating a table is safe.
use Core\Db;
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 this call creates the table.
$schema->applySafe($db);
// The table is there and has no rows yet. This prints `rows: 0`.
echo 'rows: ', $db->query('select id from notes', [])->count(), "\n";
// The database now matches the schema, so there is nothing left to run. This
// prints `steps left: 0`.
echo 'steps left: ', Core\Arr::count($schema->planAgainst($db)->steps()), "\n";
$db->close();
Output
rows: 0
steps left: 0

A step that is not safe

<?nvs
// Shows what happens when one step of the plan is not safe. `applySafe` runs
// no part of the plan and throws a `LogicError`. The plan says why.
use Core\Db;
use Core\Db\Plan\Step;
use Core\Db\Schema;
var $db = Db::connect('notes');
// The table as it is today. `title` holds up to 200 characters.
$db->execute('create table notes (id integer not null primary key autoincrement, title varchar(200) not null)', []);
// The schema asks for a shorter column. SQLite makes that change by copying
// the whole table, so the step can lose data.
var $schema = Schema::fromArray([
'tables' => [
[
'name' => 'notes',
'columns' => [
['name' => 'id', 'type' => 'int64', 'identity' => true],
['name' => 'title', 'type' => 'text(50)'],
],
'primary_key' => ['id'],
],
],
]);
// The message of the error names the step and tells you that
// `applyIncludingRisky` runs the same plan.
try {
$schema->applySafe($db);
echo "the plan ran\n";
} catch (LogicError $error) {
echo "applySafe refused the plan\n";
}
// Every step carries the grade that decided this. This prints
// `the step is destructive`.
foreach ($schema->planAgainst($db)->steps() as Step $step) {
if ($step->grade() == Step::Grade::Destructive) {
echo "the step is destructive\n";
}
}
// The database was not touched, so the change is still waiting. This prints
// `steps left: 1`.
echo 'steps left: ', Core\Arr::count($schema->planAgainst($db)->steps()), "\n";
$db->close();
Output
applySafe refused the plan
the step is destructive
steps left: 1

Add a column to a table that has rows

<?nvs
// Shows the change a deployment makes most often: a new column on a table that
// already holds rows. A column that may be null is a safe step, so `applySafe`
// runs it and every row is kept.
use Core\Db;
use Core\Db\Schema;
var $db = Db::connect('notes');
// The table and the rows an earlier release left here.
$db->execute('create table notes (id integer not null primary key autoincrement, title varchar(200) not null)', []);
$db->execute("insert into notes (title) values ('first note')", []);
$db->execute("insert into notes (title) values ('second note')", []);
// The new column is `written_at`, and it may be 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'],
],
],
]);
$schema->applySafe($db);
// Both rows are still there. This prints `rows: 2`.
echo 'rows: ', $db->query('select id from notes', [])->count(), "\n";
// The rows that were written before the column existed have no time in it.
// This prints `without a time: 2`.
echo 'without a time: ', $db->query('select id from notes where written_at is null', [])->count(), "\n";
$db->close();
Output
rows: 2
without a time: 2