Pikku kysely

From pikkujs/pikku · View interactive version

Pikku kysely is an AI agent skill from the GitHub repository pikkujs/pikku. Kysely queries in Pikku functions (joins, aggregates, transactions), collapsing sequential awaits, @pikku/addon-kysely setup. A non-SQL store is pikku-service-backends; pagination is pikku-list-query.

How to use this skill

Skill file

Pikku Kysely (SQL Database Services)

Writing Queries — the Kysely query builder

In a Pikku function body the injected kysely IS the Kysely<DB> instance — query it directly. Every connection factory below wires the CamelCasePlugin by default, so you write camelCase everywhere in TS (columns, aliases) and raw **snake_case ONLY inside a sql ` literal**. If a project opted out (createNodeSqliteKysely({ camelCase: false })`), that inverts — check how the instance was built before assuming. Kysely is a query builder, NOT an ORM — there are no relations; shape nested data with the JSON helpers below. Never hand-roll SQL strings; never annotate the return type (in Pikku the output zod schema IS the type).

import { sql } from 'kysely'
// Relation helpers are ENGINE-SPECIFIC — import the matching path:
import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/sqlite' // SQLite / libSQL
// import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/postgres' // Postgres
// SELECT + where/orderBy/limit/offset. Terminals: .execute() | .executeTakeFirst()
// | .executeTakeFirstOrThrow(() => new NotFoundError()) — pass an error factory.
const rows = await kysely
  .selectFrom('item')
  .select(['id', 'name', 'quantity'])
  .where('warehouseId', '=', warehouseId)
  .orderBy('name')
  .limit(50)
  .execute()

// JOINS + aliased selects (qualify columns once a join exists)
await kysely
  .selectFrom('stock')
  .innerJoin('item', 'item.id', 'stock.itemId')
  .leftJoin('bin as b', 'b.id', 'stock.binId')
  .select(['stock.id', 'item.name as itemName', 'b.code as binCode'])
  .execute()

// AGGREGATES via the fn helper + groupBy/having. eb.fn.count returns string|number —
// cast if you need a JS number (SQLite: CAST(... AS INTEGER)).
await kysely
  .selectFrom('stock')
  .select((eb) => ['itemId', eb.fn.sum<number>('quantity').as('onHand')])
  .groupBy('itemId')
  .having((eb) => eb.fn.sum('quantity'), '<', 10) // low-stock
  .execute()

// INSERT + RETURNING (one round-trip; works on SQLite & Postgres)
const created = await kysely
  .insertInto('item')
  .values({ name: input.name, warehouseId })
  .returning(['id', 'name'])
  .executeTakeFirstOrThrow()

// UPDATE + RETURNING, DELETE
await kysely
  .updateTable('item')
  .set({ quantity: input.quantity })
  .where('id', '=', input.id)
  .returning(['id', 'quantity'])
  .executeTakeFirstOrThrow()
await kysely.deleteFrom('item').where('id', '=', input.id).execute()

// EXPRESSION BUILDER for and/or; $if for conditional building; sql for raw fragments
await kysely
  .selectFrom('item')
  .selectAll()
  .where((eb) => eb.or([eb('quantity', '=', 0), eb('discontinued', '=', true)]))
  .$if(!!input.search, (qb) => qb.where('name', 'like', `%${input.search}%`))
  .select(sql<number>`quantity * unit_cost`.as('value')) // snake_case ok inside sql``
  .execute()

// NESTED DATA (no relations) — jsonObjectFrom (one) / jsonArrayFrom (many)
await kysely
  .selectFrom('warehouse')
  .select((eb) => [
    'warehouse.id',
    'warehouse.name',
    jsonArrayFrom(
      eb
        .selectFrom('bin')
        .select(['bin.id', 'bin.code'])
        .whereRef('bin.warehouseId', '=', 'warehouse.id')
    ).as('bins'),
  ])
  .execute()

// TRANSACTION — multi-write atomicity. Use trx (not kysely) inside.
await kysely.transaction().execute(async (trx) => {
  await trx
    .updateTable('stock')
    .set({ quantity: 0 })
    .where('itemId', '=', id)
    .execute()
  await trx
    .insertInto('stockMove')
    .values({ itemId: id, delta: -qty })
    .execute()
})

One statement, not five

Count the awaits in the function body before you finish it. In a deployed

stage the database is not in the process — every terminal (.execute(),

.executeTakeFirst()) is a network hop, and five in a row is five latencies the

