KScript docs
EN

Databases: KScript.Data

Creating and updating records

Creating records

To add a record, call ->create() on the model with its fields. The values are checked, the record is saved, and you get it back with its key filled in:

<import package="KScript.Data" />

<model name="Note" with="Timestamps">
  <field name="text" type="string" />
  <field name="pinned" type="bool" default="false" />
</model>

<do>$db->create_table(Note)</do>

<let name="note" value="Note->create(text: 'Buy milk')" />
<echo value="$note.id" />
import KScript.Data

model Note extends Timestamps {
  text: string
  pinned: bool = false
}

$db->create_table(Note)

$note = Note->create(text: 'Buy milk')
echo $note.id

->create() also takes a map, which is handy for a form: Note->create($form).

If you would like to make a record without saving it yet, call the model like a function. The record is saved when you call ->save():

<let name="note" value="Note(text: 'Buy bread')" />
<do>$note->save()</do>
$note = Note(text: 'Buy bread')
$note->save()

Sometimes you want a record only if it isn't there already. ->first_or_create() finds the first record that matches its first map, or makes one from both maps:

<let name="tag" value="Tag->first_or_create({ name: 'urgent' }, { colour: 'red' })" />
$tag = Tag->first_or_create({ name: 'urgent' }, { colour: 'red' })

->first_or_new() takes the same maps, but a record it makes isn't saved until you call ->save(). ->update_or_create() is the one to reach for when you sync records from another system: it updates the first record that matches with the second map, or makes one from both:

<let name="product" value="Product->update_or_create({ sku: $item.sku }, { price: $item.price, name: $item.name })" />
$product = Product->update_or_create({ sku: $item.sku }, { price: $item.price, name: $item.name })

To add many rows at once, pass a list to ->insert(). Each row is checked the same way ->create() checks one:

<do>Note->insert([
    { text: 'Call the bank' },
    { text: 'Water the plants', pinned: true },
  ])</do>
Note->insert([
  { text: 'Call the bank' },
  { text: 'Water the plants', pinned: true },
])

Updating records

Change a record's fields, then call ->save(). Only the fields that changed are written, along with updated_at:

<let name="note" value="Note->find(1)" />
<do>$note.pinned = true</do>
<do>$note->save()</do>
$note = Note->find(1)
$note.pinned = true
$note->save()

->update() sets fields and saves in one step:

<do>$note->update(text: 'Buy oat milk')</do>
$note->update(text: 'Buy oat milk')

Values are checked as soon as you set them. $note.pinned = 'maybe' fails with a Type error before anything reaches the database.

You may ask a record whether it has unsaved changes with ->is_dirty(), optionally for one field, and ->dirty() names the fields that changed. ->fresh() reads the record again, as the database has it now.

Counters, touching and copies

->increment() and ->decrement() change a number field in the database in one statement, so two requests counting at once both count. The record gets the new value too:

<do>$post->increment(views)</do>
<do>$post->decrement(stock, by: 2)</do>
$post->increment(views)
$post->decrement(stock, by: 2)

->touch() sets updated_at to now and saves, for a model that extends Timestamps. ->replicate() gives an unsaved copy of a record without its key and timestamps. Fields named in except are left for you to fill in:

<let name="copy" value="$post->replicate(except: [slug])" />
<do>$copy.slug = "{$post.slug}-copy"</do>
<do>$copy->save()</do>
$copy = $post->replicate(except: [slug])
$copy.slug = "{$post.slug}-copy"
$copy->save()

Deleting records

->delete() removes a record. On a model that extends SoftDeletes, it marks the record deleted instead. Use ->force_delete() to remove it for good, and ->restore() to bring a soft-deleted record back:

<do>$note->delete()</do>
$note->delete()

Model hooks

A model can run code of its own when its records are saved or deleted: filling in a slug, keeping an audit field, clearing a cache. Declare a hook as a method with one of these names, and no parameters. Inside it, as in any model method, the fields and $this are the record's:

Hook Runs
saving before a record is inserted or updated
creating before a new record is inserted, after saving
created after a new record is inserted
saved after a record is inserted or updated, after created
deleting before a record is deleted, or marked deleted
deleted after a record is deleted
<import package="KScript.Data" />

<model name="Post" with="Timestamps">
  <field name="title" type="string" />
  <field name="slug" type="string" default="''" />
  <field name="is_pinned" type="bool" default="false" />

  <fn name="saving">
    <do>.slug = .title->lower()->replace(' ', '-')</do>
  </fn>

  <fn name="deleting">
    <if $this.is_pinned>
      <throw type="Conflict">Unpin the post before deleting it.</throw>
    </if>
  </fn>
</model>
import KScript.Data

model Post extends Timestamps {
  title: string
  slug: string = ''
  is_pinned: bool = false

  fn saving() {
    .slug = .title->lower()->replace(' ', '-')
  }

  fn deleting() {
    if $this.is_pinned => throw Conflict "Unpin the post before deleting it."
  }
}

A hook that throws stops the write, and the error carries on to the caller. A model with a created, saved or deleted hook writes in a transaction, so an error in one of those undoes the write too. Hooks run for ->create(), ->save(), ->update(), ->delete() and ->insert() on a model, one record at a time. A query that changes many rows in one statement, such as Post->where(...)->update(...), doesn't read the records, so it doesn't run their hooks.