KScript docs
EN

KScript.Data

Databases: models, a query builder, transactions and raw SQL, on SQLite, Postgres, MySQL and MariaDB.

Import it at the top of a script:

<import package="KScript.Data" />
import KScript.Data

A file whose root element is <KScript.Migration> imports it for you.

A .kscript file names a package only in its import: write Migration { }, never KScript.Migration { }.

ElementsStatements

#<AddField>AddField

Adds a column to a table. A required column needs a default when the table has rows.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table to add it to.
name requireda stringThe column's name.
type required'string'|'int'|'number'|'bool'|'date'|'email'|'handle'|'uuid'|'password'|'json'|enumstring, int, number, bool, date, email, handle, uuid, password, json or enum (with values:). Each database stores it the way models do.
maxexpressionThe most characters a string may have: varchar(max).
valuesa list of names: [a, b]The words an enum column may hold: [member, admin], or the enum it takes them from: NoteColor.
optionaltrue or falseLets the column be empty (null).
defaultexpressionWhat the database fills in when a row doesn't give it: 'member', 0, true.
keytrue or falsetrue makes it the table's key.
autotrue or falsetrue on an int key: the database numbers the rows itself.
referencesa stringA foreign key: the table the column points to.
references_columna stringThe column it points to there, the table's key by default.
on_deletecascade|set_null|restrictWhat deleting the row it points to does: cascade (the default for a required column), set_null (the default for one that may be null) or restrict.
Example
<KScript.Migration>
  <AddField table="users" name="bio" type="string" optional="true" />
</KScript.Migration>
import KScript.Data

Migration {
  AddField(table: 'users', name: 'bio', type: string, optional: true)
}

#<AddIndex>AddIndex

Adds an index to a table.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table.
columns requireda list of names: [a, b]The columns, in order: [status, created_at].
uniquetrue or falseStops two rows from having the same values: Index(columns: [email], unique).
Example
<KScript.Migration>
  <AddIndex table="orders" columns="status, created_at" />
</KScript.Migration>
import KScript.Data

Migration {
  AddIndex(table: 'orders', columns: [status, created_at])
}

#<ChangeField>ChangeField

Changes a column to the one described: its type, whether it may be null, its default or what it references. The rows are kept.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table the column is in.
name requireda stringThe column's name.
type required'string'|'int'|'number'|'bool'|'date'|'email'|'handle'|'uuid'|'password'|'json'|enumstring, int, number, bool, date, email, handle, uuid, password, json or enum (with values:). Each database stores it the way models do.
maxexpressionThe most characters a string may have: varchar(max).
valuesa list of names: [a, b]The words an enum column may hold: [member, admin], or the enum it takes them from: NoteColor.
optionaltrue or falseLets the column be empty (null).
defaultexpressionWhat the database fills in when a row doesn't give it: 'member', 0, true.
keytrue or falsetrue makes it the table's key.
autotrue or falsetrue on an int key: the database numbers the rows itself.
referencesa stringA foreign key: the table the column points to.
references_columna stringThe column it points to there, the table's key by default.
on_deletecascade|set_null|restrictWhat deleting the row it points to does: cascade (the default for a required column), set_null (the default for one that may be null) or restrict.
Example
<KScript.Migration>
  <ChangeField table="users" name="bio" type="string" max="500" optional="true" />
</KScript.Migration>
import KScript.Data

Migration {
  ChangeField(table: 'users', name: 'bio', type: string, max: 500, optional: true)
}

#<CreateTable>CreateTable

Makes a table, with a Field for each column, its Index lines and a Key of two columns if it has one.

Holds statements.Holds statements in { }. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down. Holds only <Field>Field, <Index>Index, <Key>Key.

AttributeOptionValueDescription
name requireda stringThe table's name.
Example
<KScript.Migration>
  <CreateTable name="posts">
    <Field name="id" type="int" key="true" auto="true" />
    <Field name="title" type="string" max="200" />
  </CreateTable>
</KScript.Migration>
import KScript.Data

Migration {
  CreateTable(name: 'posts') {
    Field(name: 'id', type: int, key: true, auto: true)
    Field(name: 'title', type: string, max: 200)
  }
}

