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

attach

Reach a luna's tables from another thread with attach, the Attached object it returns, and the ThreadHandle that ctx.thread() gives.

attach(Luna, handle) gives a thread your handler started the same tables, SQL and transactions that ctx has, for the luna the handle names.

import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
import { attach, defineLuna, t, table } from "luna";

export const Report = defineLuna({
  name: "Report",
  key: { id: t.string() },
  schema: { totals: table({ part: t.int(), sum: t.float() }, { primaryKey: ["part"] }) },
  handlers: (h) => ({
    build: h({ args: { parts: t.int() } }, async (ctx, { parts }) => {
      const handle = ctx.thread();
      await Promise.all(
        Array.from({ length: parts }, (_, part) =>
          new Promise((done, fail) => {
            const w = new Worker(new URL(import.meta.url), { workerData: { handle, part } });
            w.once("message", done);
            w.once("error", fail);
          }),
        ),
      );
      return ctx.db.totals.count();
    }),
  }),
});

if (!isMainThread) {
  const report = attach(Report, workerData.handle);
  report.db.totals.upsert({ part: workerData.part, sum: 0 });
  parentPort?.postMessage("done");
}

Reference

attach(luna, handle)

import { attach } from "luna";
PropType
lunaLuna

The luna type, which gives the tables their names and types.

TypeLuna
handleThreadHandle

What ctx.thread() returned in a handler of a luna of that type.

TypeThreadHandle

Returns an Attached. A handle that is not a string throws a TypeError.

Attached

PropType
dbDb

The luna's tables, with the methods of ctx.db.

TypeDb
exec(sql, params?)(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }

Runs one SQL statement, with ? or :name parameters.

Type(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }
sql`…`(strings, ...values) => Record<string, unknown>[]

Runs SQL written as a tagged template. Each value becomes a parameter.

Type(strings, ...values) => Record<string, unknown>[]
transaction(fn)<T>(fn: () => T) => T

Runs a synchronous function as one transaction and returns its result.

Type<T>(fn: () => T) => T

ThreadHandle

A string that names one luna for attach. Get it with ctx.thread() in a handler and pass it to a thread, such as in workerData.

Good to know

  • Reads see the latest kept data, and threads read at the same time as each other. Each write goes through the luna one at a time and returns once kept.
  • transaction(fn) sees its own writes and keeps none of them if fn throws. When another write changed what it read before it ends, it runs fn again, up to 100 times, then throws. Keep fn free of other effects.
  • transaction refuses a function that returns a promise, since writes cannot span an await.
  • exec refuses statements that start with BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH or VACUUM. Use transaction instead.
  • A transaction started inside another runs as part of it.
  • A child process can attach with a handle too.
  • In the luna’s own handlers, use ctx.db. An Attached used on the handler’s own thread throws.

Examples

Add to a row from several threads

The transaction reads the row and writes it back, and runs again if another thread wrote it first.

if (!isMainThread) {
  const report = attach(Report, workerData.handle);
  report.db.totals.upsert({ part: workerData.part, sum: 0 });
  report.transaction(() => {
    const row = report.db.totals.get(workerData.part);
    report.db.totals.update({ where: { part: workerData.part }, set: { sum: (row?.sum ?? 0) + 1 } });
  });
  parentPort?.postMessage("done");
}

Count with SQL from a thread

const [{ n }] = report.sql`SELECT count(*) AS n FROM totals WHERE sum > ${0}`;
parentPort?.postMessage(n);

Was this page helpful?