A node query builder for various SQL databases, based on CodeIgniter's query builder.
- Callback and Promise API for making database calls.
- Mysql (via
mysql2
) - PostgreSQL (via
pg
) - Sqlite (via
dblite
)
npm install ci-node-query
(Versions 3.x and below work differently. Their documentation is here)
// Set the database connection details
const nodeQuery = require('ci-node-query')({
"driver": "mysql",
"connection": {
"host": "localhost",
"user": "test",
"password": "",
"database": "test"
}
});
// Get the query builder
const query = nodeQuery.getQuery();
// As of version 3.1.0, you can also get promises
// Version 5.0.0 removes all callback interfaces
const queryPromise = query.select('foo')
.from('bar')
.where('x', 3)
.orWhere({y: 2})
.join('baz', 'baz.boo = bar.foo', 'left')
.orderBy('x', 'DESC')
.limit(2, 3)
.get();
queryPromise.then(function(res) {
// Handle query results
});
As of version 4, all adapters return a standard result object, which looks similar to this:
// Result object
{
rows: [{
columnName1: value1,
columnName2: value2,
}],
columns: ['column1', 'column2'],
}
In addition to the rows, and columns properties,
the result object has two methods, rowCount
and columnCount
.
These methods return the number of rows and columns columns in the current result.
As of version 2, where
and having
type methods parse the values passed to look for function calls. While values passed are still passed as query parameters, take care to avoid passing these kinds of methods unfiltered input. SQL function arguments are not currently parsed, so they need to be properly escaped for the current database.