KScript docs
EN

Databases: KScript.Data

Models

Defining a model

A model is declared like a type, with model in place of type. Each field becomes a column of the table:

<import package="KScript.Data" />

<model name="Post">
  <field name="title" type="string(max: 200)" />
  <field name="body" type="string" />
  <field name="published" type="bool" default="false" />
  <field name="tags" type="string[]" default="[]" />
</model>
import KScript.Data

model Post {
  title: string(max: 200)
  body: string
  published: bool = false
  tags: string[] = []
}

A field with a default, such as published, may be left out when a record is made. A field marked with ? may be empty (null):

<import package="KScript.Data" />

<model name="User">
  <field name="name" type="string" />
  <field name="age?" type="int" />
</model>
import KScript.Data

model User {
  name: string
  age?: int
}

A model may also have methods. Inside a method, $this and the fields belong to the record it was called on:

<import package="KScript.Data" />

<model name="Post">
  <field name="title" type="string" />
  <field name="body" type="string" />

  <fn name="excerpt" value=".body->truncate(80)" />
</model>
import KScript.Data

model Post {
  title: string
  body: string

  fn excerpt() => .body->truncate(80)
}

Like every declaration, a model may have a /// doc comment above it, which the editor shows when you hover over its name.

Timestamps and soft deletes

Two things many tables want come as mixins that KScript.Data ships. A model extends them, as it would any other base.

Timestamps

KScript.Data ships a Timestamps mixin. A model that extends it gets created_at and updated_at fields. Both are filled in when a record is first saved, and updated_at changes every time it is saved again:

<import package="KScript.Data" />

<model name="Comment" with="Timestamps">
  <field name="text" type="string" />
</model>
import KScript.Data

model Comment extends Timestamps {
  text: string
}

Soft deletes

A model that extends the SoftDeletes mixin doesn't lose a row when a record is deleted. Instead, its deleted_at field is set, and queries leave it out from then on. You may still read deleted records with ->with_trashed(), and bring one back with ->restore():

<import package="KScript.Data" />

<model name="Task" with="SoftDeletes">
  <field name="title" type="string" />
</model>

<do>$db->create_table(Task)</do>
<let name="task" value="Task->create(title: 'Write the report')" />
<do>$task->delete()</do>

<echo value="Task->count()" />
<echo value="Task->with_trashed()->count()" />
import KScript.Data

model Task extends SoftDeletes {
  title: string
}

$db->create_table(Task)
$task = Task->create(title: 'Write the report')
$task->delete()

echo Task->count()
echo Task->with_trashed()->count()

Model options

Options go in brackets after the model's name. An option that is simply on is written as a bare word, and the rest take a value:

<import package="KScript.Data" />

<model name="Post" auto_create="yes" unique="[slug]">
  <field name="title" type="string" />
  <field name="slug" type="string" />
</model>
import KScript.Data

model Post(auto_create, unique: [slug]) {
  title: string
  slug: string
}

When the list grows long, you may put each option on its own line. A trailing comma after the last one is allowed (only on a list written one per line), and the formatter keeps it, so adding another option changes only one line:

<import package="KScript.Data" />

<model name="Attachment" auto_create="yes" unique="[name]">
  <field name="name" type="string" />
</model>
import KScript.Data

model Attachment(
  auto_create,
  unique: [name],
) {
  name: string
}

The block itself holds only fields, validate rules and fn methods. An option written as a line of the block is reported as KS6014, and kscript check --fix moves it into the brackets.

Table names and keys

By default, a model's table is the plural of its name in snake case: User is stored in users, and BlogPost in blog_posts. You may name the table yourself with table::

<import package="KScript.Data" />

<model name="Person" table="people">
  <field name="name" type="string" />
</model>
import KScript.Data

model Person(table: 'people') {
  name: string
}

Every model has a key. Unless you say otherwise, it is an int field called id, numbered by the database and added for you. To use one of your own fields instead, name it with key::

<import package="KScript.Data" />

<model name="Country" key="code">
  <field name="code" type="string(max: 2)" />
  <field name="name" type="string" />
</model>
import KScript.Data

model Country(key: 'code') {
  code: string(max: 2)
  name: string
}

Unique fields and indexes

unique: lists fields that no two records may share. A list inside the list is a set of fields that must be unique together. A save that would break the rule fails with a UniqueViolation error:

<import package="KScript.Data" />

<model name="Member" unique="[email, [team_id, handle]]">
  <field name="email" type="email" />
  <field name="team_id" type="int" />
  <field name="handle" type="string" />
</model>
import KScript.Data

model Member(unique: [email, [team_id, handle]]) {
  email: email
  team_id: int
  handle: string
}

index: lists fields you often search or sort by, so those queries stay fast as the table grows:

<import package="KScript.Data" />

