Create standard result object. Resolves #3

This commit is contained in:
Timothy Warren 2016-03-15 15:37:24 -04:00
parent aeb665cf44
commit 0350a165c7
30 changed files with 714 additions and 85 deletions

48
API.md
View File

@ -4,7 +4,7 @@ Class for connection management
**Parameters**
- `config`
- `config` **object** connection parameters
## constructor
@ -12,7 +12,28 @@ Constructor
**Parameters**
- `config` **object** connection paramaters
- `config` **object** connection parameters
**Examples**
```javascript
let nodeQuery = require('ci-node-query')({
driver: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: '',
database: 'mysql'
}
});
```
```javascript
let nodeQuery = require('ci-node-query')({
driver: 'sqlite',
connection: ':memory:'
});
```
## getQuery
@ -368,7 +389,7 @@ Returns **QueryBuilder** The Query Builder object, for chaining
## query
Manually make an sql query
Run an arbitrary sql query. Run as a prepared statement.
**Parameters**
@ -500,3 +521,24 @@ Set a 'where not in' clause
- `values` **Array** the array of items to search in
Returns **QueryBuilder** The Query Builder object, for chaining
# Result
Query result object
**Parameters**
- `rows` **Array** the data rows of the result
- `columns` **Array** the column names in the result
## columnCount
Get the number of columns returned by the query
Returns **Number** the number of columns in the result
## rowCount
Get the number of rows returned by the query
Returns **Number** the number of rows in the result

View File

@ -4,6 +4,7 @@
* Changed connection setup to just use a config object - the appropriate adapter object is created by the library.
* Removed mysql adapter, as mysql2 is very similar and does proper prepared statements
* Removed firebird entirely
* Created a standard result object
## 3.2.0
* Added public `query` method for making arbitrary sql calls

View File