caller waits through in series. This is the single most common thing wrong with a

generated function body, and it never shows up locally against a socket on the

same machine.

**Sequential is only correct when the second query needs the first one's

VALUES.** Everything else is one of these four:

1. Independent reads → Promise.all. Nothing about the SQL changes; they

just stop queuing behind each other.

// Three hops, in series
const item = await kysely
  .selectFrom('item')
  .where('id', '=', id)
  .selectAll()
  .executeTakeFirst()
const bins = await kysely
  .selectFrom('bin')
  .where('warehouseId', '=', wid)
  .selectAll()
  .execute()
const moves = await kysely
  .selectFrom('stockMove')
  .where('itemId', '=', id)
  .selectAll()
  .execute()

// One hop's worth of latency
const [item, bins, moves] = await Promise.all([
  kysely.selectFrom('item').where('id', '=', id).selectAll().executeTakeFirst(),
  kysely.selectFrom('bin').where('warehouseId', '=', wid).selectAll().execute(),
  kysely.selectFrom('stockMove').where('itemId', '=', id).selectAll().execute(),
])

2. Parent, then its children → jsonArrayFrom / jsonObjectFrom. A loop

containing an await is an N+1: one query per row, so the cost is the size of the

result set rather than the size of the code. **Never await inside a for/map

over rows you just fetched.** The relation helpers in the cookbook above collapse

it into one statement that returns the nested shape your output schema already

wants.

// N+1 — one extra hop per warehouse
const warehouses = await kysely.selectFrom('warehouse').selectAll().execute()
for (const w of warehouses) {
  w.bins = await kysely
    .selectFrom('bin')
    .where('warehouseId', '=', w.id)
    .selectAll()
    .execute()
}
// One hop — see NESTED DATA above

If the shape genuinely cannot be nested, fetch the children in one query with

where('warehouseId', 'in', warehouses.map((w) => w.id)) and group them in JS.

Two hops beats N.

3. Read, decide, write → one write that returns. A select to check

existence followed by an insert is both two hops and a race — another request

can insert between them. returning() and onConflict do it in one statement,

and what comes back tells you which branch happened.

// Two hops and a race
const existing = await kysely
  .selectFrom('item')
  .where('sku', '=', sku)
  .select('id')
  .executeTakeFirst()
if (existing) throw new ConflictError()
await kysely.insertInto('item').values({ sku, name }).execute()

// One hop, and the database arbitrates
const created = await kysely
  .insertInto('item')
  .values({ sku, name })
  .onConflict((oc) => oc.column('sku').doNothing())
  .returning(['id', 'sku'])
  .executeTakeFirst()
if (!created) throw new ConflictError()

The same applies to fetch-then-update: updateTable(...).where(...).returning(...)

in one call, and undefined back means the row was not there — that is your

NotFoundError, not a reason for a preceding select. Many single-row inserts

are one .values([...]) with an array.

4. A read that only feeds the next query's where → a subquery or a CTE.

If the first result never reaches the response and never reaches JS, it should

never have crossed the wire.

// Two hops — the ids are only ever used as a filter
const ids = await kysely
  .selectFrom('bin')
  .where('warehouseId', '=', wid)
  .select('id')
  .execute()
const stock = await kysely
  .selectFrom('stock')
  .where(
    'binId',
    'in',
    ids.map((b) => b.id)
  )
  .selectAll()
  .execute()

// One hop
const stock = await kysely
  .selectFrom('stock')
  .where('binId', 'in', (eb) =>
    eb.selectFrom('bin').select('bin.id').where('bin.warehouseId', '=', wid)
  )
  .selectAll()
  .execute()

.with('name', (db) => ...) builds a CTE when the same intermediate is needed

twice inside one statement. A total alongside a page is a window function —

eb.fn.countAll<number>().over().as('total') — not a second count query.

A transaction does NOT reduce round trips. It adds BEGIN and COMMIT around

whatever is inside it. Reach for it when several writes must land together or not

at all; never as a way to make sequential queries cheaper, and never wrapped round

reads that only needed Promise.all.

Pikku provides SQL database services through six packages:

The last two are runtime adapters rather than service sets: they build the

Kysely<DB> you inject into functions, while the dialect packages above supply

Pikku's own stores. They differ in one place — bun:sqlite cannot register

scalar functions, so createBunSqliteKysely throws if you pass functions.

All implement standard Pikku interfaces from @pikku/core.

