node-sql-gen
A SQL query builder, inspired by SQLAlchemy.
Installation
npm install sql-gen
Example
We can define tables using sql.table()
and sql.column()
:
; const Author = sql;const Book = sql;
We can then define a query:
const query = sql ;
We can use compile()
to turn a query into a string and parameters,
ready to pass into a database connection:
sql// {// "text": "SELECT author.name, book.title FROM book JOIN author ON book.author_id = author.id WHERE book.genre = ?",// "params": ["comedy"]// }
If using node-sqlite3:
const text params = sql;const database = "path/to/database";databasealltext ...params { if error console; else console; };
API
table(name, columns)
Represent a table in a database. Takes the following arguments:
-
name
: the name of the table in the database. -
columns
: the columns in the table. The keys should be the name by which you want to refer to the columns. The values should be the result of callingcolumn()
.
Returns an instance of Table
, which has the following properties:
-
c
: the columns of the table, which can then be used in generating queries. For instance:const Author =;sql -
as(alias)
: create a from clause for this table with an alternate name, as specified byalias
. For instance:const Author =;const authorAlias = Author;sql -
primaryKey
: if the table has no columns defined as a primary key, this isnull
. Otherwise, this is an object with acolumns
property, which is an array of all of the columns in the primary key.
column(options)
Represent a column in a table.
Options should be an object with the following properties:
-
name
: the name of the column in the database. -
type
: the type of the column. Use a value fromtypes
. -
primaryKey
(optional): set totrue
to mark this column as part of the table's primary key. Defaults to false. -
nullable
(optional): set tofalse
to mark this column asNOT NULL
. Defaults to true.
types
types.int
: SQL integer type.types.string
: SQL string type.
from(selectable)
Create an instance of Query
using selectable
as the primary from clause.
Query
Query
is used to generate SQL queries.
It has the following properties:
-
join(selectable, condition)
: creates aJOIN
clause onto the given selectable. -
select(...columns)
: specify the columns to select. -
distinct()
: add aDISTINCT
qualifier to this query. -
where(condition)
: add aWHERE
clause. If there's already aWHERE
clause,condition
is added usingAND
.condition
should be a SQL expression. -
subquery()
: turn this query into a subquery that can then be selected from, similarly to a table.
createTable(table)
Represents a CREATE TABLE
statement.
Use compile()
to compile it.
compile(query)
Turn a query or statement into a query that can be executed. Returns an object with two properties:
text
: the text of the queryparams
: any parameters that have been generated during compilation of the query