<model name="Order" index="[customer, [status, created_at]]" with="Timestamps">
  <field name="customer" type="string" />
  <field name="status" type="string" />
</model>
import KScript.Data

model Order(index: [customer, [status, created_at]]) extends Timestamps {
  customer: string
  status: string
}

Protecting fields

Two options keep fields safe when records come from, or go to, the outside world. hidden: leaves fields out of JSON, so they never appear in a route's response. guarded: lists fields that ->create($form) and ->update($form) won't set, so a form can't change them:

<import package="KScript.Data" />

<model name="Account" hidden="[password]" guarded="[role]">
  <field name="email" type="email" />
  <field name="password" type="password" />
  <field name="role" type="string" default="'member'" />
</model>
import KScript.Data

model Account(hidden: [password], guarded: [role]) {
  email: email
  password: password
  role: string = 'member'
}

A guarded field may still be set directly on the record, as in $account.role = 'admin'.

Extra keys

When ->create() is given a key the model doesn't have, it drops that key. The extra: option changes this: it may keep the keys or make them an error instead.

Connections and creating tables

connection: puts the model's table in another connection, such as connection: reports. auto_create creates the table and its indexes the first time the model is used, if the table isn't there yet. It suits small apps. For tables that change over time, use migrations.

Every option is also listed in the reference: Models and mixins.

Extending models

Models that share fields, methods or options can take them from a common base with extends. A base that is only there to be extended, with no table of its own, is a mixin, marked with the mixin option:

<import package="KScript.Data" />

<model name="Publishable" mixin="yes" index="[published_at]" with="Timestamps" description="Things that can be published.">
  <field name="published_at?" type="date" />

  <fn name="published" params="query" value="$query->where(fn(p) => $p.published_at != null)" />
</model>

<model name="Page" auto_create="yes" with="Publishable">
  <field name="title" type="string(min: 1, max: 200)" />
</model>

<do>Page->create(title: 'About', published_at: @now())</do>
<echo value="Page->published()->count()" />
import KScript.Data

/// Things that can be published.
model Publishable(mixin, index: [published_at]) extends Timestamps {
  published_at?: date

  fn published(query) => $query->where(fn(p) => $p.published_at != null)
}

model Page(auto_create) extends Publishable {
  title: string(min: 1, max: 200)
}

Page->create(title: 'About', published_at: @now())
echo Page->published()->count()

A model may extend several bases at once. List them in brackets, and later bases take precedence over earlier ones:

<import package="KScript.Data" />

<model name="UID" mixin="yes" key="uid" description="Gives a model a uid as its key.">
  <field name="uid" type="uuid" default="@uuid()" />
</model>

<model name="Publishable" mixin="yes" with="Timestamps" description="Things that can be published.">
  <field name="published_at?" type="date" />
</model>

<model name="Invoice" with="[UID, Publishable]">
  <field name="total" type="number" />
</model>
import KScript.Data

/// Gives a model a uid as its key.
model UID(mixin, key: 'uid') {
  uid: uuid = @uuid()
}

/// Things that can be published.
model Publishable(mixin) extends Timestamps {
  published_at?: date
}

model Invoice extends [UID, Publishable] {
  total: number
}

A model takes its bases' fields, validate rules, methods, scopes and options such as key, unique, index, hidden, guarded and extra. A base may itself extend the built-in mixins, so a model that extends Publishable above has timestamps too. A field or method of the model itself replaces one of the same name, and the model's own options win over all of its bases'.

Some things are never inherited. Each model has its own table, connection and auto_create, because each concrete model has its own table. A model that extends a mixin isn't a mixin itself unless it says so.

You may change a base's option for one use by giving it in brackets after the base's name:

<import package="KScript.Data" />

<model name="Publishable" mixin="yes" hidden="[published_at]">
  <field name="published_at?" type="date" />
</model>

<model name="Draft" with="Publishable(hidden: [])">
  <field name="text" type="string" />
</model>
import KScript.Data

model Publishable(mixin, hidden: [published_at]) {
  published_at?: date
}

model Draft extends Publishable(hidden: []) {
  text: string
}

In XML, the list of bases goes in the model's with attribute.

How fields are stored

Each field type is stored in the column type that suits it, so you rarely need to think about it. A few are worth knowing:

  • string, email, handle and uuid are text. Emails compare without minding case, so JOAN@example.com finds joan@example.com.
  • int, number and float are integers or real numbers, and bool is 0 or 1.
  • date is text in ISO order, so dates sort and compare correctly.
  • An enum is text, and the database checks that it is one of the enum's words.
  • A password is stored as its hash (Argon2id), never as typed.
  • A field whose type is another model, such as author: User, is a relation. It is stored as an author_id column with a foreign key to users.
  • Lists, maps and any other type are stored as JSON.

A computed field, such as label => $first + ' ' + $last, isn't stored at all. It is worked out each time a record is read.