TinyJoin logoTinyJoin

setSchema

The setSchema method makes the database's tables, columns, primary keys, and indexes match a Schema, as getSchema returns one, in one change that commits whole or not at all.

setSchema(
  schema: Schema,
  options?: SetSchemaOptions,
): Promise<boolean>
TypeDescription
schemaSchema

The schema to make the database's.

options?SetSchemaOptions

Whether to drop what the schema leaves out.

returnsPromise<boolean>

A Promise resolving to true if the database changed, or false if it already had the schema.

It creates the tables and columns the schema has and the database lacks, renames a table or column from the name its renamedFrom gives while the database still has that name, and changes a column's default, nullability, or VARCHAR length to the schema's. Each table's indexes and foreign keys become exactly the schema's, with keys added once every table they reference exists. Tables and columns the schema leaves out stay, unless the options' drop property is true. Rows keep their values, as ALTER TABLE keeps them: a change no statement could make, to a primary key or a column's runtime type, is refused, and so is one that a row prevents, such as NOT NULL where a row holds NULL.

A schema the database already has changes nothing, so every tab of an application can call setSchema as it starts. A schema whose version is lower than the database's is refused with SCHEMA_OUTDATED, so that a tab still running an older copy of the application cannot undo a newer one's changes; a higher version is recorded. Call it outside a transaction.

Example

import {create} from 'tinyjoin';

const db = await create();
await db.setSchema({
  version: 1,
  tables: [
    {
      name: 'tasks',
      columns: [
        {name: 'id', type: 'text', nullable: false},
        {name: 'title', type: 'text', nullable: false},
        {name: 'done', type: 'boolean', nullable: false, default: false},
      ],
      primaryKey: ['id'],
      indexes: [{name: 'tasks_done', columns: ['done'], unique: false}],
      foreignKeys: [],
    },
  ],
});
await db.close();

Since

v0.5.0