Skip to content

Core\Db\Schema::fromArray

Reads a schema out of the array that describes it.

Core\Db\Schema::fromArray takes an array of tables and columns and returns a Core\Db\Schema. That value is what you plan against a database or apply to one.

The array has one key, tables, holding a list. A table is name and columns, and may also carry primary_key, unique and indexes. A column is name and type, and may also carry null, identity and default.

Every rule the schema vocabulary has is checked here, so a Core\Db\Schema that exists is one all five databases can be asked for. An array that breaks a rule throws a LogicError naming the rule: a column type nobody has, a table with no columns, an index over a column that is not there.

The value you get back holds the schema in one normalized form. Tables come in name order and every key that was left out is filled in, so two programs that write one schema two ways still get the same array from Core\Db\Schema::toArray.

The examples below write the tables a program needs, catch the error a wrong array throws, and bring a database up to a schema that arrived as JSON.

Parameters

  • $arrayarray<mixed>The schema, as ["tables" => [...]]. A table has name, columns, and optionally primary_key, unique and indexes. A column has name and type, and optionally null, identity and a one-key default. A missing key means the empty list or false.

Return value

Returns Core\Db\Schema. A Core\Db\Schema in normalized form: tables in name order, columns in declaration order, and every optional key filled in. So toArray returns the same array for every way to write one schema. This is what makes two schemas comparable.

Errors

  • LogicErrorA key is missing or has the wrong type of value, a type name is not supported, or an identifier is not a plain identifier. It is also thrown when the schema is not consistent. Examples are a table with no columns, a second identity column, an identity column outside the primary key, or an index on a missing column.

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:"
# Only the third example opens a database. It may open `notes` and change its tables.
# Changing the tables needs the `schema` permission.
[[app]]
entry = "03-bring-a-database-up-to-a-schema-you-read-as-json.nvs"
[app.capabilities.db]
connect = ["notes"]
schema = ["notes"]

Write the tables your program needs

<?nvs
// Shows how to describe the tables a program needs. `fromArray` reads the
// description and returns the schema as a value.
use Core\Db\Schema;
var $schema = Schema::fromArray([
'tables' => [
[
'name' => 'notes',
'columns' => [
// `identity` means the database gives each row its own number.
['name' => 'id', 'type' => 'int64', 'identity' => true],
// `null` means the column is allowed to have no value.
['name' => 'title', 'type' => 'text(200)', 'null' => true],
],
'primary_key' => ['id'],
],
],
]);
// The schema is held in one normalized form. `Core\Db\Schema::toArray` gives it
// back with `null`, `identity`, `unique` and `indexes` filled in.
echo Core\Json::encode($schema->toArray()), "\n";
Output
{"tables":[{"name":"notes","columns":[{"name":"id","type":"int64","null":false,"identity":true},{"name":"title","type":"text(200)","null":true,"identity":false}],"primary_key":["id"],"unique":[],"indexes":[]}]}

Catch the error a wrong array throws

<?nvs
// Shows what happens when the array is not a schema. `fromArray` throws a
// `LogicError` naming the rule that was broken, and the message is what you show
// the person who wrote the array.
use Core\Db\Schema;
// A table needs at least one column.
try {
Schema::fromArray(['tables' => [['name' => 'notes', 'columns' => []]]]);
} catch (LogicError $e) {
echo $e->message, "\n";
}
// `int65` is not a column type. The types are a closed list, so a typo is caught
// here and not by the database.
try {
Schema::fromArray([
'tables' => [
['name' => 'notes', 'columns' => [['name' => 'id', 'type' => 'int65']]],
],
]);
} catch (LogicError $e) {
echo $e->message, "\n";
}
// `tables` holds a list of tables. Here it holds a text.
try {
Schema::fromArray(['tables' => 'notes']);
} catch (LogicError $e) {
echo $e->message, "\n";
}
Output
Core\Db\Schema::fromArray(): table `notes` declares no columns
Core\Db\Schema::fromArray(): `int65` is not one of the column types the vocabulary contains
Core\Db\Schema::fromArray(): the array form's `tables` wants a list

Bring a database up to a schema you read as json

<?nvs
// Shows how a deployment reads the schema it stored as JSON and brings the
// database up to it. `nvs schema dump` writes this form, so the text below is
// what a program keeps in a file next to its code.
use Core\Db;
use Core\Db\Schema;
string $stored = '{"tables":[{"name":"notes","columns":[{"name":"id","type":"int64","identity":true},{"name":"title","type":"text(200)"}],"primary_key":["id"]}]}';
var $schema = Schema::fromArray(Core\Json::decode($stored) as array<mixed>);
var $db = Db::connect('notes');
// The table is not there yet, so the plan has work in it. This prints
// `steps before: 1`.
echo 'steps before: ', Core\Arr::count($schema->planAgainst($db)->steps()), "\n";
// `applySafe` runs the steps that cannot lose data.
$schema->applySafe($db);
// The database now matches the schema, so the new plan is empty. This prints
// `steps after: 0`.
echo 'steps after: ', Core\Arr::count($schema->planAgainst($db)->steps()), "\n";
$db->close();
Output
steps before: 1
steps after: 0