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:
- **Raw
@effect/sqltagged 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`. - 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 ! SqlClientSingle-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
- SQL grammar & dialect validity: Parses standard SQL (
SELECT,INSERT,UPDATE,DELETE,WITHCTEs,INNER/LEFT/RIGHT/FULLJOIN,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). - 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. - Interpolated parameter type checking: Every
${expr}hole is checked against the inferred SQL context type (e.g.,WHERE n.authorId = ${noteId}rejects passing aNoteIdwhereUserIdis expected!). - Exact row-type inference:
SELECT a, b AS aliasinfers{ readonly a: T1; readonly alias: T2 }.- A result column that is not a plain column (
COUNT(*),score + 1, a subquery) must be named withAS(EK8004): drivers disagree on the key such a column gets (COUNT(*)on SQLite and MySQL,counton 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 JOINautomatically widens nullable side columns toT | null.- Null-propagating operators (arithmetic, comparisons,
LIKE,||,IN,BETWEEN,NOT,AND/OR) keep the nullability of their operands:discount + 1over a nullablediscountinfersnumber | null.x IN (SELECT c ...)countscamong its operands: aNULLamong the rows makes a missNULL. - 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/1tobooleanunder"sqlite"and"mysql", and the decimal strings PostgreSQL and MySQL drivers answer forbigintandnumericvalues (COUNT,SUM,AVG) tonumber.
- 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'sSqlClient($1,?, etc.). Dynamic query fragments require explicit safe combinators (sql.in(values),sql.and(predicates)). - Camel/snake column mapping: Optional
naming: "snake_case"onschema databasemapsauthor_idin SQL toauthorIdin Vibeschemaautomatically.
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
| Mistake | Code |
|---|---|
Malformed SQL syntax inside checked sql\...`` | EK8001 |
| Unknown table or CTE reference | EK8002 |
| Unknown column reference | EK8003 |
Ambiguous column name across joined tables, two result columns with one name, or a computed result column without AS | EK8004 |
Interpolated ${expr} in non-value SQL position (identifier/table/keyword) | EK8005 |
Interpolated ${expr} type incompatible with SQL column/operator type | EK8006 |
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 nullability | EK8007 |
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
JOINnullability rules and parameterization invariant (no interpolated expression can ever reach raw SQL text). - Compiler acceptance cases (
typescript/vibelang/cases/vip80-*) for allEK8001–EK8008diagnostics.
Open Questions for Will
- Should
schema databasealso 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? - Should
AppDb.sqlvalidate runtime row decoding throughSchemaby default (catching DB drift againstwhererefinements) or offer.uncheckedfor hot-path queries?