KScript docs
EN

Databases: KScript.Data

Raw SQL

When you need SQL that a query can't express, @sql runs SQL you write. Each { } inside it is worked out and sent as a parameter, never pasted into the SQL, so it's safe with any value:

<import package="KScript.Data" />

<do>$db->sql('create table if not exists visits (page text, at text)')</do>
<let name="page" value="'/about'" />
<do>$db->sql("insert into visits (page, at) values ({$page}, {@now()->to_string()})")</do>
<echo value="@sql(&quot;select count(*) as n from visits where page = {$page}&quot;)[0].n" />
import KScript.Data

$db->sql('create table if not exists visits (page text, at text)')
$page = '/about'
$db->sql("insert into visits (page, at) values ({$page}, {@now()->to_string()})")
echo @sql("select count(*) as n from visits where page = {$page}")[0].n

A list becomes (?, ?, ?), for use with in. Write {{ and }} for literal braces.

A query gives its rows as maps. If you'd like records of a type instead, pass it: @sql(text, as: User). Any other statement gives how many rows it changed.

Write the SQL inside the call, as above. Text in double quotes that is given to a variable first is filled in at that moment, so its values would be pasted into the SQL. The editor warns you when that happens. To keep SQL in a variable, use single quotes or a ```sql text block.

For a table with no model, @db('visits') is a query whose rows are maps.