#<Down>Down

The steps that undo the migration, run by kscript db rollback in place of undoing each step.

Holds statements.Holds statements in { }. Scripts only. Goes inside <KScript.Migration>Migration. Holds only <CreateTable>CreateTable, <DropTable>DropTable, <RenameTable>RenameTable, <AddField>AddField, <DropField>DropField, <RenameField>RenameField, <ChangeField>ChangeField, <AddIndex>AddIndex, <DropIndex>DropIndex, <Sql>Sql, <Run>Run.

Example
<KScript.Migration>
  <Sql up="..." />
  <Down>
    <Sql up="..." />
  </Down>
</KScript.Migration>
import KScript.Data

Migration {
  Sql(up: '...')
  Down {
    Sql(up: '...')
  }
}

#<DropField>DropField

Drops a column, with its indexes. Rollback adds it back, empty.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table.
name requireda stringThe column.
Example
<KScript.Migration>
  <DropField table="users" name="nickname" />
</KScript.Migration>
import KScript.Data

Migration {
  DropField(table: 'users', name: 'nickname')
}

#<DropIndex>DropIndex

Drops the index on these columns.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table.
columns requireda list of names: [a, b]The columns, in order: [status, created_at].
uniquetrue or falseStops two rows from having the same values: Index(columns: [email], unique).
Example
<KScript.Migration>
  <DropIndex table="orders" columns="status" />
</KScript.Migration>
import KScript.Data

Migration {
  DropIndex(table: 'orders', columns: 'status')
}

#<DropTable>DropTable

Drops a table and its rows. Rollback makes it again, empty.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
name requireda stringThe table.
Example
<KScript.Migration>
  <DropTable name="sessions" />
</KScript.Migration>
import KScript.Data

Migration {
  DropTable(name: 'sessions')
}

#<Field>Field

A column of the table CreateTable makes.

Self-closing.A statement on its own. Scripts only. Goes inside <CreateTable>CreateTable.

AttributeOptionValueDescription
name requireda stringThe column's name.
type required'string'|'int'|'number'|'bool'|'date'|'email'|'handle'|'uuid'|'password'|'json'|enumstring, int, number, bool, date, email, handle, uuid, password, json or enum (with values:). Each database stores it the way models do.
maxexpressionThe most characters a string may have: varchar(max).
valuesa list of names: [a, b]The words an enum column may hold: [member, admin], or the enum it takes them from: NoteColor.
optionaltrue or falseLets the column be empty (null).
defaultexpressionWhat the database fills in when a row doesn't give it: 'member', 0, true.
keytrue or falsetrue makes it the table's key.
autotrue or falsetrue on an int key: the database numbers the rows itself.
referencesa stringA foreign key: the table the column points to.
references_columna stringThe column it points to there, the table's key by default.
on_deletecascade|set_null|restrictWhat deleting the row it points to does: cascade (the default for a required column), set_null (the default for one that may be null) or restrict.
Example
<KScript.Migration>
  <CreateTable name="users">
    <Field name="email" type="email" />
  </CreateTable>
</KScript.Migration>
import KScript.Data

Migration {
  CreateTable(name: 'users') {
    Field(name: 'email', type: email)
  }
}

#<Index>Index

An index of the table CreateTable makes.

Self-closing.A statement on its own. Scripts only. Goes inside <CreateTable>CreateTable.

AttributeOptionValueDescription
columns requireda list of names: [a, b]The columns, in order: [status, created_at].
uniquetrue or falseStops two rows from having the same values: Index(columns: [email], unique).
Example
<KScript.Migration>
  <CreateTable name="orders">
    <Field name="status" type="string" />
    <Field name="created_at" type="date" />
    <Index columns="status, created_at" />
  </CreateTable>
</KScript.Migration>
import KScript.Data

Migration {
  CreateTable(name: 'orders') {
    Field(name: 'status', type: string)
    Field(name: 'created_at', type: date)
    Index(columns: [status, created_at])
  }
}

#<Key>Key

A key of two or more columns, for the table CreateTable makes: a pivot table's.

Self-closing.A statement on its own. Scripts only. Goes inside <CreateTable>CreateTable.

