SQL query type generator.
Finally you can use raw SQL with guaranteed type-safety.
Works with PostgreSQL and TypeScript.
- Automatically generates types for parameters/results of SQL queries of any complexity.
- Generate query types as you write them using watch mode.
- Useful parameter interpolation helpers for arrays and objects.
- No need to define your DB schema in TypeScript, your running DB is the live source of type data.
- Prevents SQL injections by not doing explicit parameter substitution. Instead it passes each query together with its parameter bindings to the DB driver, allowing parameter substitution to be done by the PostgreSQL server.
Query code:
import sql from "@pgtyped/query";
export const selectUserIds = sql<
ISelectUserIdsResult, ISelectUserIdsParams
>`select id from users where id = $id and age = $age`;
`;
Generated TypeScript interfaces:
/** 'selectUserIds' parameters type */
export interface ISelectUserIdsParams {
id: string | null;
age: number | null;
}
/** 'selectUserIds' return type */
export interface ISelectUserIdsResult {
id: string;
}
To run the selectUserIds
query:
const users = await selectAllUsers.run({
id: "some-user-id",
}, connection);
console.log(users[0]);
npm install @pgtyped/cli @pgtyped/query typescript
- Create a config file for the type generator
- Put your queries in separate files (ex.
queries.ts
) and use thesql
tag when defining them. - Run
npx pgtyped
to generate query type files.
You can also refer to the example app, to see pgtyped in action.
Additional details are available in READMEs for the @pgtyped/cli and @pgtyped/query packages.
pgtyped
command scans your srcDir
for query files,
Helper | Syntax | Parameter Type |
---|---|---|
Named parameters | $paramName |
paramName: ParamType |
Single value list | $paramName(name, author) |
paramName: { name: NameType, author: AuthorType } |
Multiple value list | $$paramName |
paramName: Array<ParamType> |
Multiple value list | $$paramName(name, author) |
paramName: Array<{ name: NameType, author: AuthorType }> |
Example insertUsers
:
INSERT INTO users (name, age)
VALUES $$users(name, age) RETURNING id
can be executed as follows:
const usersToInsert = [
{ name: 'Bob', age: 12 },
{ name: 'Tom', age: 16 },
];
const result = await insertUsers(usersToInsert, connection);
This project is still in an experimental stage so its APIs are expected to change a lot in the short term. Any help in the form of issue reports, feature requests or PRs is very appreciated.
Copyright (c) 2019-present, Adel Salakh