@ -46,8 +46,8 @@ query.select('foo')
.join('baz', 'baz.boo = bar.foo', 'left')
.orderBy('x', 'DESC')
.limit(2, 3)
.get(function(/* Adapter dependent arguments */) {
// Database module result handling
.get(function(err, result) {
// Handle Results Here
});
// As of version 3.1.0, you can also get promises
@ -65,6 +65,26 @@ queryPromise.then(function(res) {
});
```
### Result object
As of version 4, all adapters return a standard result object, which looks similar to this:
```javascript
// 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.
### Security notes
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.

View File

@ -0,0 +1,93 @@
Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@ -0,0 +1,20 @@
# Source Code Pro
Source Code Pro is a set of OpenType fonts that have been designed to work well
in user interface (UI) environments. In addition to a functional OpenType font, this open
source project provides all of the source files that were used to build this OpenType font
by using the AFDKO makeotf tool.
## Font installation instructions
* [Mac OS X](http://support.apple.com/kb/HT2509)
* [Windows](http://windows.microsoft.com/en-us/windows-vista/install-or-uninstall-fonts)
* [Linux/Unix-based systems](https://github.com/adobe-fonts/source-code-pro/issues/17#issuecomment-8967116)
## Getting Involved
Send suggestions for changes to the Source Code OpenType font project maintainer, [Paul D. Hunt](mailto:opensourcefonts@adobe.com?subject=[GitHub] Source Code Pro), for consideration.
## Further information
For information about the design and background of Source Code, please refer to the [official font readme file](http://www.adobe.com/products/type/font-information/source-code-pro-readme.html).

View File

@ -0,0 +1,15 @@
@font-face{
font-family: 'Source Code Pro';
font-weight: 400;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceCodePro-Regular.otf.woff') format('woff');
}
@font-face{
font-family: 'Source Code Pro';
font-weight: 500;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceCodePro-Medium.otf.woff') format('woff');
}

View File

@ -0,0 +1,93 @@
Copyright 2010, 2012, 2014 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@ -0,0 +1,20 @@
# Source Sans Pro
Source Sans Pro is a set of OpenType fonts that have been designed to work well
in user interface (UI) environments. In addition to a functional OpenType font, this open
source project provides all of the source files that were used to build this OpenType font
by using the AFDKO makeotf tool.
## Font installation instructions
* [Mac OS X](http://support.apple.com/kb/HT2509)
* [Windows](http://windows.microsoft.com/en-us/windows-vista/install-or-uninstall-fonts)
* [Linux/Unix-based systems](https://github.com/adobe-fonts/source-code-pro/issues/17#issuecomment-8967116)
## Getting Involved
Send suggestions for changes to the Source Sans OpenType font project maintainer, [Paul D. Hunt](mailto:opensourcefonts@adobe.com?subject=[GitHub] Source Sans Pro), for consideration.
## Further information
For information about the design and background of Source Sans, please refer to the [official font readme file](http://www.adobe.com/products/type/font-information/source-sans-pro-readme.html).

View File

@ -0,0 +1,17 @@
{
"name": "source-sans-pro",
"version": "2.020R-ro/1.075R-it",
"main": "source-sans-pro.css",
"homepage": "https://github.com/adobe-fonts/source-sans-pro",
"repository": {
"type": "git",
"url": "https://github.com/adobe-fonts/source-sans-pro.git"
},
"authors": [
{ "name": "Paul D. Hunt" }
],
"description": "Source Sans Pro font family by Adobe",
"license": "SIL OFL 1.1",
"keywords": ["font", "sourcesans", "sourcesanspro", "source sans", "source sans pro"],
"ignore": ["**/.*"]
}

View File

@ -0,0 +1,31 @@
@font-face{
font-family: 'Source Sans Pro';
font-weight: 300;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceSansPro-Light.otf.woff') format('woff');
}
@font-face{
font-family: 'Source Sans Pro';
font-weight: 400;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceSansPro-Regular.otf.woff') format('woff');
}
@font-face{
font-family: 'Source Sans Pro';
font-weight: 600;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceSansPro-Semibold.otf.woff') format('woff');
}
@font-face{
font-family: 'Source Sans Pro';
font-weight: 700;
font-style: normal;
font-stretch: normal;
src: url('WOFF/OTF/SourceSansPro-Bold.otf.woff') format('woff');
}

View File

@ -242,6 +242,21 @@
class='regular block'>
#whereNotIn
</a>
<a
href='#Result'
class='block bold'>
Result
</a>
<a
href='#Result.columnCount'
class='regular block'>
#columnCount
</a>
<a
href='#Result.rowCount'
class='regular block'>
#rowCount
</a>
</div>
</div>
</div>
@ -255,9 +270,10 @@
<h4>Parameters</h4>
<ul class='suppress-p-margin'>
<li> <strong>config</strong>
<li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">object</a></code> <strong>config</strong>
:
<div class='force-inline'>
<p>connection parameters</p>
</div>
</li>
@ -285,11 +301,24 @@
<li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">object</a></code> <strong>config</strong>
:
<div class='force-inline'>
<p>connection paramaters</p>
<p>connection parameters</p>
</div>
</li>
</ul>
<h4>Examples</h4>
<pre class='overflow-auto'><span class="hljs-keyword">let</span> nodeQuery = <span class="hljs-built_in">require</span>(<span class="hljs-string">'ci-node-query'</span>)({
driver: <span class="hljs-string">'mysql'</span>,
connection: {
host: <span class="hljs-string">'localhost'</span>,
user: <span class="hljs-string">'root'</span>,
password: <span class="hljs-string">''</span>,
database: <span class="hljs-string">'mysql'</span>
}
});</pre><pre class='overflow-auto'><span class="hljs-keyword">let</span> nodeQuery = <span class="hljs-built_in">require</span>(<span class="hljs-string">'ci-node-query'</span>)({
driver: <span class="hljs-string">'sqlite'</span>,
connection: <span class="hljs-string">':memory:'</span>
});</pre>
</section>
</div>
</div>
@ -1604,7 +1633,7 @@ prefixed with &apos;OR NOT&apos;</p>
#query<span class='gray'>(sql, [params], [callback])</span>
</code>
<div class='force-inline'>
<p>Manually make an sql query</p>
<p>Run an arbitrary sql query. Run as a prepared statement.</p>
</div>
</a>
@ -1613,7 +1642,7 @@ prefixed with &apos;OR NOT&apos;</p>
<h2 id='QueryBuilder.query' class='mt0'>
query<span class='gray'>(sql, [params], [callback])</span>
</h2>
<p>Manually make an sql query</p>
<p>Run an arbitrary sql query. Run as a prepared statement.</p>
<h4>Parameters</h4>
<ul class='suppress-p-margin'>
@ -2062,6 +2091,85 @@ prefixed with &apos;OR NOT&apos;</p>
</div>
</div>
</section>
</div><div class='py1'><section class='py2 clearfix'>
<h2 id='Result' class='mt0'>
Result<span class='gray'>(rows, columns)</span>
</h2>
<p>Query result object</p>
<h4>Parameters</h4>
<ul class='suppress-p-margin'>
<li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code> <strong>rows</strong>
:
<div class='force-inline'>
<p>the data rows of the result</p>
</div>
</li>
<li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code> <strong>columns</strong>
:
<div class='force-inline'>
<p>the column names in the result</p>
</div>
</li>
</ul>
<h4>Instance members</h4>
<div class='collapsible' id='Result.columnCount'>
<a href='#Result.columnCount'>
<code>
#columnCount<span class='gray'></span>
</code>
<div class='force-inline'>
<p>Get the number of columns returned by the query</p>
</div>
</a>
<div class='collapser border px2'>
<section class='py2 clearfix'>
<h2 id='Result.columnCount' class='mt0'>
columnCount<span class='gray'></span>
</h2>
<p>Get the number of columns returned by the query</p>
<h4>Returns</h4>
<code><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></code></code>
:
<div class='force-inline'>
<p>the number of columns in the result</p>
</div>
</section>
</div>
</div>
<div class='collapsible' id='Result.rowCount'>
<a href='#Result.rowCount'>
<code>
#rowCount<span class='gray'></span>
</code>
<div class='force-inline'>
<p>Get the number of rows returned by the query</p>
</div>
</a>
<div class='collapser border px2'>
<section class='py2 clearfix'>
<h2 id='Result.rowCount' class='mt0'>
rowCount<span class='gray'></span>
</h2>
<p>Get the number of rows returned by the query</p>
<h4>Returns</h4>
<code><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></code></code>
:
<div class='force-inline'>
<p>the number of rows in the result</p>
</div>
</section>
</div>
</div>
</section>
</div>
</div>
</div>

View File

@ -30,6 +30,16 @@ class Adapter {
throw new Error('Correct adapter not defined for query execution');
}
/**
* Transform the adapter's result into a standard format
*
* @param {*} originalResult - the original result object from the driver
* @return {Result} - the new result object
*/
transformResult(originalResult) {
throw new Error('Result transformer method not defined for current adapter');
}
/**
* Close the current database connection
* @return {void}

View File

@ -19,14 +19,28 @@ const dbDriverMap = new Map([
/**
* Class for connection management
*
* @param {object} config - connection parameters
*/
class NodeQuery {
/**
* Constructor
*
* @param {object} config - connection paramaters
* @constructor
* @param {object} config - connection parameters
* @example let nodeQuery = require('ci-node-query')({
* driver: 'mysql',
* connection: {
* host: 'localhost',
* user: 'root',
* password: '',
* database: 'mysql'
* }
* });
* @example let nodeQuery = require('ci-node-query')({
* driver: 'sqlite',
* connection: ':memory:'
* });
*/
constructor(config) {
this.instance = null;

View File

@ -309,7 +309,7 @@ class QueryBuilder extends QueryBuilderBase {
// ----------------------------------------------------------------------------
/**
* Manually make an sql query
* Run an arbitrary sql query. Run as a prepared statement.
*
* @param {string} sql - The sql to execute
* @param {array} [params] - The query parameters
@ -880,7 +880,7 @@ class QueryBuilder extends QueryBuilderBase {
* @param {Function} [callback] - Callback for handling response from the database
* @return {void|Promise} - If no callback is passed, a promise is returned
*/
delete(/*table, [where], callback*/) {
delete(/*table, [where], [callback]*/) {
let args = getArgs('table:string, [where]:object, [callback]:function', arguments);
if (args.where) {

96
lib/Result.js Normal file
View File

@ -0,0 +1,96 @@
'use strict';
const helpers = require('./helpers');
const getArgs = require('getargs');
/**
* Query result object
*
* @param {Array} rows - the data rows of the result
* @param {Array} columns - the column names in the result
*/
class Result {
/**
* Create a result object
*
* @private
* @param {Array} [rows] - the data rows of the result
* @param {Array} [columns] - the column names in the result
*/
constructor(rows, columns) {
this._rows = (rows == null) ? [] : rows;
this._columns = (columns == null) ? [] : columns;
// If columns aren't explicitly given,
// get the list from the first row's keys
if (
this._columns.length === 0 &&
this._rows.length > 0 &&
helpers.isObject(rows[0])
) {
this.columns = Object.keys(rows[0]);
}
}
/**
* Return the result rows
*
* @private
* @return {Array} - the data rows of the result
*/
get rows() {
return this._rows;
}
/**
* Set the result rows for the result object
*
* @private
* @param {Array} rows - the data rows of the result
* @return {void}
*/
set rows(rows) {
this._rows = rows;
}
/**
* Return the result columns
*
* @private
* @return {Array} - the column names in the result
*/
get columns() {
return this._columns;
}
/**
* Set the result columns for the result object
*
* @private
* @param {Array} cols - the array of columns for the current result
* @return {void}
*/
set columns(cols) {
this._columns = cols;
}
/**
* Get the number of rows returned by the query
*
* @return {Number} - the number of rows in the result
*/
rowCount() {
return this._rows.length;
}
/**
* Get the number of columns returned by the query
*
* @return {Number} - the number of columns in the result
*/
columnCount() {
return this._columns.length;
}
}
module.exports = Result;

View File

@ -1,8 +1,9 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const helpers = require('../helpers');
const getArgs = require('getargs');
const promisify = require('../promisify');
const mysql2 = require('mysql2');
class Mysql extends Adapter {
@ -17,6 +18,29 @@ class Mysql extends Adapter {
super(instance);
}
/**
* Transform the adapter's result into a standard format
*
* @param {*} result - original driver result object
* @return {Result} - standard result object
*/
transformResult(result) {
// For insert and update queries, the result object
// works differently. Just apply the properties of
// this special result to the standard result object.
if (helpers.type(result) === 'object') {
let r = new Result();
Object.keys(result).forEach(key => {
r[key] = result[key];
});
return r;
}
return new Result(result);
}
/**
* Run the sql query as a prepared statement
*
@ -30,17 +54,17 @@ class Mysql extends Adapter {
if (! args.callback) {
return new Promise((resolve, reject) => {
this.instance.execute(args.sql, args.params, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
this.instance.execute(args.sql, args.params, (err, result) =>
(err)
? reject(err)
: resolve(this.transformResult(result))
);
});
}
return this.instance.execute(args.sql, args.params, args.callback);
return this.instance.execute(args.sql, args.params, (err, rows) =>
args.callback(err, this.transformResult(rows))
);
}
}

View File

@ -1,6 +1,7 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const getArgs = require('getargs');
const helpers = require('../helpers');
const pg = require('pg');
@ -46,6 +47,23 @@ class Pg extends Adapter {
super(instance);
}
/**
* Transform the adapter's result into a standard format
*
* @param {*} result - original driver result object
* @return {Result} - standard result object
*/
transformResult(result) {
if (result == null) {
return new Result();
}
let cols = [];
result.fields.forEach(field => cols = field.name);
return new Result(result.rows, cols);
}
/**
* Run the sql query as a prepared statement
*
@ -66,17 +84,18 @@ class Pg extends Adapter {
if (! args.callback) {
return new Promise((resolve, reject) => {
this.instance.query(args.sql, args.params, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
this.instance.query(args.sql, args.params, (err, result) =>
(err)
? reject(err)
: resolve(this.transformResult(result))
);
});
}
return this.instance.query(args.sql, args.params, args.callback);
return this.instance.query(args.sql, args.params, (err, origResult) => {
let result = this.transformResult(origResult);
return args.callback(err, result);
});
}
}

View File

@ -1,9 +1,9 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const getArgs = require('getargs');
const helpers = require('../helpers');
const promisify = require('../promisify');
const dbliteAdapter = require('dblite');
class Sqlite extends Adapter {
@ -15,6 +15,16 @@ class Sqlite extends Adapter {
this.instance.on('close', () => {});
}
/**
* Transform the adapter's result into a standard format
*
* @param {*} result - original driver result object
* @return {Result} - standard result object
*/
transformResult(result) {
return new Result(result);
}
/**
* Run the sql query as a prepared statement
*
@ -27,10 +37,18 @@ class Sqlite extends Adapter {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
return promisify(this.instance.query)(args.sql, args.params);
return new Promise((resolve, reject) => {
this.instance.query(args.sql, args.params, (err, result) =>
(err)
? reject(err)
: resolve(this.transformResult(result))
);
});
}
return this.instance.query(args.sql, args.params, args.callback);
return this.instance.query(args.sql, args.params, (err, res) => {
args.callback(err, this.transformResult(res));
});
}
/**

View File

@ -1,25 +0,0 @@
'use strict';
/*eslint-disable prefer-arrow-callback*/
/**
* Function to convert a callback function into a promise
*
* @private
* @see http://eddmann.com/posts/promisifying-error-first-asynchronous-callbacks-in-javascript/
* @example promisify(fs.readFile)('hello.txt', 'utf8')
* .then(console.log)
* .catch(console.error)
* @param {Function} fn - the callback function to convert
* @return {Promise} - the new promise
*/
function promisify(fn) {
return function () {
let args = [].slice.call(arguments);
return new Promise(function (resolve, reject) {
fn.apply(undefined, args.concat((error, value) => error ? reject(error) : resolve(value)));
});
};
}
module.exports = promisify;
/*eslint-enable prefer-arrow-callback*/

View File

@ -34,8 +34,12 @@ suite('Dblite adapter tests -', () => {
Callback Tests
---------------------------------------------------------------------------*/
testRunner(qb, (err, done) => {
testRunner(qb, (err, result, done) => {
expect(err).is.not.ok;
expect(result.rows).is.an('array');
expect(result.columns).is.an('array');
expect(result.rowCount()).to.not.be.undefined;
expect(result.columnCount()).to.not.be.undefined;
done();
});
test('Callback - Select with function and argument in WHERE clause', done => {
@ -64,7 +68,7 @@ suite('Dblite adapter tests -', () => {
},
];
qb.insertBatch('create_test', data, (err, rows) => {
qb.insertBatch('create_test', data, err => {
expect(err).is.not.ok;
return done();
});

View File

@ -30,9 +30,13 @@ suite('Mysql2 adapter tests -', () => {
//--------------------------------------------------------------------------
// Callback Tests
//--------------------------------------------------------------------------
testRunner(qb, (err, done) => {
testRunner(qb, (err, result, done) => {
expect(err).is.not.ok;
return done(err);
expect(result.rows).is.an('array');
expect(result.columns).is.an('array');
expect(result.rowCount()).to.not.be.undefined;
expect(result.columnCount()).to.not.be.undefined;
done();
});
test('Callback - Select with function and argument in WHERE clause', done => {
qb.select('id')

View File

@ -37,9 +37,12 @@ suite('Pg adapter tests -', () => {
//--------------------------------------------------------------------------
// Callback Tests
//--------------------------------------------------------------------------
testRunner(qb, (err, done) => {
testRunner(qb, (err, result, done) => {
expect(err).is.not.ok;
return done(err);
expect(result.rows).is.an('array');
expect(result.rowCount()).to.not.be.undefined;
expect(result.columnCount()).to.not.be.undefined;
done();
});
test('Callback - Select with function and argument in WHERE clause', done => {
qb.select('id')

View File

@ -23,9 +23,7 @@ module.exports = function testRunner(qb, callback) {
let methodNames = Object.keys(methodObj);
let lastMethodIndex = methodNames[methodNames.length - 1];
methodObj[lastMethodIndex].push((err, rows) => {
callback(err, done);
});
methodObj[lastMethodIndex].push((err, rows) => callback(err, rows, done));
methodNames.forEach(name => {
let args = methodObj[name],
@ -52,7 +50,7 @@ module.exports = function testRunner(qb, callback) {
.set('key', '84')
.set('val', new Buffer('120'))
.insert('create_test', (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Test Insert Object', done => {
@ -61,7 +59,7 @@ module.exports = function testRunner(qb, callback) {
key: 1,
val: new Buffer('2'),
}, (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Test Update', done => {
@ -71,7 +69,7 @@ module.exports = function testRunner(qb, callback) {
key: 'gogle',
val: new Buffer('non-word'),
}, (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Test set Array Update', done => {
@ -84,7 +82,7 @@ module.exports = function testRunner(qb, callback) {
qb.set(object)
.where('id', 22)
.update('create_test', (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Test where set update', done => {
@ -93,18 +91,18 @@ module.exports = function testRunner(qb, callback) {
.set('key', 'gogle')
.set('val', new Buffer('non-word'))
.update('create_test', (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Test delete', done => {
qb.delete('create_test', {id: 5}, (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Delete with where', done => {
qb.where('id', 5)
.delete('create_test', (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Delete multiple where values', done => {
@ -112,7 +110,7 @@ module.exports = function testRunner(qb, callback) {
id: 5,
key: 'gogle',
}, (err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
});
@ -126,7 +124,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd()
.limit(2, 1)
.get((err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Using where first grouping', done => {
@ -139,7 +137,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd()
.limit(2, 1)
.get((err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Using or grouping method', done => {
@ -154,7 +152,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd()
.limit(2, 1)
.get((err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
test('Callback - Using or not grouping method', done => {
@ -169,7 +167,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd()
.limit(2, 1)
.get((err, rows) => {
return callback(err, done);
return callback(err, rows, done);
});
});
});

View File

@ -48,11 +48,8 @@ module.exports = function promiseTestRunner(qb) {
suite('DB update tests -', () => {
suiteSetup(done => {
let sql = qb.driver.truncate('create_test');
qb.query(sql).then(res => {
return done();
}).catch(err => {
return done(err);
});
qb.query(sql).then(res => done())
.catch(err => done(err));
});
test('Promise - Test Insert', () => {
let promise = qb.set('id', 98)

View File

@ -42,4 +42,11 @@ suite('Base tests -', () => {
a.execute();
}).to.throw(Error, 'Correct adapter not defined for query execution');
});
test('Invalid adapter - missing transformResult', () => {
expect(() => {
let a = new Adapter();
a.transformResult([]);
}).to.throw(Error, 'Result transformer method not defined for current adapter');
});
});