TypeScript and JavaScript (ESLint)¶
@sqlty/eslint-plugin runs the
sqlty engine on the sql tagged templates of TypeScript and JavaScript, as ESLint
lints them. It reads your schema from .sql files, so it needs no database: not in
CI, not in a pre-commit hook, not in the editor. Try it in the
playground, under the "TypeScript (ESLint plugin)" example.
npm install --save-dev eslint @typescript-eslint/parser @sqlty/eslint-plugin
Not on npm yet
@sqlty/eslint-plugin is published from the next release on. Until then, try it in the
playground.
What it solves¶
TypeScript sees a query as a string, so it checks nothing inside it. Each problem below compiles, passes review, and shows up at runtime.
A misspelled column or table fails only at runtime¶
The plugin reports it where the template writes it, with the fix as a suggestion, as you type and in CI, before the query runs.
Row types drift from the schema¶
The row type comes from the schema: eslint --fix writes it after the tag, and a
migration that changes a column flags every query whose row type it breaks.
The driver returns another type than the column's¶
bigint and numeric arrive as strings, an enum array as text in node-postgres. The row
type says what the driver hands you, not the SQL type.
Checking queries needs a database¶
The schema is read from .sql files, so the check runs in a pre-commit hook, a fork's CI
or an editor with no PostgreSQL to connect to.
A coding agent gets no feedback on the SQL it writes¶
An agent's sandbox rarely has the database, yet npx eslint . names the wrong column, the
line and the fix, npx eslint . --fix writes the row types, and --format json reads as
data. The answer depends only on the schema and the code, so a retry gets the same one.
Configure¶
// eslint.config.js
import parser from "@typescript-eslint/parser";
import sqlty from "@sqlty/eslint-plugin";
const check = ["error", { schema: "schema.sql", driver: "postgres", targets: [{ tag: "sql", transform: "{type}[]" }] }];
export default [
{ files: ["**/*.js"], plugins: { sqlty }, rules: { "sqlty/check-sql": check } },
{ files: ["**/*.ts"], languageOptions: { parser }, plugins: { sqlty }, rules: { "sqlty/check-sql": check } },
];
What it reports¶
A typo is reported where the template writes it, with the fix as a suggestion:
const sql = postgres();
export const recent = () => sql`SELECT id, emial FROM users ORDER BY id DESC`;
// ^^^^^ column `emial` does not exist in `users`; did you mean `email`?
In TypeScript, a query without its row type, or with one that no longer matches the
query, gets it from eslint --fix:
export const user = (id: number) =>
sql<{ id: number; name: string; email: string | null }[]>`SELECT id, name, email FROM users WHERE id = ${id}`;
Each interpolation is a parameter ($1, $2, ...). JavaScript has no type
arguments, so a .js file gets the SQL problems only.
A type alias or interface of the same file is read as the type it names, so queries that return the same row can share one. Its keys follow the query's columns, in their order:
type User = { id: number; name: string; email: string | null };
export const user = (id: number) => sql<User[]>`SELECT id, name, email FROM users WHERE id = ${id}`;
Values the parameter cannot take¶
With type information, each interpolated value is checked against the parameter it fills,
as sqlty check checks Python parameters. Turn it on with parserOptions.projectService:
// eslint.config.js
{ files: ["**/*.ts"], languageOptions: { parser, parserOptions: { projectService: true } }, plugins: { sqlty }, rules: { "sqlty/check-sql": check } },
const age: string = "forty";
sql`SELECT id FROM person WHERE age > ${age}`;
// ^^^ parameter 1 is 'forty', which is not valid input for integer
A string, number, bigint or boolean literal, a const bound to one, a Date, null and
undefined are read as the driver sends them: against an enum's labels or a
CHECK (col IN (...)), as input for the parameter's type, as JSON for json, and null for
a NOT NULL column. postgres.js throws on undefined and on a bigint for json. A wide
string or number, any, unknown, an object or an array is not judged, and without
type information nothing is. Set param-type-mismatch in rules to change the severity.
Options¶
| Option | |
|---|---|
schema |
a .sql file, or a list of them, with the CREATE TABLE statements, relative to the working directory |
migrationsDir |
a directory whose .sql files, in name order, make the schema |
dialect |
postgres (default), mysql or sqlite; another dialect sqlty knows, such as duckdb, gets the PostgreSQL row types |
driver |
postgres (postgres.js, default) or pg (node-postgres) for postgres, mysql2 (mysql2) for mysql, better-sqlite3 (better-sqlite3) for sqlite; the dialect's by default, and one of another dialect is a configuration error |
targets |
[{ tag, transform, fieldTransform, skipTypeAnnotations }]: tag is a name such as sql or db.query, or a /regex/ |
overrides.types |
the TypeScript type of a SQL type or a table.column, such as { "BIGINT": "bigint", "person.address": "Address" } |
rules |
sqlty rule severities, such as { "unknown-column": "warn" } |
enforceType |
fix (default) or suggest |
The options follow SafeQL's, which asks a running PostgreSQL to type the same templates.
A repository that also checks Python configures sqlty once: the plugin reads the
sqlty.toml or pyproject.toml that sqlty check finds for each file, its schema,
dialect and rules included. The ESLint options win: schema or migrationsDir
replaces the configured schema, and rules the severities it names.
Drivers¶
The row type is what the driver hands JavaScript, which is not always the SQL type:
| SQL type | postgres.js 3.4 | node-postgres 8 |
|---|---|---|
int, smallint, real, double precision |
number |
number |
bigint, numeric |
string |
string |
date, timestamp, timestamptz |
Date |
Date |
interval |
string |
IPostgresInterval |
numeric[] |
string[] |
number[] |
an enum, a text column with a CHECK (col IN (...)) |
'a' \| 'b' |
'a' \| 'b' |
| an array of an enum | ('a' \| 'b')[] |
string, the array's literal text |
json, jsonb |
unknown |
unknown |
JSON the query builds (json_build_object, json_agg, to_json(row)) |
its shape, such as { id: number; at: string } |
the same |
bytea |
Buffer |
Buffer |
With dialect: "mysql" or "sqlite", the row type is what mysql2 3 or better-sqlite3 13
returns by default:
| SQL type | mysql2 3 | better-sqlite3 13 |
|---|---|---|
int, bigint, tinyint(1), boolean, year, float, double |
number |
number |
decimal |
string |
number |
date, datetime, timestamp |
Date |
string |
time, set, text |
string |
string |
an enum, a text column with a CHECK (col IN (...)) |
'a' \| 'b' |
'a' \| 'b' |
json |
unknown |
string |
JSON the query builds (JSON_OBJECT, json_object) |
its shape | string |
blob, binary |
Buffer |
Buffer |
bit |
Buffer |
string |
| a column with no declared type | unknown |
A bigint past Number.MAX_SAFE_INTEGER loses precision in both, as the drivers return
it.
overrides.types changes one, such as bigint for a postgres.js client created with
types: { bigint: postgres.BigInt }. A table.column key, such as "person.address": "Address"
for a jsonb column of a known shape, types that column wherever a query reads it, through
aliases, subqueries and CTEs, and wins over its SQL type. The column stays nullable, as
Address | null. A type an override names, declared in the file or imported, is compared
by its name.
Limits¶
- With mysql2 and better-sqlite3, an interpolated value is checked only for
null. - A
sqlfragment is spliced into the query that interpolates it when the file shows its SQL: directly, through aconst, aconstarrow function or a branch of?:, up to 16 combinations. A query that interpolates asql(...)helper, a fragment held anywhere else, or more combinations, is skipped. The playground still skips any query that interpolates a fragment. - An interpolated value is checked only with type information. Date, time and interval text
is reported only when it holds no value at all, and postgres.js values of a
booleanparameter are not checked: postgres.js 3.4 sends any of them astrueorfalse. - A row type imported from another file, a class, an enum, a generic type or an interface that extends another or is declared twice is not checked.
- The playground reads type arguments as written, not the aliases they name.