AttributeOptionValueDescription
columns requireda list of names: [a, b]The columns: [post_id, tag_id].
Example
<KScript.Migration>
  <CreateTable name="post_tag">
    <Field name="post_id" type="int" />
    <Field name="tag_id" type="int" />
    <Key columns="post_id, tag_id" />
  </CreateTable>
</KScript.Migration>
import KScript.Data

Migration {
  CreateTable(name: 'post_tag') {
    Field(name: 'post_id', type: int)
    Field(name: 'tag_id', type: int)
    Key(columns: [post_id, tag_id])
  }
}

#<KScript.Migration>Migration

A migration file, in database/migrations: the steps that change the tables, run in order by kscript db migrate and undone by kscript db rollback. kscript db diff writes them from the models.

Holds statements.Holds statements in { }. Scripts only. Holds only <CreateTable>CreateTable, <DropTable>DropTable, <RenameTable>RenameTable, <AddField>AddField, <DropField>DropField, <RenameField>RenameField, <ChangeField>ChangeField, <AddIndex>AddIndex, <DropIndex>DropIndex, <Sql>Sql, <Run>Run, <Down>Down.

Example
<KScript.Migration>
  <AddField table="users" name="bio" type="string" optional="true" />
</KScript.Migration>
import KScript.Data

Migration {
  AddField(table: 'users', name: 'bio', type: string, optional: true)
}

#<model>model

Declares a model: a <type> whose records are kept in a database table. User->where(role: admin)->get() reads them, User->create({...}) adds one, and $user->save() writes changes. Its fields are checked by their types and rules on every save.Declares a model: a type whose records are kept in a database table. User->where(role: admin)->get() reads them, User->create({...}) adds one, and $user->save() writes changes. Its fields are checked by their types and rules on every save.
Declares a persisted record. Write model Person(key: id) { id: int }. Model options follow the name and fields go in the body.

Holds statements.Holds statements in { }.

AttributeValueDescription
name requireda new variable's nameThe model's name, such as User: User->where(...) queries it, and its records have its fields.
fieldsfieldsA short model's fields on one line: name: string, email: email. Bigger models list one <field> per line.A short model's fields on one line: name: string, email: email. Bigger models list one name: type per line.
witha stringThe record types, models and mixins this model extends, in order.
mixintrue or falseDeclares reusable fields, methods and options for other models. A mixin has no table.
auto_createtrue or falseCreates this model's table and indexes on first use if the table is missing.
tablea stringThe table its records are kept in. Default: the plural of the name in snake case (User is users, BlogPost blog_posts).
connectiona stringThe database connection, from database.connections in your config. Default: the default connection (main).
keya stringThe field that is the key. Default: id, an int the database numbers, added when the model doesn't declare it.
timestampstrue or falseRetired: extend the Timestamps mixin instead. Only KScript.Data's own script, which declares the mixin, sets it.
soft_deletestrue or falseRetired: extend the SoftDeletes mixin instead. Only KScript.Data's own script, which declares the mixin, sets it.
uniquea stringFields no two records may share: [email], or [email, [team_id, slug]] for a pair that is unique together. Saving a clash fails with UniqueViolation.
indexa stringFields to index, so queries on them are fast: [team_id, [team_id, created_at]].
hiddena stringFields left out of JSON (and so out of route responses): [password].
guardeda stringFields ->create($form) and ->update($form) don't set, so a form can't change them: [role]. Set them on the record instead: user.role = 'admin'.
extradrop|keep|errorKeys ->create() is given that the model doesn't have: drop them (the default), keep them, or make them an error.
descriptiona stringWhat the model is, shown on hover.
OptionValueDescription
mixintrue or falseDeclares reusable fields, methods and options for other models. A mixin has no table.
auto_createtrue or falseCreates this model's table and indexes on first use if the table is missing.
tablea stringThe table its records are kept in. Default: the plural of the name in snake case (User is users, BlogPost blog_posts).
connectiona stringThe database connection, from database.connections in your config. Default: the default connection (main).
keya stringThe field that is the key. Default: id, an int the database numbers, added when the model doesn't declare it.
timestampstrue or falseRetired: extend the Timestamps mixin instead. Only KScript.Data's own script, which declares the mixin, sets it.
soft_deletestrue or falseRetired: extend the SoftDeletes mixin instead. Only KScript.Data's own script, which declares the mixin, sets it.
uniquea stringFields no two records may share: [email], or [email, [team_id, slug]] for a pair that is unique together. Saving a clash fails with UniqueViolation.
indexa stringFields to index, so queries on them are fast: [team_id, [team_id, created_at]].
hiddena stringFields left out of JSON (and so out of route responses): [password].
guardeda stringFields ->create($form) and ->update($form) don't set, so a form can't change them: [role]. Set them on the record instead: user.role = 'admin'.
extradrop|keep|errorKeys ->create() is given that the model doesn't have: drop them (the default), keep them, or make them an error.
descriptiona stringWhat the model is, shown on hover.
Example
<import package="KScript.Data" />
<model name="User" with="Timestamps" unique="email">
  <field name="name" type="string(max: 120)" />
  <field name="email" type="email" />
