/lunora:lunora-setup-hyperdrivefrom Lunora
Connects an existing Postgres/MySQL database to a Lunora app via Cloudflare Hyperdrive. Covers @lunora/hyperdrive, ctx.sql client setup, wrangler binding, and making external rows live.
Ships in Lunora. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
@lunora/hyperdrive exposes a Cloudflare Hyperdrive binding as a
driver-agnostic ctx.sql client that is available only inside an action. It integrates
a database Lunora doesn't own. Don't use it to replace defineSchema, because you'd lose
realtime, OCC, optimistic updates, the offline queue and the advisors.
ctx.sqlis not reactive. Lunora cannot see this database, so subscriptions do not re-run when its rows change, including rows you write throughctx.sql. Queries are non-deterministic, soctx.sqlexists only onActionCtx. Thehyperdrive_outside_actionadvisor lint flags any use in aquery/mutation. To make the data live, see Step 5. If you instead want Lunora-owned tables stored in Postgres/MySQL and fully reactive, uselunora-setup-hyperdrive-global.
pnpm add @lunora/hyperdrive
pnpm add postgres # → fromPostgresJs ($1, $2 placeholders)
# or: pnpm add pg → fromNodePg ($1, $2)
# or: pnpm add mysql2 → fromMysql2 (?)
The drivers are optional peer dependencies, so none ships with the package. The package never rewrites SQL, so use your driver's native placeholders.
Nothing to write by hand: lunora dev and lunora deploy add a HYPERDRIVE binding
to wrangler.jsonc with a placeholder id.
ctx.sql runs on an embedded Postgres (PGlite), data in
.wrangler/state/lunora-pglite. Install its two optional packages:pnpm add -D @electric-sql/pglite @electric-sql/pglite-socket
To use your own database, set localConnectionString on the binding or
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>; neither is overridden.
lunora deploy the origin and a token that may edit Hyperdrive:LUNORA_HYPERDRIVE_URL="postgres://user:pass@host:5432/db" lunora deploy # gitleaks:allow -- placeholder, not a real secret
(CLOUDFLARE_API_TOKEN with Hyperdrive: Edit, and CLOUDFLARE_ACCOUNT_ID; the variable is
LUNORA_<BINDING>_URL.) Lunora creates the config, or reuses one of the same name, and writes
its id into wrangler.jsonc. The connection string is never written or logged.
To manage the config yourself, run wrangler hyperdrive create my-db --connection-string=...
and put the id in the binding. Validation fails without a binding.
Hyperdrive caches read results (up to 60 s plus 15 s stale by default) and a write does not
invalidate them. For reads that must see your own writes, add a second config created with
--caching-disabled and bind it under another name.
lunora codegen
When ctx.sql is used, codegen adds readonly sql: SqlClient to ActionCtx only. It also
emits a .hyperdrive() method on the generated app builder.
ctx.sql is readonly, so assigning it in a handler is a TS2540 error.
Codegen can't build the client because it depends on your driver, so supply a
thunk instead. It runs once per shard construction, not per request:
import type { HyperdriveLike } from "@lunora/hyperdrive";
import { createHyperdrive, fromPostgresJs } from "@lunora/hyperdrive";
import { defineApp } from "../lunora/_generated/app.js";
const app = defineApp<Env>()
.shard((env) => env.SHARD)
.hyperdrive((env) =>
fromPostgresJs(async () => {
const { default: postgres } = await import("postgres");
return postgres(createHyperdrive(env.HYPERDRIVE as HyperdriveLike).connectionString, { fetch_types: false, max: 5 });
}),
)
.build();
export const ShardDO = app.ShardDO;
The adapters take a loader, not a driver. It runs on the first query, so the
driver stays out of the Worker's startup graph; never import postgres from "postgres" statically in the entry. For pg, the loader may await client.connect() before returning.
Then query from any action:
import { LunoraError } from "lunorash/server";
import { action, v } from "#lunora/_generated/server.js";
export const listLegacyOrders = action.input({ orgId: v.string() }).action(async ({ ctx, args: { orgId } }) => {
if (!ctx.auth.userId) {
throw new LunoraError("UNAUTHORIZED", "not signed in");
}
// `orgId` comes from the client: the join scopes it to orgs the caller belongs to.
return ctx.sql.query<{ id: string; total: number }>(
"select o.id, o.total from orders o join org_members m on m.org_id = o.org where o.org = $1 and m.user_id = $2",
[orgId, ctx.auth.userId],
);
});
Verify: call the action from the studio's function runner and check that it returns rows.
Pick one approach:
A. Projection from an action. This works when your app is the writer. Write the row into a
defineSchema table through a mutation. That write is tracked:
import { LunoraError } from "lunorash/server";
import { internal } from "#lunora/_generated/internal.js";
const [row] = await ctx.sql.query<{ id: string; total: number }>("select id, total from orders where id = $1", [id]);
if (!row) {
throw new LunoraError("NOT_FOUND", `order ${id} not found`);
}
// Re-runs live queries over `orders`. ctx.run* takes a generated reference, not a "file:fn" string.
await ctx.runMutation(internal.orders.upsert, { id: row.id, total: row.total });
B. A .source() table. This works when other systems also write the database. Lunora polls
the external query on the shard's alarm, diffs the result, materializes it into the
DO's SQLite and notifies subscribers, so you don't write an action or a cron:
// lunora/schema.ts
messages: defineTable({ body: v.string(), channelId: v.string() })
.shardBy("channelId")
.source({
binding: "HYPERDRIVE",
query: 'select id, body, channel_id as "channelId" from messages where channel_id = $1',
tenantBy: (shardKey) => [shardKey], // required under .shardBy(): the tenant boundary
}),
// worker entry: one client per binding name
.sourceClient((env, binding) => fromPostgresJs(async () => {
const { default: postgres } = await import("postgres");
return postgres((env[binding] as { connectionString: string }).connectionString, { fetch_types: false, max: 5 });
}))
How .source() behaves:
refresh: { everyMs } to throttle it, or "manual".mode: "full-pull" re-reads the whole slice on every tick, which
works up to about 10k rows. For larger slices, use mode: "incremental" with a
cursor, plus either reconcileEveryMs or softDeleteColumn so deletes are
still detected..global().ctx.sql in a query/mutation. It's action-only. Move the SQL into an action.ctx.sql writes to update subscriptions. They don't. Use Step 5.id at deploy. The deploy stops until LUNORA_<BINDING>_URL is set
(Lunora then creates the config) or the real id is pasted in. An empty id is not
provisioned: wrangler rejects it, so remove the entry and let Lunora add it again.$1 for postgres/pg and ? for mysql2.fetch_types: false. A JS array bound to
= ANY($1) fails as a malformed array literal: bind JSON.stringify(list) to
IN (SELECT jsonb_array_elements_text($1::text::jsonb)). Cast JSON params $1::text::jsonb,
since a bare $1::jsonb gets your string JSON-encoded twice..source() under .shardBy(). Without tenantBy, every tenant's
rows are copied into each shard. defineSchema throws, and the
external_source_unscoped lint fails the build.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
lunora, hyperdrive, external-database, cloudflare-hyperdrive, ctx-sql
npx claudepluginhub anolilab/lunora --plugin lunora15 skills in this plugin
/lunoraRoutes general Lunora requests to the right Lunora skill and gives the shared mental model (codegen loop, generated `api`/`internal` references, review commands, add-on capabilities, the `@lunora/mcp` server). Use when the user asks which Lunora skill to use, gives an underspecified task in a project with a `lunora/` directory or `lunorash`/`@lunora/*` dependencies, asks to review or audit Lunora code, asks about an add-on without its own skill (queues, workflows, agents, AI, flags, payments, notifications), or wants to expose a deployment to an AI agent over MCP./lunora-cloudflare-auditAudits a Lunora app for Cloudflare cost and reliability risk before launch or after a surprise bill. Chains the read-only `lunora doctor`, `lunora advisor` and `lunora insights` signals, then traces what they cannot see — retry and fan-out loops, cron cadence, public routes that reach a metered product (Workers AI, Browser, Containers, Vectorize, R2, D1), preview environments with paid bindings, and missing usage alerts (`lunora cloudflare alerts`). Reports each finding with the billing meter it moves, the smallest fix, and how to verify. Use when the user asks to "audit before launch", "what could blow up our Cloudflare bill", "why did the bill spike", "is this safe to put on the public internet", or "review our cron / queue / AI / workflow cost". For a slow query or OCC conflict use `lunora-performance-audit`; for a failing deploy use `lunora-deploy`./lunora-create-packageBuilds a reusable Lunora capability, either as a registry item that `lunora add` / `lunora registry add` copies into an app's `lunora/`, or as a publishable `@lunora/*` workspace package in the Lunora monorepo. Use when the user wants to package schema + functions + wrangler bindings + env vars for other apps, add or edit an item under `registry/<name>/` (`registry.json`), run `vis generate lunora-package`, or wire a new `ctx.*` capability into codegen./lunora-deployDeploys a Lunora app to Cloudflare Workers + Durable Objects and gets wrangler.jsonc, remote resources and secrets to line up. Covers `lunora deploy` (and `--env`, `--dry-run`, `--migrate`), isolated per-PR previews (`lunora preview deploy | list | delete`), the `lunora doctor` / `lunora verify` / `lunora prepare` preflights, Durable Object bindings (SHARD, SHARD_REGISTRY, SCHEDULER), the `DB` D1 binding and its placeholder id, R2 buckets, production secrets (`lunora env push`, `wrangler secret put`) versus `.dev.vars`, the schema-drift gate, the architecture diff, and rollback with `lunora cloudflare deployments`. Use when the user asks to "deploy", "ship to production", "set up a staging environment", wire CI deploys, or when a deploy fails on a binding, a placeholder `database_id`, an unexported Durable Object class, a missing secret, or "schema drift gate blocked deploy"./lunora-functionsAuthoring rules for Lunora schema and server functions under `lunora/` — `defineSchema`/`defineTable`, `v.*` validators, the generated `query`/`mutation`/`action` builders (and `internal*`), indexes and `withIndex`, the `ctx.db` API, pagination, `ctx.db.related`, opt-in `ctx.*` capabilities, topics, modules, services, and `httpAction`. Use when writing or reviewing files in `lunora/` (`schema.ts`, function files, `http.ts`, `queues.ts`), when asked to "add a query/mutation/action", "add an index", "call one function from another", or "add a webhook endpoint", or when `lunora codegen` reports an error in a function./lunora-migration-helperPlans and runs Lunora schema and data migrations with the widen → migrate → narrow pattern. Covers online data migrations (`defineMigration` in `lunora/migrations.ts`, `lunora migrate create | up | down | status`), what the pre-deploy schema-drift gate treats as breaking and how a migration covers it, `.global()` table DDL on D1 (`lunora migrate generate`) and Hyperdrive, moving a dataset with `lunora migrate d1-to-hyperdrive` (and back with `hyperdrive-to-d1`), and re-keying a `.shardBy()` table. Use when the user wants to make a field required, rename or drop a field or table, change a field's type, add a unique index to a populated table, backfill data, switch a table between root / `.shardBy()` / `.global()`, or when `lunora deploy` reports "schema drift gate blocked".Other plugins' skills for the same job