Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Run SQL

Run SQL against a luna's own SQLite database with ctx.sql and ctx.exec, undo part of a handler with ctx.transaction, and keep query handlers read-only.

The typed table methods read and write one table at a time, with conditions that must all hold. For a join, an OR or anything else SQLite can do, run SQL against the luna’s own database.

Query with ctx.sql

ctx.sql is a tagged template. Each ${value} becomes a parameter, so a value from a caller cannot change the statement. The examples on this page use a List whose items table has the columns id, text, an optional note and done.

find: h({ args: { word: t.string() }, query: true }, (ctx, { word }) => {
  const like = `%${word}%`;
  return ctx.sql`
    SELECT id, text FROM items
    WHERE text LIKE ${like} OR note LIKE ${like}
    ORDER BY id`;
}),

It returns the rows as objects keyed by column name. Tables have the names you gave them in the luna type’s schema.

Run a statement with ctx.exec

ctx.exec runs one statement with positional ? parameters in an array, or named :name parameters in an object. It returns { rows, changes, lastInsertRowid }.

checkAll: h({ args: { word: t.string() } }, (ctx, { word }) => {
  const r = ctx.exec(
    "UPDATE items SET done = 1 WHERE text LIKE :like",
    { like: `%${word}%` },
  );
  return { changed: r.changes };
}),

A named parameter’s key may leave out the colon, as like does here. changes counts the rows the statement changed.

Read values as SQLite stores them

SQL returns each value as SQLite holds it, without the conversion the typed methods do. Parameters go the other way: true and false become 1 and 0, a Uint8Array becomes binary data, and an object or array becomes JSON text.

Column ctx.db gives SQL gives
t.bool() true or false 1 or 0
t.json() The parsed value JSON text
t.vector(dims) A Float32Array A Uint8Array of its bytes
t.bytes() Base64 text A Uint8Array

Undo part of a handler with ctx.transaction

A handler’s writes already stay or go together, as The life of a luna explains. ctx.transaction undoes a smaller part: if its function throws, the writes made inside it roll back and the error goes on to you.

import: h({ args: { texts: t.array(t.string()) } }, (ctx, { texts }) => {
  try {
    ctx.transaction(() => {
      for (const text of texts) {
        if (!text.trim()) throw new Error("an empty item");
        ctx.db.items.insert({ text });
      }
    });
    return { added: texts.length };
  } catch {
    return { added: 0 };
  }
}),

The function must be synchronous. Passing an async function fails with ctx.transaction takes a synchronous function (writes can't span an await). Events emitted inside a transaction that throws are taken back too.

Keep writes out of query handlers

A handler marked query: true only reads. A statement that writes is refused, whether it comes through ctx.db, ctx.exec or ctx.sql.

This query tidies the list before counting it. It fails with an error that says attempt to write a readonly database.

openCount: h({ query: true }, (ctx) => {
  ctx.exec("DELETE FROM items WHERE done = 1");
  return ctx.db.items.count();
}),

This one only reads, and works.

openCount: h({ query: true }, (ctx) =>
  ctx.db.items.count({ where: { done: false } }),
),

Move the write into a handler without query. A query may be answered by a read copy of the luna, which The life of a luna describes.

Choose typed methods or SQL

Both run on the same database, in the same handler, and you can mix them.

Use ctx.db for Use SQL for
Reads and writes on one table Joins across tables
Conditions that must all hold OR, subqueries and expressions
Values converted to their TypeScript types Aggregates past count, sum, min and max
Full-text, vector, location and graph search Statements with no typed method, such as in onMigrate

Start with ctx.db, and write SQL where it runs out.

Next steps

Was this page helpful?