Declaring tables

Declare the app's tables in db/tables.ts, with their annotations on the

columns. One declaration gives the SQL, the types and the classification.

pikku meta db says where the file is and what it already declares. You never

need to know where migrations live.

// db/tables.ts
import { defineTables } from '@pikku/core/db'

export const tables = defineTables({
  invoice: {
    columns: {
      invoiceId: { type: 'key', primaryKey: true },
      customerEmail: {
        type: 'text',
        required: true,
        security: 'pii',
        format: 'email',
      },
      paidAt: { type: 'timestamp', kind: 'date' },
    },
    indexes: [{ columns: ['customerEmail'] }],
  },
})

Then:

pikku db generate   # writes the SQL
pikku db migrate    # applies it and regenerates the types

text, string(n), integer, bigint, real, boolean, timestamp,

timestamptz, uuid, json. A column takes required, default,

primaryKey, unique, index, references: 'table.column' + onDelete; a table takes

composite primaryKey, unique and indexes. No Kysely builder calls: the

old statements shape is refused.

again. It writes only the difference: new tables, new columns, new indexes.

written as DROP COLUMN / DROP TABLE behind -- pikku:destructive only once

a person approves (a prompt on a terminal, or --allowDestructive); db migrate

then asks again. Taking data away is a person's decision, so stop and ask.

A changed type, and a new NOT NULL column with no default, are refused with

the reason and nothing is written: declare a new column nullable or with a

default.

'label' } writes RENAME COLUMN and keeps the rows. Delete renamedFrom` once

the migration is applied. It is refused on a column in a key, an index or a

reference.

columns: {...} } writes ALTER TABLE ... RENAME TO ...` and keeps the rows,

renames the indexes, keys and triggers the engine named after the table, and a

foreign key in another table follows (declare it references: 'dashboard.id').

No drop, no approval. Delete renamedFrom once the migration is applied. It is

refused when the migrations hold neither table or both, on a declareOnly

table, and when two tables are renamed from one name.

hand-written table) is a references: 'user.id' with no type: it takes the type the

migrations gave the target. onDelete defaults to restrict.

```typescript

note: {

columns: {

noteId: { type: 'key', primaryKey: true },

userId: { references: 'user.id', onDelete: 'cascade', required: true },

},

},

```

one) can be declared with declareOnly: true to give it types and

annotations. No SQL is written for it; its declared columns must exist in

the migrations with a type that matches, or generate refuses.

warns** (PKU486 pii, PKU487 secret) on pikku db migrate. The column is

still private, which is the default for every unannotated column; the

warning asks you to say so. Whole-token matching on the name: email,

phone, first_name, address, dob, ssn, ip, lat/lng suggest

security: 'pii'; password, api_key, token, client_secret,

credential suggest security: 'secret' with form: 'hashed' (a value you

only verify) or 'wrapped'/'sealed' (a value you read back; wrapped is

decrypted on read by the kysely plugin, writes go through

ClassificationCrypto.encryptColumn()). name warns only on person tables

(user, person, customer, member, contact, profile, employee, account holder).

Any explicit security silences it, private included, except public on a

pii-looking name. Booleans, dates and numbers, and names ending _at,

_count, _id, _type, _ref, _verified, are never flagged. Framework

tables are skipped. There is no config opt-out: annotate the column.

MySQL.** enum, min, max, minLength, maxLength reach the zod schema,

the generated union types and the console hints; pattern is zod only. On

Postgres and MySQL (8.0.16+, older is refused) they become named CHECKs

(<table>_<col>_<hash>_<kind>_check, the hash being of the table+column

pair so names stay unique schema-wide on MySQL, readable front cut when too

long for the engine) on a new table, a new column, or an existing column via

ADD/DROP CONSTRAINT (postgres NOT VALID then VALIDATE, though one

transaction still holds the lock; MySQL swaps a changed check in under an

interim name), each added check preceded by a -- pikku:check-probe line that

migrate runs against existing rows first. A generated-shape check

(..._<8 hex>_<kind>_check) the declaration no longer wants under that exact

name is dropped (add first, then drop, so a bound is never unenforced), which

is what removes the old rule after you rename a table or column by hand; `db

check` reports it, a check with a name of your own is left alone. Aurora MySQL 3.x is

accepted, MariaDB, Aurora 2.x and 5.7 are refused. SQLite gets no CHECK at all:

validation only, and db generate/db check print one notice with the

