Type-safe SQL
This is a type-safe query builder for SQL written in TypeScript. It has built-in support for Postgres and MySQL, and it shouldn't be hard to adopt it for other database engines.
Installing
npm install type-sql
Examples
.whereBOOK.author.lower.like'%john%' .andBOOK.price.lt10.orBOOK.available.eqtrue .andBOOK.date.gtenew Date'2016-10-23T19:11:25.342Z' .groupByBOOK.author, BOOK.available .havingBOOK.price.sum.between1000, 2000 .orderByBOOK.author.asc.nullsFirst, BOOK.price.sum.desc .offset20 .limit10 .selectBOOK.author, BOOK.available, BOOK.price.sum.as'sum_price'; await db.tableBOOK .whereBOOK.author.eq'John Smith', BOOK.price.lte200 .update; await db.tableBOOK.whereBOOK.title.isNull.delete; ;;
Table definition
You have to define the structure of the tables with a table object, and optionally an entity interface. The table object is used for the builder, while the entity interface is used as an input type for INSERT and UPDATE queries, and as a result type of SELECT queries when all columns of a single table are queried.
(DDL generation from or to the table object is not supported)
; ;
Query executor
The database object that acts as the source of the query builder must be initialized with a Postgres or MySQL client:
PostgreSQL:
;; ;client.connect; ;
MySQL:
;; ;client.connect; ;
Features
The are many more examples among the tests, with features including
- joins
- more functions on columns
- composite ID
- inserting multiple entities
- shortcuts for deleting/updating/querying a single entity by ID
- aliased column name, for example to map snake_case columns to camelCase JavaScript object fields
SQL injection
The library uses "parameterized" queries by default, so that the input parameters are passed to the client separately from the sql string.
If for some reason you want to switch off the parameter escaping, then you can do it by passing the "parameterized: false" flag to the query source. Note that the query builder will still throw an error if the parameter's type is incorrect, so for example you can't pass a string to a number column even if the parameters are not escaped.
;
Logging
You can log the SQL queries performed by the library two different ways: By passing the logging flag to the query source object, and then the queries will be written to the console by the debug tool under the 'type-sql' tag:
;
Or you can pass a custom logger function to the query source:
Licensing
MIT License