</model>
import KScript.Data
model User(unique: [email]) extends Timestamps {
  name: string(max: 120)
  email: email
}

#<RenameField>RenameField

Renames a column, keeping its rows.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
table requireda stringThe table.
from requireda stringThe column's name now.
to requireda stringIts new name.
Example
<KScript.Migration>
  <RenameField table="users" from="nick" to="handle" />
</KScript.Migration>
import KScript.Data

Migration {
  RenameField(table: 'users', from: 'nick', to: 'handle')
}

#<RenameTable>RenameTable

Renames a table. Foreign keys that point to it follow.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
from requireda stringThe table's name now.
to requireda stringIts new name.
Example
<KScript.Migration>
  <RenameTable from="people" to="users" />
</KScript.Migration>
import KScript.Data

Migration {
  RenameTable(from: 'people', to: 'users')
}

#<Run>Run

KScript that runs at its place among the steps, in the migration's transaction: to move rows into a table or column made above it before an old one is dropped. db diff can't see what it does, and rollback needs a Down block to undo it.

Holds statements.Holds statements in { }. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

Example
<KScript.Migration>
  <Run>
    <do>@db('users')->where(name: '')->update(name: 'Guest')</do>
  </Run>
</KScript.Migration>
import KScript.Data

Migration {
  Run {
    @db('users')->where(name: '')->update(name: 'Guest')
  }
}

#<Sql>Sql

SQL to run as it is, for what the other steps can't do. db diff doesn't see what it changes, and rollback needs its down: to undo it.

Self-closing.A statement on its own. Scripts only. Goes inside <KScript.Migration>Migration or <Down>Down.

AttributeOptionValueDescription
up requireda stringThe SQL that migrates.
downa stringThe SQL that undoes it.
Example
<KScript.Migration>
  <Sql up="UPDATE users SET active = TRUE" down="UPDATE users SET active = FALSE" />
</KScript.Migration>
import KScript.Data

Migration {
  Sql(up: 'UPDATE users SET active = TRUE', down: 'UPDATE users SET active = FALSE')
}

#<transaction>transaction

Runs its statements in a transaction: what they save is kept when the block ends, and undone if anything in it fails (the error then carries on). A transaction inside another is a savepoint, so only its own changes are undone.

Holds statements.Holds statements in { }.

AttributeOptionValueDescription
retriesexpressionTries the block again this many times when the database is busy or a deadlock stops it.
connectiona stringThe database connection, from database.connections in your config. Default: the default connection.
Example
<import package="KScript.Data" />
<model name="Order">
  <field name="total" type="number" />
</model>
<do>$db->create_table(Order)</do>
<transaction>
  <do>Order->create(total: 10)</do>
</transaction>
<echo>{ Order->count() }</echo>
import KScript.Data
model Order {
  total: number
}
$db->create_table(Order)
transaction {
  Order->create(total: 10)
}
echo Order->count()

Commands

Commands are called with @, in any expression: @name(arguments).

#@db(table?, connection?) → any

A query on a table with no model (@db('users')->where(active: 1)->get() gives maps), or with no table the database itself. connection names one from database.connections in your config.

