TypeScript Types Generation
sqlx-ts provides the powerful Typescript type generation based on the raw SQLs that you write in your code. The feature greatly enhances type safety of the raw SQL queries, ultimately replaces the need of ORM completely.
Without type generation, you would maintain type definition of each raw SQL manually, which is a brittle process and becomes an extra management in large projects.
Getting started
The simplest way to use type generation feature of sqlx-ts is by setting -g
or --generate-types
flag when running sqlx-ts CLI.
$ cargo run ./samples/type-generator-test --generate-types --config=<path to .sqlxrc.json>
By default, sqlx-ts will generate type
Please read more about .sqlxrc.json here
What's possible
sqlx-ts supports following type generations and other SQL syntax will be ignored from type generation
- SELECT statements
- INSERT statements
- UPDATE statements
- DELETE statements
Also type generation supports parameterised query as per the requirements of PREPARE statements of the databases that sqlx-ts currently supports.
Database | Parameterised Query | Example |
---|---|---|
MySQL | ? | SELECT * FROM items WHERE points > ? AND points < ? |
Postgres | $1 $2 $3 | SELECT * FROM items WHERE points > $1 AND points < $2 |
in your codebase, if you have the following SQL query
const simpleQuery = sql`
SELECT *
FROM items
WHERE points > ?
AND points < ?
`
by running sqlx-ts type generation against the query, it would generate
export type ISimpleQueryParams = [number, number]
export interface ISimpleQueryResult {
id: string
points: number
}
export interface ISimpleQueryQuery{
params: ISimpleQueryParams;
result: ISimpleQueryResult;
}
sqlx-ts will pick up name of the variable and use it when generating the type definitions. You can override
the type name by setting the @name
annotation, you can read more in the section below.
Configuration
You can configure type generation in .sqlxrc.json
; available configurations:
Todo We need configurations for following:
- generate type paths
- file names (by default, it should be file_name.types.ts)
Q/A
Why doesn't SQLx support named parameterised queries? e.g. SELECT * FROM items WHERE point = :point
We believe that there is no official way in Typescript to ensure the value level type-safety yet and providing named parameter does not guarantee the true type safetiness that we are trying to achieve. Furthermore, name parameter is not the syntax supported by native database drivers, but they are an additional syntax supported by popular ORM libraries such as Sequelize.
The closest type safety that exists in TypeScript world is by emulating Opaque type e.g. https://github.com/sindresorhus/type-fest/blob/main/source/opaque.d.ts. In the future, sqlx-ts will support Opaque type overrides natively to solve this matter.