CHECK SQL to add by hand (constraints a hand-written check in the migrations

already enforces are left out, so the notice goes once you add them) (silence: `validate.rules["db-sqlite-unenforced-constraints"]

= "off"`). A table too large to validate, or data that breaks the check, is for

a person to migrate; say so rather than editing around it. **A declared

constraint is enforced at runtime only where a function uses the generated zod

(<Table>InsertZ / PatchZ / Z) as its input**; a Kysely write that skips

such a function is guarded only by the DB CHECKs (Postgres/MySQL), and on

SQLite not at all, so route values that must be right through a function with

that input. Integer columns are generated as z.number().int(). When a

declared enum differs from the database's, the generated union follows the

declaration and codegen warns PKU488 per column; run pikku db generate.

pii (+ format: 'email'), session.token, account.access_token /

refresh_token / id_token and verification.value are secret + `form:

'plain', account.password is secret + form: 'hashed'`, and the

secrets/credentials ciphertext columns are secret + form: 'plain'.

They apply with no db/tables.ts. To change one, declare the table

declareOnly: true and annotate the column: yours replaces the built-in

column whole. A secret column comes back Secret<...>, so a function that

returns it fails PKU910: strip it. A direct write to account.password

needs unsafeAsHashed(hash) from @pikku/core/classification.

not have. security is public, private, pii or secret.

migrations, and tell you to run generate.

Installation

# Pick your database
yarn add @pikku/addon-kysely @pikku/addon-kysely-postgres     # PostgreSQL
yarn add @pikku/addon-kysely @pikku/addon-kysely-mysql        # MySQL
yarn add @pikku/addon-kysely @pikku/addon-kysely-sqlite       # SQLite (stores)
yarn add @pikku/addon-kysely-node-sqlite                # SQLite on Node
yarn add @pikku/addon-kysely-bun-sqlite                 # SQLite on Bun

API Reference

PostgreSQL Connection — `PikkuKysely`

import { PikkuKysely } from '@pikku/addon-kysely-postgres'

const db = new PikkuKysely<DB>(
  logger: Logger,
  connectionOrConfig: postgres.Sql | postgres.Options | string,
  defaultSchemaName?: string,
  poolConfig?: PostgresConfig   // maxPool, connectTimeout, idleTimeout, maxLifetime, prepare, statementTimeout
)

await db.init()
db.kysely  // Kysely<DB> instance for queries
await db.close()

It builds a postgres.js-backed Kysely with the CamelCasePlugin. Pass an existing

postgres.Sql when something else owns the pool — the wrapper then leaves it

open on close(). poolConfig keys are only forwarded when set, so postgres.js

keeps its own defaults for the rest, and it is ignored entirely when you hand in

an already-constructed connection.

SQLite factories

import { createNodeSqliteKysely } from '@pikku/addon-kysely-node-sqlite'

// Your application DB — CamelCasePlugin on by default
const kysely = createNodeSqliteKysely<DB>({
  filename: 'app.db', // or ':memory:'
  camelCase: true,
  plugins: [], // layered on top
  functions: {}, // scalar UDFs, registered as deterministic (Node only)
})
import { createSQLiteKysely } from '@pikku/addon-kysely-sqlite'

// Pikku's own tables — returns Kysely<KyselyPikkuDB>, not your DB
const pikkuDb = createSQLiteKysely(
  database: SqliteDatabase | (() => Promise<SqliteDatabase>),
  { plugins: [] } // layered ahead of the always-last SerializePlugin
)

These two are not interchangeable. createSQLiteKysely is typed to

KyselyPikkuDB and wires the SerializePlugin (JSON columns in and out) rather

than the CamelCasePlugin, because it exists to back the stores below. Reach for

createNodeSqliteKysely / createBunSqliteKysely for the instance your

functions query.

MySQL and `pikku db`

mysqlUrl in createConfig makes MySQL the third dialect the pikku db

commands drive, with the seed in db/mysql-dev-seed.sql. It behaves like the

other two with four differences:

a pikku_scratch_<hex> one on your server, so the account needs CREATE and

DROP.

the top, so a migration has to be safe to run twice.

FOREIGN KEY (...) REFERENCES ... or none exists.

default. Use varchar(n), or DEFAULT ('...') for an expression default.

db.schema is refused (a MySQL schema is a database), and a standalone bundle

cannot target MySQL yet.

Available Services

Each database variant exports these services with a prefix (Pg, MySQL, SQLite, or base Kysely):

