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";
lunaLuna
The luna type, which gives the tables their names and types.
LunahandleThreadHandle
What ctx.thread() returned in a handler of a luna of that type.
ThreadHandleReturns an Attached. A handle that is not a string throws a TypeError.
Attached
dbDb
The luna's tables, with the methods of ctx.db.
Dbexec(sql, params?)(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }
Runs one SQL statement, with ? or :name parameters.
(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.
(strings, ...values) => Record<string, unknown>[]transaction(fn)<T>(fn: () => T) => T
Runs a synchronous function as one transaction and returns its result.
<T>(fn: () => T) => TThreadHandle
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 iffnthrows. When another write changed what it read before it ends, it runsfnagain, up to 100 times, then throws. Keepfnfree of other effects.transactionrefuses a function that returns a promise, since writes cannot span anawait.execrefuses statements that start withBEGIN,COMMIT,END,ROLLBACK,SAVEPOINT,RELEASE,ATTACH,DETACHorVACUUM. Usetransactioninstead.- 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. AnAttachedused 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);