---
title: attach
description: Reach a luna's tables from another thread with attach, the Attached object it returns, and the ThreadHandle that ctx.thread() gives.
related:
  - /lunas/use-more-threads
  - /sdk/ctx
  - /sdk/db
---

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

```ts luna/lunas/report.ts
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)

```ts
import { attach } from "luna";
```

| Prop | Type | Default | Description |
| - | - | - | - |
| `luna` | `Luna` | - | The luna type, which gives the tables their names and types. |
| `handle` | `ThreadHandle` | - | What ctx.thread() returned in a handler of a luna of that type. |

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

### Attached

| Prop | Type | Default | Description |
| - | - | - | - |
| `db` | `Db` | - | The luna's tables, with the methods of ctx.db. |
| `exec(sql, params?)` | `(sql: string, params?: unknown[] \| Record<string, unknown>) => { rows; changes; lastInsertRowid }` | - | Runs one SQL statement, with ? or :name parameters. |
| sql`…` | `(strings, ...values) => Record<string, unknown>[]` | - | Runs SQL written as a tagged template. Each value becomes a parameter. |
| `transaction(fn)` | `<T>(fn: () => T) => T` | - | Runs a synchronous function as one transaction and returns its result. |

### 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.

```ts luna/lunas/report.ts
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

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