KScript docs
EN

Databases: KScript.Data

Queries

Retrieving records

Every query starts from the model. ->all() gives every record, and ->get() runs a query you've built:

<import package="KScript.Data" />

<model name="Order" with="Timestamps">
  <field name="customer" type="string" />
  <field name="total" type="number" />
  <field name="status" type="string" default="'open'" />
</model>

<do>$db->create_table(Order)</do>
<do>Order->insert([
    { customer: 'Ada', total: 120 },
    { customer: 'Ben', total: 35, status: 'paid' },
    { customer: 'Ada', total: 60, status: 'paid' },
  ])</do>

<for each="order" in="Order->where(status: 'paid')->get()">
  <echo>{$order.customer}: {$order.total}</echo>
</for>
import KScript.Data

model Order extends Timestamps {
  customer: string
  total: number
  status: string = 'open'
}

$db->create_table(Order)
Order->insert([
  { customer: 'Ada', total: 120 },
  { customer: 'Ben', total: 35, status: 'paid' },
  { customer: 'Ada', total: 60, status: 'paid' },
])

for order in Order->where(status: 'paid')->get() {
  echo "{$order.customer}: {$order.total}"
}

Each step returns a new query, so you may build a query up and reuse it:

<let name="paid" value="Order->where(status: 'paid')" />
<echo value="$paid->count()" />
<echo value="$paid->where(customer: 'Ada')->count()" />
$paid = Order->where(status: 'paid')
echo $paid->count()
echo $paid->where(customer: 'Ada')->count()

To read one record, use ->find() with a key or ->first() with a query. Both give null when nothing matches. ->sole() is for a query that must match exactly one row: it throws ModelNotFound when none do and MultipleRecordsFound when more than one does:

<let name="order" value="Order->find(1)" />
<let name="latest" value="Order->where(customer: 'Ada')->latest()->first()" />
$order = Order->find(1)
$latest = Order->where(customer: 'Ada')->latest()->first()

When a missing record is a mistake, use ->find_or_fail() or ->first_or_fail() instead. They throw a ModelNotFound error, which a route answers with a 404 for you.

If you only need one column, ->pluck() gives it for every row and ->value() gives it for the first:

<let name="names" value="Order->pluck(customer)" />
$names = Order->pluck(customer)

What a query gives

The query reference writes a query method's types with Self, which stands for the model's records. ->find(id): Self? gives an Order or null, ->get(): Self[] a list of them, and ->value(column: Self.fields): Self[column] the type of the field you name, so Order->value(total) is a number. A parameter typed Self.fields takes one of the model's field names, and values...: Self takes fields and values, each checked against its field's type:

<import package="KScript.Data" />

<model name="Order">
  <field name="customer" type="string" />
  <field name="total" type="number" />
</model>

<let name="paid" value="Order->where(total: 'lots')->get()" /> <!-- error: total is a number -->
import KScript.Data

model Order {
  customer: string
  total: number
}

$paid = Order->where(total: 'lots')->get()    // error: total is a number

The editor follows these types along a chain, so after Order->find(1)-> it offers a record's methods, and after Order->find(1). the model's fields. A query on a table with no model, @db('orders'), gives maps with the table's columns, read from your migrations or a model whose table it is.

Conditions

The simplest condition names fields and the values they must equal:

<let name="open_for_ada" value="Order->where(status: 'open', customer: 'Ada')->get()" />
$open_for_ada = Order->where(status: 'open', customer: 'Ada')->get()

A list means any of its values, and null means the field is empty. Enum words don't need quotes:

<let name="active" value="User->where(role: [editor, admin])->get()" />
<let name="no_age" value="User->where(age: null)->get()" />
$active = User->where(role: [editor, admin])->get()
$no_age = User->where(age: null)->get()

For anything else, pass a lambda. Its parameter stands for the row, so $o.total is a column:

<let name="big" value="50" />
<let name="large_orders" value="Order->where(fn(o) => $o.total > $big and $o.status != 'paid')->get()" />
$big = 50
$large_orders = Order->where(fn(o) => $o.total > $big and $o.status != 'paid')->get()

The lambda is turned into SQL. Everything in it that isn't a column, such as $big, is worked out first and sent to the database as a parameter, so a value can never change the SQL. When there is only one condition on the row, you may leave out the lambda and start with a dot:

<let name="a_customers" value="Order->where(.customer->starts_with('A'))->get()" />
$a_customers = Order->where(.customer->starts_with('A'))->get()

A condition may use comparisons, and, or, not, in with a list, ??, arithmetic and ? :. On a column, it may also call ->contains(), ->starts_with(), ->ends_with(), ->lower(), ->upper(), ->trim(), ->count() and ->matches(regex). Anything else is a Query error that says which part can't run in the database, rather than a query that quietly does something different.

A few rules keep conditions working the way they do in a script. $o.x == null is SQL's IS NULL, even when the null comes from a variable. $o.status != 'paid' keeps rows whose status is empty. And / divides as it does in a script, so two whole-number columns can give 3.5.

->or_where() adds another way to match, and ->where_not() keeps the rows that don't match:

