Skip to content

Bias onboarding toward inline config - #148

Draft
mmkal wants to merge 20 commits into
mainfrom
inline-config-docs
Draft

mmkal wants to merge 20 commits into
mainfrom
inline-config-docs

Conversation

@mmkal

@mmkal mmkal commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

sqlfu init now starts a project as one inline TypeScript module: schema, migrations, queries and generated types together. Every CLI command works on it, so starting inline never costs you a capability. Docs, guides, the agent skill and llms.txt teach this shape first. File-backed configs stay supported as the split-out path for bigger projects.

Includes #150 (inline command parity + optional db), which was merged into this branch, not main.

Closes #112.

import {defineConfig, sql} from 'sqlfu';

export default defineConfig({
  db: './app.db', // optional: path or client factory for CLI commands; defaults to .sqlfu/app.db
  definitions: sql`
    create table posts (
      id int,
      slug text,
      body text
    );
  `,
  queries: {
    listPosts: sql`
      select id, slug, body
      from posts
      order by id desc
    `,
  },
});
import {DatabaseSync} from 'node:sqlite';
import {createNodeSqliteClient} from 'sqlfu';
import dbConfig from './sqlfu.config.ts';

const db = dbConfig(createNodeSqliteClient(new DatabaseSync('./.sqlfu/app.db')));
db.migrate();
const posts = db.listPosts(); // typed rows once `sqlfu generate` has run

Inline queries also get .map(...) for result shaping:

getPostCount: sql.one<{result: {post_count: number}}>`
  select count(*) as post_count
  from posts
`.map((row) => ({postCount: row.post_count})),

The mapper runs wherever rows come back (inline bindings, client.all, client.iterate) and throws anywhere they don't (client.run, sql.run/sql.metadata tags, definitions/migration templates, interpolation into another query).

Before / after

sqlfu init before: sqlfu.config.ts + definitions.sql + migrations/ + sql/. After: one inline sqlfu.config.ts.

Database commands on an inline project, before:

$ npx sqlfu migrate
This command requires a file-backed sqlfu config. inline defineConfig modules currently support generate and draft.

After, in a scratch project straight out of sqlfu init + sqlfu draft:

$ npx sqlfu pending
- 2026-10-29T08.38.10.396Z_create_table_posts
$ npx sqlfu migrate
$ npx sqlfu applied
- 2026-10-29T08.38.10.396Z_create_table_posts

Then add a column to definitions without drafting:

$ npx sqlfu check
Repo Drift
Desired Schema does not match Migrations.

Sync Drift
Desired Schema does not match Live Schema.

Recommended next actions
- `sqlfu draft` Create a reviewable migration. (Addresses Repo Drift)
- `sqlfu sync` Update the database from Desired Schema, useful while iterating locally. (Addresses Sync Drift)

Changes