Arguments can be named: @db(…, connection: …).

Example
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ @db('tasks')->where(done: false)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo @db('tasks')->where(done: false)->pluck(title)

#@queries() → list

The SQL statements this run has sent, oldest first (the last 1000), each as { sql, bindings, database }. In a test, only the test's own: expect(@queries(), count_at_most: 4) catches a page that makes a query per row.
Example
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(done: false)->count()</do>
<echo>{ @queries()->last().sql }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(done: false)->count()
echo @queries()->last().sql

#@sql(text, as?, connection?) → any

Runs SQL. Each in it is worked out and sent as a parameter, never pasted in: @sql("select * from users where email = {$email}"). A query gives its rows as maps (or as: a type); anything else gives how many rows it changed.

Arguments can be named: @sql(…, as: …, connection: …).

Example
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="least" value="3" />
<let name="rows" value='@sql("select title from tasks where points >= {$least} order by title")' />
<echo>{ $rows->map(fn(r) => $r.title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$least = 3
$rows = @sql("select title from tasks where points >= {$least} order by title")
echo $rows->map(fn(r) => $r.title)

Methods

On grouped_query values: ->count(), ->sum(), ->average(), ->min(), ->max()

On query values: ->where(), ->or_where(), ->where_not(), ->when(), ->select(), ->distinct(), ->order_by(), ->latest(), ->oldest(), ->limit(), ->offset(), ->with_trashed(), ->only_trashed(), ->lock_for_update(), ->in_random_order(), ->group_by(), ->skip_locked(), ->get(), ->first(), ->first_or_fail(), ->sole(), ->find(), ->find_or_fail(), ->exists(), ->count(), ->sum(), ->average(), ->min(), ->max(), ->pluck(), ->value(), ->paginate(), ->cursor_paginate(), ->chunk(), ->update(), ->increment(), ->decrement(), ->delete(), ->force_delete(), ->restore(), ->insert(), ->upsert(), ->sql(), ->with(), ->with_count(), ->create(), ->attach(), ->detach(), ->sync(), ->toggle()

On model values: ->where(), ->or_where(), ->where_not(), ->when(), ->select(), ->distinct(), ->order_by(), ->latest(), ->oldest(), ->limit(), ->offset(), ->with_trashed(), ->only_trashed(), ->lock_for_update(), ->in_random_order(), ->group_by(), ->skip_locked(), ->get(), ->first(), ->first_or_fail(), ->sole(), ->find(), ->find_or_fail(), ->exists(), ->count(), ->sum(), ->average(), ->min(), ->max(), ->pluck(), ->value(), ->paginate(), ->cursor_paginate(), ->chunk(), ->update(), ->increment(), ->decrement(), ->delete(), ->force_delete(), ->restore(), ->insert(), ->upsert(), ->sql(), ->with(), ->with_count(), ->create(), ->all(), ->first_or_create(), ->first_or_new(), ->update_or_create(), ->query(), ->fake(), ->fake_many()

On record values: ->save(), ->update(), ->delete(), ->force_delete(), ->restore(), ->fresh(), ->is_dirty(), ->dirty(), ->load(), ->is(), ->increment(), ->decrement(), ->touch(), ->replicate(), ->is_saved()

On password_hash values: ->verify(), ->needs_rehash()

On database values: ->table(), ->sql(), ->tables(), ->describe_table(), ->has_table(), ->create_table(), ->drop_table(), ->transaction()

Variables

VariableTypeDescription
$dbdatabaseThe default database connection: $db->table('users'), $db->tables(), $db->create_table(User). With no config it is SQLite in data/app.sqlite in the project folder; database.connections in your config sets others.

Models and mixins

KScript.Data ships these, written in KScript:

  • Timestamps, a mixin: Adds created_at and updated_at to a model. Both are set when a record is first saved, and updated_at changes every time it is saved again.
  • SoftDeletes, a mixin: Adds deleted_at to a model: ->delete() sets it instead of removing the row, and queries leave those records out. ->with_trashed() keeps them, ->restore() brings one back and…

Every option a model takes and every built-in mixin: Models and mixins.