<let name="urgent" value="Order->where(status: 'open')->or_where(fn(o) => $o.total > 100)->get()" />
<let name="unpaid" value="Order->where_not(status: 'paid')->get()" />
$urgent = Order->where(status: 'open')->or_where(fn(o) => $o.total > 100)->get()
$unpaid = Order->where_not(status: 'paid')->get()

->when() changes a query only when its test is true, which is useful for optional filters, such as a search box that may be empty:

<let name="results" value="Order->when($search != '', fn(q) => $q->where(.customer->contains($search)))->get()" />
$results = Order->when($search != '', fn(q) => $q->where(.customer->contains($search)))->get()

Ordering, limiting and paging

->order_by() sorts by a field, ascending unless you say desc:

<let name="biggest_first" value="Order->order_by(total: desc)->get()" />
$biggest_first = Order->order_by(total: desc)->get()

->latest() and ->oldest() sort by created_at, or by the key when the model doesn't extend Timestamps. Both also take a field name. ->in_random_order() shuffles the rows, a new order each time: Quote->in_random_order()->first().

->limit() reads at most that many rows, and ->offset() skips rows first. ->select() reads only some columns, and ->distinct() leaves out rows that repeat.

To show results a page at a time, use ->paginate(). It gives one page of records along with what a page of links needs: items, page, per_page, total, last_page, from, to and has_more. The page number may be text, straight from the query string:

<let name="page" value="Order->latest()->paginate(20, $query.page)" />
$page = Order->latest()->paginate(20, $query.page)

Counting and totals

->count() and ->exists() ask the database how many rows match, or whether any do, without reading the rows:

<echo value="Order->where(status: 'open')->count()" />
echo Order->where(status: 'open')->count()

->sum(), ->average(), ->min() and ->max() total a column over the rows that match:

<echo value="Order->where(status: 'paid')->sum(total)" />
echo Order->where(status: 'paid')->sum(total)

Totals per group

->group_by() splits the rows into groups that share a value, and the totals after it give one total per group, as a map keyed by the group's value. It's what every dashboard needs, without writing SQL:

<echo value="Order->group_by(status)->count()" /> <!-- { open: 1, paid: 2 } -->
<echo value="Order->group_by(customer)->sum(total)" /> <!-- { Ada: 180, Ben: 35 } -->
echo Order->group_by(status)->count()        // { open: 1, paid: 2 }
echo Order->group_by(customer)->sum(total)   // { Ada: 180, Ben: 35 }

With more than one column, each total is in a map inside a map, one level per column: Order->group_by(status, customer)->count() gives { open: { Ada: 1 }, paid: { Ada: 1, Ben: 1 } }. Conditions go before ->group_by(), and the totals are ->count(), ->sum(), ->average(), ->min() and ->max(). A group whose value is empty is keyed ''.

Scopes

A query you write often deserves a name. A scope is a model method whose first parameter is query. It adds to the query it's given and returns it, so more steps can follow:

<import package="KScript.Data" />

<model name="Article">
  <field name="title" type="string" />
  <field name="views" type="int" default="0" />
  <field name="published" type="bool" default="false" />

  <fn name="live" params="query" value="$query->where(published: true)" />
  <fn name="popular" params="query, over: int = 100" value="$query->where(fn(a) => $a.views > $over)" />
</model>

<do>$db->create_table(Article)</do>
<echo value="Article->live()->popular(over: 10)->count()" />
import KScript.Data

model Article {
  title: string
  views: int = 0
  published: bool = false

  fn live(query) => $query->where(published: true)
  fn popular(query, over: int = 100) => $query->where(fn(a) => $a.views > $over)
}

$db->create_table(Article)
echo Article->live()->popular(over: 10)->count()

You may call a scope on the model, on a query, or on a relation. Its other parameters work as they do in any function. A scope from a mixin becomes the model's own, and kscript check knows a scope wherever it's called from, including other files.

Changing many rows

Some methods change every row a query matches in a single statement, and give back how many rows changed. They are ->update(), ->increment(), ->decrement(), ->delete(), ->force_delete() and ->restore():

<do>Order->where(status: 'open')->update(status: 'cancelled')</do>
<do>Article->where(published: true)->increment(views, by: 1)</do>
Order->where(status: 'open')->update(status: 'cancelled')
Article->where(published: true)->increment(views, by: 1)

These can't follow ->limit() or ->offset(). That is an Argument error rather than a change to every row. To change only some rows, read their keys first: ->where(id: $query->pluck(id)).

Chunking results

When a query matches more rows than fit comfortably in memory, ->chunk() goes through them a batch at a time. Return false from the function to stop early:

<fn name="send" params="batch: list, n: int">
  <echo>Batch {$n}: {$batch->count()} orders</echo>
</fn>

<do>Order->chunk(100, @send)</do>
fn send(batch: list, n: int) {
  echo "Batch {$n}: {$batch->count()} orders"
}

Order->chunk(100, @send)

Seeing the SQL

->sql() gives the SQL a query would run, and its parameters, without running it. It's a quick way to check what a condition turns into.