Change Purpose
Onboarding docs rewritten inline-first: packages/sqlfu/README.md (synced to root README), docs/getting-started.md, every docs/guides/*, docs/typegen.md, docs/migration-model.md, docs/cli.md New users see the one-file project first. File-backed config is framed as "split it out later", not the default
Agent surfaces: skills/using-sqlfu/SKILL.md, llms.txt agent notes (website/scripts/sync-llms.mjs), Getting Started blurb (sync-docs.mjs), CLI --help strings (node/cli-router.ts) An agent in a fresh sqlfu init project was being told to edit definitions.sql and sql/*.sql, which don't exist. Also covers #112: use the published package, use the runtime's own adapter (createBunClient on Bun)
sqlfu init (init-preview.ts, runInitCommand in api/internal.ts) scaffolds inline. Companion files come from the contents the user confirmed; an unloadable confirmed config is removed; relative configPath resolves against the project root First run creates the shape the docs teach, and an edited or failed init can't leave a half-initialized project that blocks a retry
Admin UI init keeps a file-backed scaffold (initPreviewFormat: 'file-backed' in ui/router.ts); UI copy and the inline-project errors updated (config.ts, ui/server.ts, packages/ui/src/client.tsx) The UI backend still needs file-backed projects. The error now says that instead of "inline supports generate and draft only"
Inline parser (node/inline-source.ts) accepts export default defineConfig(...) and records hasDb and .map usage The init scaffold has to parse. hasDb decides whether the CLI imports the module at all. .map tracking lets generate reject .map on rowless queries instead of writing a module the parser then rejects
Inline command parity (#150): loadContextConfig builds a full context for inline projects, and readDefinitionsSql/readMigrationsFromContext read the parsed templates (api/internal.ts, node/config.ts, config.ts) migrate, check, sync, pending, applied, find, goto, baseline work on inline configs with file-backed semantics, without special cases in each command
Optional inline db (config-inline.ts), imported lazily through host.importConfigModule (host.ts, node/host.ts, node/config.ts) Same db options as file-backed configs. The import only happens when a command opens the database, so repo-only commands still work on modules that only load in their own runtime (Durable Objects importing cloudflare:workers)
.map(...) on row-returning sql tags (sql.ts, types.ts, adapter-errors.ts, config-inline.ts, typegen/index.ts) Result shaping for inline queries without a hand-written wrapper. Mapper errors surface raw (they're user code, not driver errors). Rowless contexts reject it at type, parse and runtime level
Docs-site sql tag highlighting via a TextMate injection grammar (website/src/sql-tag-grammar.mjs, astro.config.mjs) Inline-first docs are mostly SQL inside TS template literals. This highlights it with the real SQL grammar instead of as a plain string
Tests: init.test.ts, inline-commands-parity.test.ts, config-inline.test.ts, inline-source-robustness.test.ts, inline-generate.test.ts, sql-map.test.ts, api-inline.test-d.ts, website/test/sql-tag-grammar.test.mjs Init round-trip and retry; every db command against default, path and factory db; repo-only commands never importing the module; mapper behavior across client paths; grammar edge cases
tasks/complete/2026-10-29-inline-config-{docs,commands}.md Task logs for this PR and #150

Deliberate limits

  • Modules with several inline defineConfig calls (the multi-Durable-Object shape) error for db commands. generate and draft still work per config.
  • Runtime-managed databases still migrate at runtime with db.migrate(). Reaching inside a Durable Object from the CLI is a separate problem from config shape.
  • The Admin UI backend (npx sqlfu) still requires a file-backed config.

Verification

  • CI jobs sqlfu, ui, ui-floor-compat, website, pg-package
  • Source CLI against a scratch project: init → draft → generate → pending → migrate → applied → check, output as above
  • Website: 8 grammar-injection cases (keywords incl. desc, comments/strings untouched, fragments, multi-line templates); astro build checked for highlighted SQL in both themes
Package size — packed 286.8 kB (+6.2 kB, +2.2%)

Package size

main this PR Δ
packed 280.6 kB 286.8 kB +2.2%
unpacked 1.12 MB 1.14 MB +1.8%
files 226 226 0

dist/vendor/*.js bundles

main this PR Δ
vendor/sha256.js 4.3 kB 4.3 kB 0
vendor/sql-formatter/*.js 94.5 kB 94.5 kB 0
vendor/sqlfu-sqlite-parser/*.js 17.2 kB 17.2 kB 0
vendor/standard-schema/*.js 2.8 kB 2.8 kB 0
vendor/typesql/*.js 134.9 kB 134.9 kB 0

Measured with npm pack --dry-run --json on sqlfu (0.0.0-dev on main vs 0.0.0-dev on this PR).


Claude Code session 39a1bd3a-3b27-4948-a464-dc9a4cf75573 (pre-merge pass; earlier work was in other sessions)

🤖 Generated with Claude Code

@pkg-pr-new

pkg-pr-new Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/sqlfu@148

commit: 670d7be

mmkal and others added 9 commits June 25, 2026 15:04
The init scaffold (and every doc example) uses export default
defineConfig({...}), but the static parser only accepted defineConfig
calls assigned to top-level consts or static class properties. A fresh
'sqlfu init' project failed to load on the very next command - generate,
draft, even re-running init - with 'inline defineConfig(...) calls must
be assigned to top-level const declarations...'.

Default-exported configs now parse with the reference name 'default'.
Added an init round-trip test (init -> load -> generate) so the scaffold
can never again produce a project sqlfu itself refuses to parse.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The mapper previously only ran for inline-config row queries; everywhere
else it typechecked and silently did nothing.

- client.all and client.iterate now apply the mapper (all adapters share
  the wrapClientErrors boundary, so this lands in one place); client.run
  throws if handed a mapped query rather than silently dropping the mapper
- sql.run / sql.metadata tags no longer expose .map at the type level, the
  static parser rejects .map on metadata-mode query tags, and inline
  binding throws if an untyped caller attaches one anyway
- .map is rejected again on definitions and migration content templates,
  where it could never run
- .map<{...}>(fn) with explicit type arguments now parses (it's valid TS
  per the declared map signature, but previously broke generate/draft)
- a one-mode query returning zero rows no longer calls the mapper with
  undefined (which surfaced as a TypeError blamed on the user's config);
  it returns undefined like generated file-backed wrappers
- modeSqlTag no longer builds and discards a second .map property per tag
  evaluation; mapper plumbing reuses the SqlResultMapper type

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The init confirm prompt is editable, but whether definitions.sql,
migrations/ and sql/ got scaffolded was decided by a format flag derived
from the pre-edit preview (and threaded through host -> api -> internal
-> ui). Editing the inline preview into a file-backed config produced a
project pointing at files that were never created; the reverse (the UI's
file-backed preview edited into an inline config) left stray scaffold
files. The CLI init handler passed no format at all, so a file-backed
edit there always broke.

initializeProject now re-loads the project from the contents it just
wrote: file-backed configs get their resolved migrations/definitions/
queries paths scaffolded, inline configs get nothing extra, and a config
that can't be loaded fails init loudly instead of writing a project every
later command rejects. The format flag is gone from the host interface;
initPreviewFormat remains only to pick which preview to show.

Also dedupes the init orchestration (preview -> confirm -> initialize)
that was copy-pasted across api/core.ts, api/internal.ts and
cli-router.ts into one runInitCommand helper - this PR had to apply the
same edit to all three copies, which is how the format bug got in.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The node-sqlite, bun-sqlite and turso guides paired inline defineConfig
examples with 'npx sqlfu migrate' (turso also promised the db factory
works for migrate/check/UI, and showed a db factory inline configs don't
even accept). All of those reject inline projects: inline configs bind
their database at runtime, so there is nothing for the CLI to connect to.

The guides now follow getting-started's flow - draft + generate, with
migrations applied by the runtime db.migrate() call - and the CLI doc and
README command reference state the inline vs file-backed command split
explicitly instead of leaving users to discover it via the error message.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The docs-site sql-in-ts highlighting re-tokenized template contents with
a hand-rolled 26-keyword regex and guessed theme colors from surrounding
tokens. That missed keywords the docs themselves use (desc,
autoincrement, count, as), painted keywords inside SQL strings and
comments, silently no-opped on fragment snippets containing no
const/import/export/from token, and re-highlighted sql`...` text inside
TypeScript comments and strings.

It's now a TextMate injection grammar (inline.sqlfu-sql-tag) registered
via expressive-code's shiki.langs: the template contents embed the real
source.sql grammar, so keyword coverage, string/comment awareness and
theme colors all come from the grammar, in every theme, with no
transformer code. The injection selector excludes comments and strings,
and generic type arguments on mode tags render as TypeScript.

The injected-into grammars (ts/js) and the embedded sql grammar are
preloaded in the expressive-code config because TextMate injections only
bind to grammars that are already registered - lazily loading ts on its
first fence silently disabled the injection.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
mmkal and others added 9 commits July 3, 2026 13:55
sqlfu migrate, check, sync, pending, applied, find, goto and baseline
now work on inline defineConfig projects. loadContextConfig resolves an
inline project into a real SqlfuContext instead of throwing: a
synthesized project config plus the statically-parsed definitions SQL
and migration entries as in-memory repo inputs, consumed via the two
repo-input seams (readDefinitionsSql / readMigrationsFromContext). All
the command internals already only used context.config + context.host,
so they work unchanged - including the .sqlfu/app.db default database
when no db is declared, matching file-backed configs.

Inline configs also accept the same optional db (path or factory) as
file-backed configs. The static parser records whether a defineConfig
object declares db, and only then does the CLI dynamically import the
module (via a new optional host.importConfigModule capability) - so
runtime-only modules like Durable Objects importing cloudflare:workers
are never imported. String paths resolve relative to the config module;
a db on a non-exported config errors with instructions to export it.

Deliberate limits: modules with multiple inline defineConfig calls error
for db commands (that's the runtime-managed multi-DO shape), drafting
for inline stays on the appendInlineMigration path, and the Admin UI
backend remains file-backed-only with an updated error message.

Docs: the CLI/README command-shape notes now describe parity, and the
turso guide's db factory example is back - this time against an API that
actually supports it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Two mapper honesty fixes at the sql/adapter boundary:

- Mapper exceptions thrown by user code in .map(...) were caught by the
  adapter error wrapper and re-thrown as SqlfuError driver errors,
  misattributing the user's own bug to the database (and diverging from
  the inline binding path, which throws them raw). Mappers now run
  outside the driver-error try blocks in all()/iterate(); the no-mapper
  iterate path gets its yield* delegation back.

- Interpolating a mapped query into another query silently dropped the
  inner mapper (the fragment branch of buildSqlQuery copies only
  sql/args). That's unfixable-by-copying — fragment rows never exist as
  such — so it now throws, telling the user to call .map on the outer
  query.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…e module

An ungenerated query like sql`delete from posts`.map(...) parses fine
(bare sql tags allow .map), but generate would annotate it as
sql.run<...> while keeping the .map(...) call — producing a module the
inline parser rejects, so every subsequent command (including the next
watch-mode generate cycle) failed on the file generate itself wrote.

The parser now records whether a template carries .map calls, and
generate reports a per-query failure ("returns no rows, so .map would
never run") instead of writing the self-invalidating tag, using the
same collect-don't-abort failure path as analysis errors.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Two ways initializeProject could leave a project in a broken or silent
state:

- A relative configPath from the programmatic API was written relative
  to cwd but loaded back relative to the project root, so init
  "succeeded" while scaffolding nothing (and the pre-existing-config
  check never fired). The path is now resolved once, against the
  project root, and used for both the write and the reload.

- If the user edited the confirm prompt into something unloadable, the
  broken config was still written, companions and gitignore were
  skipped, and retrying init failed with "already initialized". The
  reload now runs in a try/catch that removes the written file and
  rethrows with the load error, so a failed init is fully retryable.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Declaring db on an inline defineConfig made every command dynamically
import the module at context-load time — including repo-only commands
like check migrationsMatchDefinitions that never touch a database. That
breaks modules importable only in their real runtime (a Durable Object
importing cloudflare:workers). The synthesized project config now
carries a lazy db factory: the import happens only when a command
actually opens the database.

The db read errors also stopped lying: a factory assigned to a const
and re-exported (export default app) now says the name "is not exported
directly" rather than flatly "not exported", and a db expression that
resolves to a falsy value at import time (an unset environment
variable, say) gets its own message instead of being blamed on a
missing export.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The onboarding rewrite made inline config the default `sqlfu init` shape,
but the two surfaces agents read first still described only file-backed
projects: the `using-sqlfu` skill told agents to edit `definitions.sql`
and `.sql` query files, and the llms.txt agent notes pointed at
`definitions.sql`/`migrations/`/`sql/*.sql`. An agent dropped into a
freshly initialized project would look for files that don't exist.

- skills/using-sqlfu/SKILL.md: describe both config shapes (inline
  first), where `draft`/`generate` write their output for each, the
  `db`-opts-into-import caveat for runtime-only modules, `.map(...)`,
  and that `serve` is file-backed only.
- llms.txt agent notes + Getting Started blurb: inline-first wording.
- Both now say to install the published package unless told to test a
  local checkout, and the skill points at the runtime's own adapter
  (`createBunClient` for Bun), covering the remaining asks in #112.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`generate`, `generate --watch`, `sync` and `draft` all work on inline
configs now, but their --help text (and the `check
migrationsMatchDefinitions` failure) still talked about
`definitions.sql`, the `sql/` directory and "migration files" - none of
which exist in a project fresh out of `sqlfu init`. Reword them in
terms of "the definitions", "a migration" and "the configured query
files", which hold for both config shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both tasks' checklists are done; the commands task shipped as #150,
merged into this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mmkal added a commit that referenced this pull request Oct 29, 2026
Findings, rough edges, follow-ups, and a recommendation for #148: keep
init and docs file-backed-first, since that layout drops generate on
TS 7.1 and keeps working with generate before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Clarify minimal agent onboarding for small sqlfu integrations

1 participant