Skip to content

Typed SQL queries

Specified by VIP-80.

A schema database declaration names your tables, and a sql template tagged with it is checked against them when you compile. The compiler reads the SQL, resolves every table and column, checks each ${…} value against the column it meets, and infers the type of the rows. Use it where you would write an @effect/sql query and a row type by hand.

Declare the tables

// db.vibe
export schema Note {
  readonly id: string
  readonly authorId: string
  readonly title: string
  readonly score: number
}
 
export schema User {
  readonly id: string
  readonly name: string
}
 
export schema database AppDb (dialect: "sqlite", naming: "snake_case") {
  table notes: Note {
    primary key (id)
    foreign key (authorId) references users(id)
  }
  table users: User {
    primary key (id)
  }
}
 
export effect function notesBy(authorId: string) {
  return try AppDb.sql`
    SELECT n.id, n.title, u.name AS authorName
    FROM notes n
    LEFT JOIN users u ON u.id = n.author_id
    WHERE n.author_id = ${authorId}
    ORDER BY n.title ASC
  `
}
 
export effect function findNote(id: string) {
  return try AppDb.sql.one`SELECT * FROM notes WHERE id = ${id}`
}
 
export effect function rename(id: string, title: string) {
  return try AppDb.sql.oneOrFail`UPDATE notes SET title = ${title} WHERE id = ${id} RETURNING id, title`
}
 
export effect function titlesOf(ids: ReadonlyArray<string>) {
  return try AppDb.sql`SELECT title FROM notes WHERE id IN ${AppDb.sql.in(ids)}`
}

Each table takes its columns from a schema, so a column's type is the field's type. A branded field keeps its brand: a query cannot compare a note's id with a user's id when the two are different brands. dialect is "postgres", "sqlite" or "mysql". With naming: "snake_case" the SQL says author_id where the schema says authorId; without it the SQL uses the field names. The key clauses are recorded on AppDb.constraints. Queries do not read them yet.

What a query returns

notesBy returns ReadonlyArray<{ readonly id: string; readonly title: string; readonly authorName: string | null }>. The row has one readonly property per selected column, named by its AS alias when it has one. A column that is computed, such as COUNT(*) or score + 1, must be named with AS: SQLite and MySQL return it under the key COUNT(*) and PostgreSQL under count, so without a name it is EK8004. authorName is string | null because users is the optional side of the LEFT JOIN. RIGHT JOIN and FULL JOIN widen their optional sides the same way.

COUNT(*) is a number, SUM, MIN, MAX and AVG are nullable, and COALESCE(a, b) drops the null when a later argument cannot be null. x IN (SELECT c …) is boolean | null when x or c can be null, as SQL has it: a NULL among the rows makes a miss unknown.

AppDb.sql.one returns an Option of the first row. AppDb.sql.oneOrFail returns the row and fails with Cause.NoSuchElementError when there is none. A statement without RETURNING returns rows with no properties.

Every query needs the SqlClient service from effect/sql and can fail with SqlError. Provide the layer of any Effect SQL client where you run the program.

Values are bound, never spliced

A ${…} hole is one bound parameter. The client sends the SQL text and the values separately, so a value can never become SQL. A hole is allowed only where SQL takes a value, and its type must be one value: a string, number, bigint, boolean, the built-in Date, a built-in byte array or null. A type of your own that is named Date or Buffer is not one of them. An object, such as a fragment a client would splice into the text, is EK8005 in every position. A table name, a column name, a keyword or a piece of a quoted string is EK8005.

For a list of values after IN, write AppDb.sql.in(values). The compiler checks the element type against the column, and the client binds every element.

What the compiler checks

CodeMistake
EK8001The SQL does not parse. The error points inside the template.
EK8002A table that is neither declared nor a WITH name of the query.
EK8003A column its table does not have.
EK8004A bare column name that two joined tables share. Qualify it. Also two result columns with one name, such as n.id, u.id, and a computed result column with no name, such as COUNT(*): name each with AS.
EK8005A ${…} hole where SQL takes a name or keyword, a raw list after IN, or a hole whose type is not one SQL value, such as an object or a client's SQL fragment.
EK8006A ${…} value whose type does not fit the column or operator, or an IN (SELECT …) whose selected column cannot be compared with the left side.
EK8007An INSERT whose values do not match its columns, or that leaves out a required column.
EK8008A feature the dialect lacks, such as ILIKE under "sqlite" or RETURNING under "mysql".

The checked grammar is SELECT, INSERT, UPDATE, DELETE, WITH, the four joins, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, RETURNING, ON CONFLICT, and a subquery after IN or in parentheses. UNION is EK8001 today.

Limits today

  • The compiler converts two kinds of value, in the emitted query, by the result column's type. Under "sqlite" and "mysql" a column typed boolean is read back as true or false from the driver's 1 or 0, and under "sqlite" a boolean parameter is bound as 1 or 0. Under "postgres" and "mysql" a column typed number is read back as a number when the driver returns a decimal string or a bigint, as node-postgres does for bigint and numeric: that is what COUNT, SUM and AVG are. A value beyond Number.MAX_SAFE_INTEGER loses precision there; cast it to text in SQL to keep every digit. Every other value arrives as the driver returns it.
  • The number conversion is checked against generated driver rows, not against a running PostgreSQL or MySQL server.
  • naming: "snake_case" changes what the compiler accepts in SQL. Returning authorId for author_id is the client's job: configure its row name transform.
  • An optional schema field is typed T | undefined in a row, and SQL returns null.
  • There is no sql.and for building a WHERE from parts yet.

Coming from Effect

  • AppDb.sql replaces sql<Row> and the hand-written Row. The template still runs through SqlClient, with the same bound parameters.
  • AppDb.sql.in(values) is the client's sql.in(values), with its element type checked.