Skip to content

VIP-80: Compile-Time Checked sql\...`` Tagged Template Queries

Status: accepted by Will, 2026-11-30. Will: "I accept 76 to 81". (Previously open, 2026-11-28.)

Will's words

"and yea let's add typesafe sql queries as a VIP that's a good source of typesafety."

Motivation

SQL queries are one of the largest remaining untyped holes in full-stack TypeScript applications. Today, teams choose between two painful compromises:

  1. **Raw @effect/sql tagged templates (sql\SELECT id, title FROM notes WHERE id = ${id}`):** Great SQL ergonomics and automatic parameterization, but zero compile-time validation of table names, column names, parameter types, JOINnullability, or projected row shapes — typos fail only in production or integration tests, and authors duplicate the result schema manually viaSqlSchema.findAll`.
  2. Query builders / ORMs / external codegen (Drizzle, Prisma, Kysely, sqlc): Either replace real SQL with a verbose TypeScript DSL that lags behind PostgreSQL/SQLite features, or require a separate codegen watcher and live database connection just to get red squiggles.

Because VibeLang owns the Go TypeScript 7 compiler and already has first-class schema declarations (VIP-15) and branded/refined types (VIP-77), the compiler itself can parse and typecheck sql\...`` tagged templates directly against declared table schemas — delivering SQLite/Postgres SQL with full static type safety, zero codegen step, and zero SQL-injection surface.

Decision

1. Table Schema Binding

Tables are declared directly from existing VIP-15 schema types (no duplicate column definitions):

export schema Note {
  readonly id: NoteId
  readonly authorId: UserId
  readonly title: string
  readonly body: string
  readonly archived: boolean
  readonly createdAt: string
}
 
export schema User {
  readonly id: UserId
  readonly name: string
}
 
export schema database AppDb (dialect: "postgres") {
  table notes: Note {
    primary key (id)
    foreign key (authorId) references users(id)
  }
  table users: User {
    primary key (id)
  }
}

2. Typed sql\...`` Queries

Binding a query tag to a declared database schema (const sql = AppDb.sql or sql<AppDb>\...``) enables full compile-time SQL parsing and type inference:

export effect function listNotesByAuthor(authorId: UserId) {
  return try AppDb.sql`
    SELECT n.id, n.title, u.name AS authorName
    FROM notes n
    LEFT JOIN users u ON u.id = n.authorId
    WHERE n.authorId = ${authorId}
      AND n.archived = false
    ORDER BY n.createdAt DESC
  `
}
// Inferred return type:
// ReadonlyArray<{
//   readonly id: NoteId
//   readonly title: string
//   readonly authorName: string | null   // <-- inferred nullable from LEFT JOIN!
// }> ! SqlError ! SqlClient

Single-row and mutation helpers derive exact shapes too:

// Returns Option<Note> ! SqlError ! SqlClient
const maybeNote = try AppDb.sql.one`
  SELECT * FROM notes WHERE id = ${id}
`
 
// INSERT ... RETURNING infers exact inserted row type and checks every column value!
const created = try AppDb.sql.oneOrFail`
  INSERT INTO notes (id, authorId, title, body, archived, createdAt)
  VALUES (${note.id}, ${note.authorId}, ${note.title}, ${note.body}, false, ${now})
  RETURNING *
`

3. What the Compiler Checks Statically

  1. SQL grammar & dialect validity: Parses standard SQL (SELECT, INSERT, UPDATE, DELETE, WITH CTEs, INNER/LEFT/RIGHT/FULL JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT/OFFSET, RETURNING, ON CONFLICT) for "postgres", "sqlite", and "mysql". Syntax errors point at the exact column offset inside the template literal (EK8001).
  2. Table & column resolution: Unknown table (EK8002), unknown column (EK8003), or ambiguous unqualified column across joined tables (EK8004) are compile errors with source spans inside the SQL string.
  3. Interpolated parameter type checking: Every ${expr} hole is checked against the inferred SQL context type (e.g., WHERE n.authorId = ${noteId} rejects passing a NoteId where UserId is expected!).
  4. Exact row-type inference:
    • SELECT a, b AS alias infers { readonly a: T1; readonly alias: T2 }.
    • A result column that is not a plain column (COUNT(*), score + 1, a subquery) must be named with AS (EK8004): drivers disagree on the key such a column gets (COUNT(*) on SQLite and MySQL, count on PostgreSQL). So must two result columns that would share one name. A subquery used as a value needs no name.
    • LEFT JOIN / RIGHT JOIN / FULL JOIN automatically widens nullable side columns to T | null.
    • Null-propagating operators (arithmetic, comparisons, LIKE, ||, IN, BETWEEN, NOT, AND/OR) keep the nullability of their operands: discount + 1 over a nullable discount infers number | null. x IN (SELECT c ...) counts c among its operands: a NULL among the rows makes a miss NULL.
    • Standard SQL aggregates (COUNT(*) -> number, SUM(col) -> number | null, COALESCE(a, b) non-null narrowing) are typed natively.
    • The emitted query converts what a driver answers in another representation, by the result column's type: 0/1 to boolean under "sqlite" and "mysql", and the decimal strings PostgreSQL and MySQL drivers answer for bigint and numeric values (COUNT, SUM, AVG) to number.
  5. SQL-injection prevention by construction: Raw string interpolation into SQL keywords, table names, or column names is rejected (EK8005). Every ${expr} lowers exclusively to a bound parameter passed to @effect/sql's SqlClient ($1, ?, etc.). Dynamic query fragments require explicit safe combinators (sql.in(values), sql.and(predicates)).
  6. Camel/snake column mapping: Optional naming: "snake_case" on schema database maps author_id in SQL to authorId in Vibe schema automatically.

4. Lowering

Every checked AppDb.sql\...`lowers directly to@effect/sql (SqlClient.SqlClient) parameterized queries + optional Schema` decode for branded/refined columns — zero custom runtime SQL parser in the shipped JS bundle:

Effect.flatMap(SqlClient.SqlClient, (sql) =>
  sql<{ readonly id: NoteId; readonly title: string; readonly authorName: string | null }>`
    SELECT n.id, n.title, u.name AS authorName
    FROM notes n
    LEFT JOIN users u ON u.id = n.authorId
    WHERE n.authorId = ${authorId}
      AND n.archived = false
    ORDER BY n.createdAt DESC
  `
)

5. Static Rules

MistakeCode
Malformed SQL syntax inside checked sql\...``EK8001
Unknown table or CTE referenceEK8002
Unknown column referenceEK8003
Ambiguous column name across joined tables, two result columns with one name, or a computed result column without ASEK8004
Interpolated ${expr} in non-value SQL position (identifier/table/keyword)EK8005
Interpolated ${expr} type incompatible with SQL column/operator typeEK8006
INSERT column list and VALUES arity or type mismatch, missing non-default NOT NULL column, or an UPDATE ... SET value that violates the column type or nullabilityEK8007
Dialect-specific feature used under incompatible dialect (e.g. Postgres ILIKE on SQLite, or a non-boolean WHERE/ON condition on Postgres)EK8008

Testing & Verification Plan

  • Go SQL parser + binder unit tests and FuzzSqlTemplateChecker (ensuring arbitrary malformed SQL templates never panic or hang).
  • Differential runtime parity suite running real SQLite (@effect/sql-sqlite-node) and Postgres queries against compiler-inferred row types, verifying runtime rows decode cleanly through derived schemas.
  • Formal verification (Z3 / Lean 4) of the JOIN nullability rules and parameterization invariant (no interpolated expression can ever reach raw SQL text).
  • Compiler acceptance cases (typescript/vibelang/cases/vip80-*) for all EK8001–EK8008 diagnostics.

Open Questions for Will

  1. Should schema database also accept SQL DDL migration files directly (e.g., schema database AppDb from "./migrations/*.sql") so teams with existing SQL migrations don't have to duplicate table definitions in .vibe?
  2. Should AppDb.sql validate runtime row decoding through Schema by default (catching DB drift against where refinements) or offer .unchecked for hot-path queries?