Litestone guide / Advanced
Raw SQL
For a predicate the structured where cannot say, $raw takes a sql tagged template. Values are bound as parameters and never concatenated into the statement.
model Product {
id Int
name String
price Float
state String
}
import { sql } from '@frontierjs/litestone'
await db.product.createMany({ data: [
{ name: 'A', price: 30, state: 'CA' },
{ name: 'B', price: 10, state: 'CA' },
{ name: 'C', price: 120, state: 'NY' },
] })
const state = 'CA'
const minPrice = 20
const rows = await db.product.findMany({
where: { $raw: sql`price > iif(state = ${state}, ${minPrice}, 100)` },
orderBy: { name: 'asc' },
})
if (rows.map(r => r.name).join() !== 'A,C') throw new Error('expected A and C')
A value in ${...} is a bound ?, so a caller's text cannot change the shape of the query.
What else it can do
$rawsits beside structured filters, ANDed with them, or insideANDandOR- It works wherever
wheredoes: reads, updates, deletes,count,aggregateandgroupBy - Only a
sqltag value is accepted, at any depth; a plain string is refused by name now()emits the clock in the format aDateTimecolumn holds, anddatetime('now')is refusedjson_extractandjuliandaywork as in SQLite$rawkeeps the model's policies, since it is only a predicate inside the wheredb.sqlruns a whole statement, and on a schema with access rules it needsasSystem()
In depth: Filtering § Raw SQL, § The clock