| Service | Interface | Purpose |

| ---------------------- | ------------------------------------------- | ---------------------------------------------- |

| *ChannelStore | ChannelStore | WebSocket channel state persistence |

| *EventHubStore | EventHubStore | Event hub state persistence |

| *WorkflowService | PikkuWorkflowService | Workflow definition storage |

| *WorkflowRunService | WorkflowRunService | Workflow execution tracking |

| *DeploymentService | DeploymentService | Deployment state management |

| *AgentStorageService | AgentStorageService, AgentRunStateService | AI conversation/run storage |

| *AgentRunService | AgentRunService | Agent execution tracking |

| *SecretService | SecretService | Encrypted secret storage (envelope encryption) |

A handful more live only on the base package — there is no Pg/MySQL/SQLite

variant to reach for, you import them from @pikku/addon-kysely whatever the engine:

| Service | Purpose |

| ---------------------------- | ------------------------------------------------------------------- |

| KyselySessionStore | Persisted user sessions |

| KyselyScopeService | Scope and role storage |

| KyselyWebhookService | Outgoing webhook deliveries + attempt history (see pikku-webhook) |

| KyselyCredentialService | Encrypted third-party credentials |

| KyselyAgentRunStateService | AI run state (also implemented by AIStorage) |

| KyselyWorkflowMirror | Mirrors workflow runs into queryable tables |

| KyselyAuditService | Durable audit sink (see pikku-services) |

All services take a Kysely<KyselyPikkuDB> instance in their constructor and have an init() method that creates tables if needed.

Secret Service

Envelope encryption: each secret gets its own DEK, wrapped by a KEK derived from

key plus a stored per-version salt. Keeping previousKey around is what makes

rotation possible — rotateKEK re-wraps every secret from the old key to the

current one and returns the new version, and it throws if no previousKey is

configured.

import { PgKyselySecretService } from '@pikku/addon-kysely-postgres'

const secrets = new PgKyselySecretService(db.kysely, {
  key: 'your-key-encryption-passphrase',
  keyVersion: 2, // defaults to 1
  previousKey: 'the-passphrase-you-are-rotating-away-from',
  audit: true, // log write/delete/rotate through the audit sink
  auditReads: false, // reads too — noisy, off by default
})
await secrets.init()

await secrets.setSecret('api-key', { key: 'sk-...' })
const secret = await secrets.getSecret<{ key: string }>('api-key')
await secrets.hasSecret('api-key')
await secrets.deleteSecret('api-key')
const newVersion = await secrets.rotateKEK()

getSecret hands back a SecretValue<T>, not the bare value — it serializes as

[secret] until something reveals it, which is what stops a secret drifting into

a log line or an audit row. See pikku-services for the reveal rules.

Usage Patterns

PostgreSQL Setup

import {
  PikkuKysely,
  PgKyselyChannelStore,
  PgKyselyLeaseService,
  PgKyselyWorkflowService,
} from '@pikku/addon-kysely-postgres'

const createSingletonServices = pikkuServices(async (config) => {
  const logger = new PinoLogger()
  const db = new PikkuKysely(logger, config.databaseUrl)
  await db.init()

  const channelStore = new PgKyselyChannelStore(db.kysely)
  await channelStore.init()

  const leaseService = new PgKyselyLeaseService(db.kysely)
  await leaseService.init()

  const workflowService = new PgKyselyWorkflowService(db.kysely, {
    leaseService,
  })
  await workflowService.init()

  return {
    config,
    logger,
    database: db,
    channelStore,
    leaseService,
    workflowService,
  }
})

SQLite Setup

import {
  createSQLiteKysely,
  SQLiteKyselyChannelStore,
} from '@pikku/addon-kysely-sqlite'
import Database from 'better-sqlite3'

const kysely = createSQLiteKysely(new Database('app.db'))
const channelStore = new SQLiteKyselyChannelStore(kysely)
await channelStore.init()

MySQL Setup

import {
  MySQLKyselyLeaseService,
  MySQLKyselyWorkflowService,
} from '@pikku/addon-kysely-mysql'

const leaseService = new MySQLKyselyLeaseService(kyselyInstance)
await leaseService.init()

const workflowService = new MySQLKyselyWorkflowService(kyselyInstance, {
  leaseService,
})
await workflowService.init()

Every persistent workflow service takes a required leaseService and locks runs

and steps on it. Pass the same instance you register as the app's

leaseService.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.