Merge branch 'develop' into 'master'

Version 4



See merge request !1
This commit is contained in:
Timothy Warren 2016-03-16 09:35:52 -04:00
commit 9326992f8b
53 changed files with 1358 additions and 898 deletions

38
.eslintrc Normal file
View File

@ -0,0 +1,38 @@
{
"env": {
"node": true,
"es6": true
},
"rules": {
"arrow-parens": [2, "as-needed"],
"no-console": [1],
"no-constant-condition": [1],
"no-extra-semi": [1],
"no-func-assign": [1],
"no-obj-calls": [2],
"no-unexpected-multiline" : [2],
"no-unneeded-ternary": [2],
"radix": [2],
"no-with": [2],
"no-eval": [2],
"no-unreachable": [1],
"no-irregular-whitespace": [1],
"no-new-wrappers": [2],
"no-new-func": [2],
"curly" : [2, "multi-line"],
"no-implied-eval": [2],
"no-invalid-this": [2],
"constructor-super": [2],
"no-dupe-args": [2],
"no-dupe-keys": [2],
"no-dupe-class-members": [2],
"no-this-before-super": [2],
"prefer-arrow-callback": [1],
"no-var": [2],
"valid-jsdoc": [1],
"strict": [2, "global"],
"callback-return": [1],
"object-shorthand": [1, "methods"],
"prefer-template": [1]
}
}

4
.gitignore vendored
View File

@ -1,6 +1,6 @@
build/* build/*
coverage coverage
coverage/*
npm-debug.log npm-debug.log
tests/FB_TEST_DB.FD
node_modules/* node_modules/*
.sonar/*
test/config.json

View File

@ -1,6 +0,0 @@
reporting:
reports:
- lcov
- lcovonly
report-config:
lcovonly: {file: ../coverage/lcov.info}

View File

@ -1,30 +0,0 @@
language: node_js
sudo: false
node_js:
- "node"
- "5.6"
- "5.5"
- "5.4"
- "5.3"
- "5.2"
- "5.1"
- "5.0"
- "4.3"
- "4.2"
- "4.1"
- "4.0"
before_script:
- npm install -g gulp
- npm install -g codeclimate-test-reporter
- psql -c 'DROP DATABASE IF EXISTS test;' -U postgres
- psql -c 'create database test;' -U postgres
- mysql -e 'create database IF NOT EXISTS test;'
- mysql -v -uroot test < ./test/sql/mysql.sql
- psql test postgres -f ./test/sql/pgsql.sql
script: gulp
after_script:
- CODECLIMATE_REPO_TOKEN=aa39789a53f6f8fd84747a98968c9f79795e890d55a533daa943b1042f81687f codeclimate-test-reporter < coverage/lcov.info

75
API.md
View File

@ -2,23 +2,42 @@
Class for connection management Class for connection management
## getQuery **Parameters**
Return an existing query builder instance - `config` **object** connection parameters
Returns **QueryBuilder** The Query Builder object ## constructor
## init Constructor
Create a query builder object
**Parameters** **Parameters**
- `driverType` **String** The name of the database type, eg. mysql or pg - `config` **object** connection parameters
- `connObject` **Object** A connection object from the database library
you are connecting with **Examples**
- `connLib` **[String]** The name of the db connection library you are
using, eg. mysql or mysql2. Optional if the same as driverType ```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
Return an existing query builder instance
Returns **QueryBuilder** The Query Builder object Returns **QueryBuilder** The Query Builder object
@ -370,7 +389,7 @@ Returns **QueryBuilder** The Query Builder object, for chaining
## query ## query
Manually make an sql query Run an arbitrary sql query. Run as a prepared statement.
**Parameters** **Parameters**
@ -427,6 +446,17 @@ query.set({foo:'bar'}); // Set with an object
Returns **QueryBuilder** The Query Builder object, for chaining Returns **QueryBuilder** The Query Builder object, for chaining
## truncate
Empties the selected database table
**Parameters**
- `table` **string** the name of the table to truncate
- `callback` **[function]** Optional callback
Returns **void or Promise** Returns a promise if no callback is supplied
## update ## update
Run the generated update query Run the generated update query
@ -491,3 +521,24 @@ Set a 'where not in' clause
- `values` **Array** the array of items to search in - `values` **Array** the array of items to search in
Returns **QueryBuilder** The Query Builder object, for chaining 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

@ -1,5 +1,11 @@
# Changelog # Changelog
## 4.0.0
* 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 ## 3.2.0
* Added public `query` method for making arbitrary sql calls * Added public `query` method for making arbitrary sql calls
* Added back tests for `node-firebird` adapter. Using this adapter with promises is not currently supported. * Added back tests for `node-firebird` adapter. Using this adapter with promises is not currently supported.

View File

@ -3,20 +3,15 @@
A node query builder for various SQL databases, based on [CodeIgniter](http://www.codeigniter.com/user_guide/database/query_builder.html)'s query builder. A node query builder for various SQL databases, based on [CodeIgniter](http://www.codeigniter.com/user_guide/database/query_builder.html)'s query builder.
[![Build Status](https://jenkins.timshomepage.net/buildStatus/icon?job=node-query)](https://jenkins.timshomepage.net/job/node-query/) [![Build Status](https://jenkins.timshomepage.net/buildStatus/icon?job=node-query)](https://jenkins.timshomepage.net/job/node-query/)
[![Build Status](https://travis-ci.org/timw4mail/node-query.svg?branch=master)](https://travis-ci.org/timw4mail/node-query)
[![Code Climate](https://codeclimate.com/github/timw4mail/node-query/badges/gpa.svg)](https://codeclimate.com/github/timw4mail/node-query)
[![Test Coverage](https://codeclimate.com/github/timw4mail/node-query/badges/coverage.svg)](https://codeclimate.com/github/timw4mail/node-query/coverage)
### Features ### Features
* Callback and Promise API for making database calls. * Callback and Promise API for making database calls.
### Supported adapters ### Supported databases
* mysql * Mysql (via `mysql2`)
* mysql2 * PostgreSQL (via `pg`)
* pg * Sqlite (via `dblite`)
* dblite
* node-firebird (Not supported as of version 3.1.0, as the adapter is very difficult to test)
### Installation ### Installation
@ -24,22 +19,24 @@ A node query builder for various SQL databases, based on [CodeIgniter](http://ww
[![NPM](https://nodei.co/npm/ci-node-query.png?downloads=true&downloadRank=true)](https://nodei.co/npm/ci-node-query/) [![NPM](https://nodei.co/npm/ci-node-query.png?downloads=true&downloadRank=true)](https://nodei.co/npm/ci-node-query/)
(Versions 3.x and below work differently. Their documentation is [here](https://git.timshomepage.net/timw4mail/node-query/tree/v3#README))
### Basic use ### Basic use
```javascript ```javascript
var nodeQuery = require('ci-node-query');
var connection = ... // Database module connection // Set the database connection details
const nodeQuery = require('ci-node-query')({
"driver": "mysql",
"connection": {
"host": "localhost",
"user": "test",
"password": "",
"database": "test"
}
});
// Three arguments: database type, database connection, database connection library // Get the query builder
var query = nodeQuery.init('mysql', connection, 'mysql2'); const query = nodeQuery.getQuery();
// The third argument is optional if the database connection library has the same name as the adapter, eg..
nodeQuery.init('mysql', connection, 'mysql');
// Can be instead
nodeQuery.init('mysql', connection);
// You can also retrieve the instance later
query = nodeQuery.getQuery();
query.select('foo') query.select('foo')
.from('bar') .from('bar')
@ -48,8 +45,8 @@ query.select('foo')
.join('baz', 'baz.boo = bar.foo', 'left') .join('baz', 'baz.boo = bar.foo', 'left')
.orderBy('x', 'DESC') .orderBy('x', 'DESC')
.limit(2, 3) .limit(2, 3)
.get(function(/* Adapter dependent arguments */) { .get(function(err, result) {
// Database module result handling // Handle Results Here
}); });
// As of version 3.1.0, you can also get promises // As of version 3.1.0, you can also get promises
@ -67,6 +64,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 ### 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. 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

@ -26,17 +26,17 @@
href='#NodeQuery' href='#NodeQuery'
class='block bold'> class='block bold'>
NodeQuery NodeQuery
</a>
<a
href='#NodeQuery.constructor'
class='regular block'>
#constructor
</a> </a>
<a <a
href='#NodeQuery.getQuery' href='#NodeQuery.getQuery'
class='regular block'> class='regular block'>
#getQuery #getQuery
</a> </a>
<a
href='#NodeQuery.init'
class='regular block'>
#init
</a>
<a <a
href='#QueryBuilder' href='#QueryBuilder'
class='block bold'> class='block bold'>
@ -207,6 +207,11 @@
class='regular block'> class='regular block'>
#set #set
</a> </a>
<a
href='#QueryBuilder.truncate'
class='regular block'>
#truncate
</a>
<a <a
href='#QueryBuilder.update' href='#QueryBuilder.update'
class='regular block'> class='regular block'>
@ -237,6 +242,21 @@
class='regular block'> class='regular block'>
#whereNotIn #whereNotIn
</a> </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> </div>
</div> </div>
@ -244,11 +264,64 @@
<div class='px2'> <div class='px2'>
<div class='py1'><section class='py2 clearfix'> <div class='py1'><section class='py2 clearfix'>
<h2 id='NodeQuery' class='mt0'> <h2 id='NodeQuery' class='mt0'>
NodeQuery<span class='gray'></span> NodeQuery<span class='gray'>(config)</span>
</h2> </h2>
<p>Class for connection management</p> <p>Class for connection management</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/Object">object</a></code> <strong>config</strong>
:
<div class='force-inline'>
<p>connection parameters</p>
</div>
</li>
</ul>
<h4>Instance members</h4> <h4>Instance members</h4>
<div class='collapsible' id='NodeQuery.constructor'>
<a href='#NodeQuery.constructor'>
<code>
#constructor<span class='gray'>(config)</span>
</code>
<div class='force-inline'>
<p>Constructor</p>
</div>
</a>
<div class='collapser border px2'>
<section class='py2 clearfix'>
<h2 id='NodeQuery.constructor' class='mt0'>
constructor<span class='gray'>(config)</span>
</h2>
<p>Constructor</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/Object">object</a></code> <strong>config</strong>
:
<div class='force-inline'>
<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>
<div class='collapsible' id='NodeQuery.getQuery'> <div class='collapsible' id='NodeQuery.getQuery'>
<a href='#NodeQuery.getQuery'> <a href='#NodeQuery.getQuery'>
<code> <code>
@ -276,59 +349,6 @@
</section> </section>
</div> </div>
</div> </div>
<div class='collapsible' id='NodeQuery.init'>
<a href='#NodeQuery.init'>
<code>
#init<span class='gray'>(driverType, connObject, [connLib])</span>
</code>
<div class='force-inline'>
<p>Create a query builder object</p>
</div>
</a>
<div class='collapser border px2'>
<section class='py2 clearfix'>
<h2 id='NodeQuery.init' class='mt0'>
init<span class='gray'>(driverType, connObject, [connLib])</span>
</h2>
<p>Create a query builder 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/String">String</a></code> <strong>driverType</strong>
:
<div class='force-inline'>
<p>The name of the database type, eg. mysql or pg</p>
</div>
</li>
<li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></code> <strong>connObject</strong>
:
<div class='force-inline'>
<p>A connection object from the database library
you are connecting with</p>
</div>
</li>
<li><code>[<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></code>]</code> <strong>connLib</strong>
:
<div class='force-inline'>
<p>The name of the db connection library you are
using, eg. mysql or mysql2. Optional if the same as driverType</p>
</div>
</li>
</ul>
<h4>Returns</h4>
<code><code><a href="#QueryBuilder">QueryBuilder</a></code></code>
:
<div class='force-inline'>
<p>The Query Builder object</p>
</div>
</section>
</div>
</div>
</section> </section>
</div><div class='py1'><section class='py2 clearfix'> </div><div class='py1'><section class='py2 clearfix'>
<h2 id='QueryBuilder' class='mt0'> <h2 id='QueryBuilder' class='mt0'>
@ -1613,7 +1633,7 @@ prefixed with &apos;OR NOT&apos;</p>
#query<span class='gray'>(sql, [params], [callback])</span> #query<span class='gray'>(sql, [params], [callback])</span>
</code> </code>
<div class='force-inline'> <div class='force-inline'>
<p>Manually make an sql query</p> <p>Run an arbitrary sql query. Run as a prepared statement.</p>
</div> </div>
</a> </a>
@ -1622,7 +1642,7 @@ prefixed with &apos;OR NOT&apos;</p>
<h2 id='QueryBuilder.query' class='mt0'> <h2 id='QueryBuilder.query' class='mt0'>
query<span class='gray'>(sql, [params], [callback])</span> query<span class='gray'>(sql, [params], [callback])</span>
</h2> </h2>
<p>Manually make an sql query</p> <p>Run an arbitrary sql query. Run as a prepared statement.</p>
<h4>Parameters</h4> <h4>Parameters</h4>
<ul class='suppress-p-margin'> <ul class='suppress-p-margin'>
@ -1769,6 +1789,50 @@ prefixed with &apos;OR NOT&apos;</p>
</section> </section>
</div> </div>
</div> </div>
<div class='collapsible' id='QueryBuilder.truncate'>
<a href='#QueryBuilder.truncate'>
<code>
#truncate<span class='gray'>(table, [callback])</span>
</code>
<div class='force-inline'>
<p>Empties the selected database table</p>
</div>
</a>
<div class='collapser border px2'>
<section class='py2 clearfix'>
<h2 id='QueryBuilder.truncate' class='mt0'>
truncate<span class='gray'>(table, [callback])</span>
</h2>
<p>Empties the selected database table</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/String">string</a></code> <strong>table</strong>
:
<div class='force-inline'>
<p>the name of the table to truncate</p>
</div>
</li>
<li><code>[<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function">function</a></code>]</code> <strong>callback</strong>
:
<div class='force-inline'>
<p>Optional callback</p>
</div>
</li>
</ul>
<h4>Returns</h4>
<code><code>void</code> or <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code></code>
:
<div class='force-inline'>
<p>Returns a promise if no callback is supplied</p>
</div>
</section>
</div>
</div>
<div class='collapsible' id='QueryBuilder.update'> <div class='collapsible' id='QueryBuilder.update'>
<a href='#QueryBuilder.update'> <a href='#QueryBuilder.update'>
<code> <code>
@ -2027,6 +2091,85 @@ prefixed with &apos;OR NOT&apos;</p>
</div> </div>
</div> </div>
</section> </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> </div>
</div> </div>

View File

@ -15,45 +15,6 @@ const TEST_FILES = [
'test/adapters/*_test.js' 'test/adapters/*_test.js'
]; ];
const ESLINT_SETTINGS = {
"env": {
"node": true,
"es6": true
},
"rules": {
"arrow-parens": [2, "as-needed"],
"no-console": [1],
"no-constant-condition": [1],
"no-extra-semi": [1],
"no-func-assign": [1],
"no-obj-calls": [2],
"no-unexpected-multiline" : [2],
"no-unneeded-ternary": [2],
"radix": [2],
"no-with": [2],
"no-eval": [2],
"no-unreachable": [1],
"no-irregular-whitespace": [1],
"no-new-wrappers": [2],
"no-new-func": [2],
"curly" : [2, "multi-line"],
"no-implied-eval": [2],
"no-invalid-this": [2],
"constructor-super": [2],
"no-dupe-args": [2],
"no-dupe-keys": [2],
"no-dupe-class-members": [2],
"no-this-before-super": [2],
"prefer-arrow-callback": [1],
"no-var": [2],
"valid-jsdoc": [1],
"strict": [2, "global"],
"callback-return": [1],
"object-shorthand": [1, "methods"],
"prefer-template": [1]
}
};
const MOCHA_OPTIONS = { const MOCHA_OPTIONS = {
ui: 'tdd', ui: 'tdd',
bail: true, bail: true,
@ -63,7 +24,7 @@ const MOCHA_OPTIONS = {
gulp.task('lint', () => { gulp.task('lint', () => {
pipe(gulp.src(SRC_FILES), [ pipe(gulp.src(SRC_FILES), [
eslint(ESLINT_SETTINGS), eslint(),
eslint.format(), eslint.format(),
eslint.failAfterError() eslint.failAfterError()
]); ]);
@ -75,7 +36,7 @@ gulp.task('lint', () => {
gulp.task('lint-tests', ['lint'], () => { gulp.task('lint-tests', ['lint'], () => {
pipe(gulp.src(['test/**/*.js']), [ pipe(gulp.src(['test/**/*.js']), [
eslint(ESLINT_SETTINGS), eslint(),
eslint.format(), eslint.format(),
eslint.failAfterError() eslint.failAfterError()
]); ]);
@ -117,14 +78,8 @@ gulp.task('test', ['test-sloc', 'lint-tests'], function(cb) {
mocha(MOCHA_OPTIONS), mocha(MOCHA_OPTIONS),
istanbul.writeReports({ istanbul.writeReports({
dir: './coverage', dir: './coverage',
reporters: ['clover', 'lcov', 'lcovonly', 'html', 'text'] reporters: ['clover', 'lcov', 'lcovonly', 'html', 'text'],
}) }),
.once('error', () => {
process.exit(1);
})
.once('end', () => {
process.exit();
})
]); ]);
}); });
}); });

View File

@ -30,6 +30,16 @@ class Adapter {
throw new Error('Correct adapter not defined for query execution'); 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 * Close the current database connection
* @return {void} * @return {void}

View File

@ -1,59 +1,63 @@
'use strict'; 'use strict';
let fs = require('fs'), const helpers = require('./helpers');
helpers = require('./helpers'), const QueryBuilder = require('./QueryBuilder');
QueryBuilder = require('./QueryBuilder');
// Map config driver name to code class name
const dbDriverMap = new Map([
['my', 'Mysql'],
['mysql', 'Mysql'],
['maria', 'Mysql'],
['mariadb', 'Mysql'],
['firebird', 'Firebird'],
['postgresql', 'Pg'],
['postgres', 'Pg'],
['pg', 'Pg'],
['sqlite3', 'Sqlite'],
['sqlite', 'Sqlite'],
]);
/** /**
* Class for connection management * Class for connection management
*
* @param {object} config - connection parameters
*/ */
class NodeQuery { class NodeQuery {
/** /**
* Constructor * Constructor
* *
* @private * @param {object} config - connection parameters
* @constructor * @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() { constructor(config) {
this.instance = null; this.instance = null;
if (config != null) {
let drivername = dbDriverMap.get(config.driver);
if (! drivername) {
throw new Error(`Selected driver (${config.driver}) does not exist!`);
} }
/** let driver = require(`./drivers/${drivername}`);
* Create a query builder object let $adapter = require(`./adapters/${drivername}`);
*
* @param {String} driverType - The name of the database type, eg. mysql or pg
* @param {Object} connObject - A connection object from the database library
* you are connecting with
* @param {String} [connLib] - The name of the db connection library you are
* using, eg. mysql or mysql2. Optional if the same as driverType
* @return {QueryBuilder} - The Query Builder object
*/
init(driverType, connObject, connLib) {
connLib = connLib || driverType;
let paths = {
driver: `${__dirname}/drivers/${helpers.upperCaseFirst(driverType)}`,
adapter: `${__dirname}/adapters/${connLib}`,
};
Object.keys(paths).forEach(type => {
try {
fs.statSync(`${paths[type]}.js`);
} catch (e) {
throw new Error(
`Selected ${type} (${helpers.upperCaseFirst(driverType)}) does not exist!`
);
}
});
let driver = require(paths.driver);
let $adapter = require(paths.adapter);
let adapter = new $adapter(connObject);
let adapter = new $adapter(config.connection);
this.instance = new QueryBuilder(driver, adapter); this.instance = new QueryBuilder(driver, adapter);
}
return this.instance;
} }
/** /**
@ -70,4 +74,4 @@ class NodeQuery {
} }
} }
module.exports = new NodeQuery(); module.exports = (config => new NodeQuery(config));

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 {string} sql - The sql to execute
* @param {array} [params] - The query parameters * @param {array} [params] - The query parameters
@ -339,6 +339,21 @@ class QueryBuilder extends QueryBuilderBase {
return this.state; return this.state;
} }
/**
* Empties the selected database table
*
* @param {string} table - the name of the table to truncate
* @param {function} [callback] - Optional callback
* @return {void|Promise} - Returns a promise if no callback is supplied
*/
truncate(/*table:string, [callback]:function*/) {
getArgs('table:string, [callback]:function', arguments);
let args = [].slice.apply(arguments);
let sql = this.driver.truncate(args.shift());
args.unshift(sql);
return this.query.apply(this, args);
}
/** /**
* Closes the database connection for the current adapter * Closes the database connection for the current adapter
* *
@ -865,7 +880,7 @@ class QueryBuilder extends QueryBuilderBase {
* @param {Function} [callback] - Callback for handling response from the database * @param {Function} [callback] - Callback for handling response from the database
* @return {void|Promise} - If no callback is passed, a promise is returned * @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); let args = getArgs('table:string, [where]:object, [callback]:function', arguments);
if (args.where) { if (args.where) {

95
lib/Result.js Normal file
View File

@ -0,0 +1,95 @@
'use strict';
const helpers = require('./helpers');
/**
* 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;

71
lib/adapters/Mysql.js Normal file
View File

@ -0,0 +1,71 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const helpers = require('../helpers');
const getArgs = require('getargs');
const mysql2 = require('mysql2');
class Mysql extends Adapter {
constructor(config) {
let instance = mysql2.createConnection(config);
instance.connect(err => {
if (err) {
throw new Error(err);
}
});
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
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
return new Promise((resolve, reject) => {
this.instance.execute(args.sql, args.params, (err, result) =>
(err)
? reject(err)
: resolve(this.transformResult(result))
);
});
}
return this.instance.execute(args.sql, args.params, (err, rows) =>
args.callback(err, this.transformResult(rows))
);
}
}
module.exports = Mysql;

102
lib/adapters/Pg.js Normal file
View File

@ -0,0 +1,102 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const getArgs = require('getargs');
const helpers = require('../helpers');
const pg = require('pg');
const url = require('url');
class Pg extends Adapter {
constructor(config) {
let instance = null;
let connectionString = '';
if (helpers.isObject(config)) {
let host = config.host || 'localhost';
let user = config.user || 'postgres';
let password = `:${config.password}` || '';
let port = config.port || 5432;
let conn = {
protocol: 'postgres',
slashes: true,
host: `${host}:${port}`,
auth: `${user}${password}`,
pathname: config.database,
};
connectionString = url.format(conn);
} else if (helpers.isString(config)) {
connectionString = config;
}
if (connectionString !== '') {
let connected = false;
instance = new pg.Client(connectionString);
instance.connect(err => {
connected = true;
if (err) {
throw new Error(err);
}
});
}
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
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
// Replace question marks with numbered placeholders, because this adapter is different...
let count = 0;
args.sql = args.sql.replace(/\?/g, () => {
count++;
return `$${count}`;
});
if (! args.callback) {
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, (err, origResult) => {
let result = this.transformResult(origResult);
return args.callback(err, result);
});
}
}
module.exports = Pg;

64
lib/adapters/Sqlite.js Normal file
View File

@ -0,0 +1,64 @@
'use strict';
const Adapter = require('../Adapter');
const Result = require('../Result');
const getArgs = require('getargs');
const helpers = require('../helpers');
const dbliteAdapter = require('dblite');
class Sqlite extends Adapter {
constructor(config) {
let file = (helpers.isString(config)) ? config : config.file;
super(dbliteAdapter(file));
// Stop the stupid 'bye bye' message being output
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
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
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, (err, res) => {
args.callback(err, this.transformResult(res));
});
}
/**
* Close the current database connection
* @return {void}
*/
close() {
this.instance.close();
}
}
module.exports = Sqlite;

View File

@ -1,34 +0,0 @@
'use strict';
let Adapter = require('../Adapter'),
getArgs = require('getargs'),
promisify = require('../promisify');
module.exports = class dblite extends Adapter {
/**
* Run the sql query as a prepared statement
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
return promisify(this.instance.query)(args.sql, args.params);
}
return this.instance.query(args.sql, args.params, args.callback);
}
/**
* Close the current database connection
* @return {void}
*/
close() {
this.instance.close();
}
};

View File

@ -1,25 +0,0 @@
'use strict';
let Adapter = require('../Adapter'),
getArgs = require('getargs'),
promisify = require('../promisify');
module.exports = class mysql extends Adapter {
/**
* Run the sql query as a prepared statement
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(sql, params, callback) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
return promisify(this.instance.query)(args.sql, args.params);
}
return this.instance.query(args.sql, args.params, args.callback);
}
};

View File

@ -1,25 +0,0 @@
'use strict';
let Adapter = require('../Adapter'),
getArgs = require('getargs'),
promisify = require('../promisify');
module.exports = class mysql2 extends Adapter {
/**
* Run the sql query as a prepared statement
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
if (! args.callback) {
return promisify(this.instance.execute)(args.sql, args.params);
}
return this.instance.execute(args.sql, args.params, args.callback);
}
};

View File

@ -1,43 +0,0 @@
'use strict';
let Adapter = require('../Adapter'),
getArgs = require('getargs');
module.exports = class nodefirebird extends Adapter {
/**
* Run the sql query as a prepared statement
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params], [callback]:function', arguments);
if (! args.callback) {
//return instance.queryAsync(args.sql, args.params);
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);
});
});
}
}
return this.instance.query(args.sql, args.params, args.callback);
}
/**
* Close the current database connection
* @return {void}
*/
close() {
this.instance.detach();
}
};

View File

@ -1,39 +0,0 @@
'use strict';
let Adapter = require('../Adapter'),
getArgs = require('getargs');
module.exports = class pg extends Adapter {
/**
* Run the sql query as a prepared statement
*
* @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided
*/
execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
// Replace question marks with numbered placeholders, because this adapter is different...
let count = 0;
args.sql = args.sql.replace(/\?/g, () => {
count++;
return `$${count}`;
});
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);
});
});
}
return this.instance.query(args.sql, args.params, args.callback);
}
};

View File

@ -1,46 +0,0 @@
'use strict';
let helpers = require('../helpers');
/**
* Driver for Firebird databases
*
* @module drivers/firebird
*/
module.exports = (() => {
delete require.cache[require.resolve('../Driver')];
let driver = require('../Driver');
driver.hasTruncate = false;
/**
* Set the limit clause
* @param {String} origSql - SQL statement to modify
* @param {Number} limit - Maximum number of rows to fetch
* @param {Number|null} offset - Number of rows to skip
* @return {String} - Modified SQL statement
*/
driver.limit = (origSql, limit, offset) => {
let sql = `FIRST ${limit}`;
if (helpers.isNumber(offset))
{
sql += ` SKIP ${offset}`;
}
return origSql.replace(/SELECT/i, `SELECT ${sql}`);
};
/**
* SQL to insert a group of rows
*
* @return {void}
* @throws {Error}
*/
driver.insertBatch = () => {
throw new Error('Not Implemented');
};
return driver;
})();

View File

@ -50,9 +50,7 @@ module.exports = (() => {
sql += `SELECT ${cols.join(', ')}\n`; sql += `SELECT ${cols.join(', ')}\n`;
vals.forEach(rowValues => { vals.forEach(rowValues => {
let quoted = rowValues.map(value => { let quoted = rowValues.map(value => String(value).replace('\'', '\'\''));
return String(value).replace('\'', '\'\'');
});
sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`; sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`;
}); });

View File

@ -1,27 +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) => {
return error ? reject(error) : resolve(value);
}));
});
};
}
module.exports = promisify;
/*eslint-enable prefer-arrow-callback*/

View File

@ -1,6 +1,6 @@
{ {
"name": "ci-node-query", "name": "ci-node-query",
"version": "3.2.0", "version": "4.0.0",
"description": "A query builder for node based on the one in CodeIgniter", "description": "A query builder for node based on the one in CodeIgniter",
"author": "Timothy J Warren <tim@timshomepage.net>", "author": "Timothy J Warren <tim@timshomepage.net>",
"engines": { "engines": {
@ -22,14 +22,12 @@
"keywords": [ "keywords": [
"codeigniter", "codeigniter",
"mysql2", "mysql2",
"mysql",
"query builder", "query builder",
"pg", "pg",
"postgres", "postgres",
"sqlite3",
"sqlite", "sqlite",
"dblite", "dblite"
"firebird",
"node-firebird"
], ],
"bugs": { "bugs": {
"url": "https://git.timshomepage.net/timw4mail/node-query/issues" "url": "https://git.timshomepage.net/timw4mail/node-query/issues"
@ -38,32 +36,33 @@
"dependencies": { "dependencies": {
"dblite": "~0.7.6", "dblite": "~0.7.6",
"getargs": "~0.0.8", "getargs": "~0.0.8",
"mysql": "~2.10.2", "glob": "^7.0.3",
"mysql2": "~0.15.8", "mysql2": "^1.0.0-rc.1",
"node-firebird": "~0.7.2", "pg": "^4.5.1",
"pg": "~4.4.3",
"require-reload": "~0.2.2", "require-reload": "~0.2.2",
"xregexp": "^3.0.0" "xregexp": "^3.0.0"
}, },
"devDependencies": { "devDependencies": {
"chai": "~3.4.1", "chai": "^3.5.0",
"chai-as-promised": "^5.2.0", "chai-as-promised": "^5.2.0",
"documentation": "", "documentation": "",
"eslint": "~1.10.3", "eslint": "^2.4.0",
"glob": "~6.0.4", "glob": "~6.0.4",
"gulp": "~3.9.0", "gulp": "~3.9.0",
"gulp-documentation": "~2.1.0", "gulp-documentation": "^2.2.0",
"gulp-eslint": "~1.1.1", "gulp-eslint": "^2.0.0",
"gulp-istanbul": "^0.10.3", "gulp-istanbul": "^0.10.3",
"gulp-jscs": "^3.0.2", "gulp-jscs": "^3.0.2",
"gulp-mocha": "^2.2.0", "gulp-mocha": "^2.2.0",
"gulp-pipe": "^1.0.4", "gulp-pipe": "^1.0.4",
"gulp-sloc": "~1.0.4", "gulp-sloc": "~1.0.4",
"istanbul": "~0.4.2", "istanbul": "~0.4.2",
"mocha": "" "mocha": "^2.4.5"
}, },
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"predocs": "documentation build -f md -o API.md lib/*.js",
"docs": "documentation build -f html -o docs lib/*.js",
"test": "gulp test" "test": "gulp test"
} }
} }

View File

@ -1,7 +0,0 @@
{
"preset": "airbnb",
"validateIndentation": null,
"requireLineFeedAtFileEnd": null,
"disallowSpaceAfterPrefixUnaryOperators": null,
"disallowMultipleVarDecl": null
}

Binary file not shown.

View File

@ -3,51 +3,42 @@
// Load the test base // Load the test base
const reload = require('require-reload')(require); const reload = require('require-reload')(require);
reload.emptyCache(); reload.emptyCache();
const fs = require('fs');
const testBase = reload('../base'); const testBase = reload('../base');
const expect = testBase.expect, const expect = testBase.expect;
promiseTestRunner = testBase.promiseTestRunner, const promiseTestRunner = testBase.promiseTestRunner;
testRunner = testBase.testRunner; const testRunner = testBase.testRunner;
let tests = reload('../base/tests'); let tests = reload('../base/tests');
// Load the test config file // Load the test config file
let adapterName = 'dblite'; const config = testBase.config;
let sqlite = null;
let connection = null;
// Set up the connection
try {
sqlite = require(adapterName).withSQLite('3.7.11');
connection = sqlite(':memory:');
} catch (e) {
// Export an empty testsuite if module not loaded
}
if (connection) {
// Set up the query builder object // Set up the query builder object
let nodeQuery = require('../../lib/NodeQuery'); let nodeQuery = require('../../lib/NodeQuery')(config.dblite);
let qb = nodeQuery.init('sqlite', connection, adapterName); let qb = nodeQuery.getQuery();
suite('Dblite adapter tests -', () => { suite('Dblite adapter tests -', () => {
suiteSetup(done => { suiteSetup(done => {
// Set up the sqlite database // Set up the sqlite database
let sql = 'CREATE TABLE IF NOT EXISTS "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);' + fs.readFile(`${__dirname}/../sql/sqlite.sql`, 'utf8', (err, data) => {
'CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);'; if (err) {
connection.query(sql, () => { return done(err);
return done(); }
qb.query(data, () => done());
}); });
}); });
test('nodeQuery.getQuery = nodeQuery.init', () => {
expect(nodeQuery.getQuery())
.to.be.deep.equal(qb);
});
/*--------------------------------------------------------------------------- /*---------------------------------------------------------------------------
Callback Tests Callback Tests
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
testRunner(qb, (err, done) => { testRunner(qb, (err, result, done) => {
expect(err).is.not.ok; 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(); done();
}); });
test('Callback - Select with function and argument in WHERE clause', done => { test('Callback - Select with function and argument in WHERE clause', done => {
@ -76,7 +67,7 @@ if (connection) {
}, },
]; ];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, err => {
expect(err).is.not.ok; expect(err).is.not.ok;
return done(); return done();
}); });
@ -94,5 +85,29 @@ if (connection) {
expect(promise).to.be.fulfilled; expect(promise).to.be.fulfilled;
}); });
test('Promise - Test Insert Batch', () => {
let data = [
{
id: 544,
key: 3,
val: new Buffer('7'),
}, {
id: 89,
key: 34,
val: new Buffer('10 o\'clock'),
}, {
id: 48,
key: 403,
val: new Buffer('97'),
},
];
let promise = qb.query(qb.driver.truncate('create_test')).then(
() => qb.insertBatch('create_test', data)
);
expect(promise).to.be.fulfilled;
});
suiteTeardown(() => {
qb.end();
});
}); });
}

View File

@ -1,42 +0,0 @@
'use strict';
module.exports = function mysqlBase(qb, nodeQuery, expect, testRunner, promiseTestRunner) {
test('nodeQuery.getQuery = nodeQuery.init', () => {
expect(nodeQuery.getQuery())
.to.be.deep.equal(qb);
});
/*---------------------------------------------------------------------------
Callback Tests
---------------------------------------------------------------------------*/
testRunner(qb, (err, done) => {
expect(err).is.not.ok;
done();
});
test('Callback - Select with function and argument in WHERE clause', done => {
qb.select('id')
.from('create_test')
.where('id', 'CEILING(SQRT(88))')
.get((err, rows) => {
expect(err).is.not.ok;
return done();
});
});
/*---------------------------------------------------------------------------
Promise Tests
---------------------------------------------------------------------------*/
promiseTestRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id')
.from('create_test')
.where('id', 'CEILING(SQRT(88))')
.get();
expect(promise).to.be.fulfilled;
});
suiteTeardown(() => {
qb.end();
});
};

View File

@ -1,34 +1,51 @@
'use strict'; 'use strict';
const configFile = (process.env.TRAVIS) ? '../config-travis.json' : '../config.json';
// Load the test base // Load the test base
const reload = require('require-reload')(require); const reload = require('require-reload')(require);
reload.emptyCache(); reload.emptyCache();
const testBase = reload('../base'); const testBase = reload('../base');
const expect = testBase.expect, const expect = testBase.expect;
promiseTestRunner = testBase.promiseTestRunner, const promiseTestRunner = testBase.promiseTestRunner;
testRunner = testBase.testRunner; const testRunner = testBase.testRunner;
let getArgs = reload('getargs');
// Load the test config file // Load the test config file
let adapterName = 'mysql2'; let adapterName = 'mysql2';
let config = reload(configFile)[adapterName]; const config = testBase.config[adapterName];
// Set up the connection
let mysql2 = reload(adapterName);
let connection = mysql2.createConnection(config.conn);
// Set up the query builder object // Set up the query builder object
let nodeQuery = reload('../../lib/NodeQuery'); let nodeQuery = reload('../../lib/NodeQuery')(config);
let qb = nodeQuery.init('mysql', connection, adapterName); let qb = nodeQuery.getQuery();
qb.query(qb.driver.truncate('create_test')).then(() => {
suite('Mysql2 adapter tests -', () => { suite('Mysql2 adapter tests -', () => {
require('./mysql-base')(qb, nodeQuery, expect, testRunner, promiseTestRunner); suiteSetup(done => qb.truncate('create_test').then(() => done()));
test('Test Insert Batch', done => { test('nodeQuery.getQuery = nodeQuery.init', () => {
expect(nodeQuery.getQuery())
.to.be.deep.equal(qb);
});
//--------------------------------------------------------------------------
// Callback Tests
//--------------------------------------------------------------------------
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 => {
qb.select('id')
.from('create_test')
.where('id', 'CEILING(SQRT(88))')
.get((err, rows) => {
expect(err).is.not.ok;
return done();
});
});
test('Callback - Test Insert Batch', done => {
let data = [ let data = [
{ {
id: 5441, id: 5441,
@ -45,10 +62,46 @@ qb.query(qb.driver.truncate('create_test')).then(() => {
}, },
]; ];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, (err, res) => {
expect(err).is.not.ok; expect(err).is.not.ok;
return done(); return done(err);
}); });
}); });
//---------------------------------------------------------------------------
// Promise Tests
//---------------------------------------------------------------------------
promiseTestRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id')
.from('create_test')
.where('id', 'CEILING(SQRT(88))')
.get();
return expect(promise).to.be.fulfilled;
});
test('Test Insert Batch', () => {
let data = [
{
id: 5442,
key: 4,
val: new Buffer('7'),
}, {
id: 892,
key: 35,
val: new Buffer('10 o\'clock'),
}, {
id: 482,
key: 404,
val: 97,
},
];
return expect(qb.insertBatch('create_test', data)).to.be.fulfilled;
});
suiteTeardown(() => {
qb.end();
}); });
}); });

View File

@ -1,55 +0,0 @@
'use strict';
const configFile = (process.env.TRAVIS) ? '../config-travis.json' : '../config.json';
// Load the test base
const reload = require('require-reload')(require);
reload.emptyCache();
const testBase = reload('../base');
const expect = testBase.expect,
promiseTestRunner = testBase.promiseTestRunner,
testRunner = testBase.testRunner;
let getArgs = reload('getargs');
// Load the test config file
let adapterName = 'mysql';
let config = reload(configFile)[adapterName];
// Set up the connection
let mysql = reload(adapterName);
let connection = mysql.createConnection(config.conn);
// Set up the query builder object
let nodeQuery = reload('../../lib/NodeQuery');
let qb = nodeQuery.init('mysql', connection);
qb.query(qb.driver.truncate('create_test')).then(() => {
suite('Mysql adapter tests -', () => {
require('./mysql-base')(qb, nodeQuery, expect, testRunner, promiseTestRunner);
test('Test Insert Batch', done => {
let data = [
{
id: 544,
key: 3,
val: new Buffer('7'),
}, {
id: 89,
key: 34,
val: new Buffer('10 o\'clock'),
}, {
id: 48,
key: 403,
val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, rows) => {
expect(err).is.not.ok;
return done();
});
});
});
});

View File

@ -1,61 +0,0 @@
'use strict';
(() => {
// Load the test base
const path = require('path');
const reload = require('require-reload')(require);
const testBase = reload('../base');
const promisify = require('../../lib/promisify');
const expect = reload('chai').expect;
const testRunner = testBase.testRunner;
const promiseTestRunner = testBase.promiseTestRunner;
// Load the test config file
let adapterName = 'node-firebird';
let Firebird = reload(adapterName);
const config = reload('../config.json')[adapterName];
config.conn.database = path.join(__dirname, config.conn.database);
let nodeQuery = reload('../../lib/NodeQuery');
let qb = null;
// Skip on TravisCi
if (process.env.CI) {
return;
}
// Promisifying the connection seems to be the only way to get
// this test suite to run consistently.
promisify(Firebird.attach)(config.conn).then(db => {
qb = nodeQuery.init('firebird', db, adapterName);
suite('Firebird adapter tests -', () => {
test('nodeQuery.getQuery = nodeQuery.init', () => {
expect(nodeQuery.getQuery())
.to.be.deep.equal(qb);
});
test('insertBatch throws error', () => {
expect(() => {
qb.driver.insertBatch('create_test', []);
}).to.throw(Error, 'Not Implemented');
});
/*---------------------------------------------------------------------------
Callback Tests
---------------------------------------------------------------------------*/
testRunner(qb, (err, done) => {
expect(err).is.not.ok;
done();
});
/*---------------------------------------------------------------------------
Promise Tests
---------------------------------------------------------------------------*/
/*qb.adapter.execute(qb.driver.truncate('create_test')).then(() => {
promiseTestRunner(qb);
});*/
suiteTeardown(() => {
qb.end();
});
});
}).catch(err => {
throw new Error(err);
});
})();

View File

@ -1,41 +1,45 @@
'use strict'; 'use strict';
let configFile = (process.env.CI) ? '../config-travis.json' : '../config.json';
// Load the test base // Load the test base
const reload = require('require-reload')(require); const reload = require('require-reload')(require);
reload.emptyCache(); reload.emptyCache();
const testBase = reload('../base'); const testBase = reload('../base');
const expect = testBase.expect, const expect = testBase.expect;
promiseTestRunner = testBase.promiseTestRunner, const promiseTestRunner = testBase.promiseTestRunner;
testRunner = testBase.testRunner; const testRunner = testBase.testRunner;
// Load the test config file // Load the test config file
let adapterName = 'pg'; let adapterName = 'pg';
let config = reload(configFile)[adapterName]; const allConfig = testBase.config;
const config = allConfig[adapterName];
// Set up the connection
let pg = reload(adapterName);
let connection = new pg.Client(config.conn);
// Set up the query builder object // Set up the query builder object
let nodeQuery = reload('../../lib/NodeQuery'); let nodeQuery = reload('../../lib/NodeQuery')(config);
let qb = nodeQuery.init('pg', connection); let qb = nodeQuery.getQuery();
let qb2 = null;
suite('Pg adapter tests -', () => { suite('Pg adapter tests -', () => {
suiteSetup(done => {
return connection.connect(done);
});
test('nodeQuery.getQuery = nodeQuery.init', () => { test('nodeQuery.getQuery = nodeQuery.init', () => {
expect(nodeQuery.getQuery()) expect(nodeQuery.getQuery())
.to.be.deep.equal(qb); .to.be.deep.equal(qb);
}); });
/*--------------------------------------------------------------------------- test('Connecting with an object also works', () => {
Callback Tests let config = allConfig[`${adapterName}-object`];
---------------------------------------------------------------------------*/ let nodeQuery = reload('../../lib/NodeQuery')(config);
testRunner(qb, (err, done) => { qb2 = nodeQuery.getQuery();
return expect(qb2).to.be.ok;
});
//--------------------------------------------------------------------------
// Callback Tests
//--------------------------------------------------------------------------
testRunner(qb, (err, result, done) => {
expect(err).is.not.ok; expect(err).is.not.ok;
expect(result.rows).is.an('array');
expect(result.rowCount()).to.not.be.undefined;
expect(result.columnCount()).to.not.be.undefined;
done(); done();
}); });
test('Callback - Select with function and argument in WHERE clause', done => { test('Callback - Select with function and argument in WHERE clause', done => {
@ -43,14 +47,37 @@ suite('Pg adapter tests -', () => {
.from('create_test') .from('create_test')
.where('id', 'CEILING(SQRT(88))') .where('id', 'CEILING(SQRT(88))')
.get((err, rows) => { .get((err, rows) => {
expect(rows).is.ok;
expect(err).is.not.ok; expect(err).is.not.ok;
return done(); return done(err);
});
});
test('Callback - Test Insert Batch', done => {
let data = [
{
id: 5441,
key: 3,
val: new Buffer('7'),
}, {
id: 891,
key: 34,
val: new Buffer('10 o\'clock'),
}, {
id: 481,
key: 403,
val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, res) => {
expect(err).is.not.ok;
return done(err);
}); });
}); });
/*--------------------------------------------------------------------------- //--------------------------------------------------------------------------
Promise Tests // Promise Tests
---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------
promiseTestRunner(qb); promiseTestRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => { test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id') let promise = qb.select('id')
@ -58,7 +85,7 @@ suite('Pg adapter tests -', () => {
.where('id', 'CEILING(SQRT(88))') .where('id', 'CEILING(SQRT(88))')
.get(); .get();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test Insert Batch', () => { test('Promise - Test Insert Batch', () => {
let data = [ let data = [
@ -80,4 +107,8 @@ suite('Pg adapter tests -', () => {
let promise = qb.insertBatch('create_test', data); let promise = qb.insertBatch('create_test', data);
return expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
suiteTeardown(() => {
qb.end();
qb2.end();
});
}); });

View File

@ -4,7 +4,11 @@ const chai = require('chai');
const chaiAsPromised = require('chai-as-promised'); const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised); chai.use(chaiAsPromised);
// Load the test config file
const configFile = './config.json';
module.exports = { module.exports = {
config: require(configFile),
expect: chai.expect, expect: chai.expect,
tests: require('./base/tests'), tests: require('./base/tests'),
testRunner: require('./base/adapterCallbackTestRunner'), testRunner: require('./base/adapterCallbackTestRunner'),

View File

@ -23,9 +23,7 @@ module.exports = function testRunner(qb, callback) {
let methodNames = Object.keys(methodObj); let methodNames = Object.keys(methodObj);
let lastMethodIndex = methodNames[methodNames.length - 1]; let lastMethodIndex = methodNames[methodNames.length - 1];
methodObj[lastMethodIndex].push((err, rows) => { methodObj[lastMethodIndex].push((err, rows) => callback(err, rows, done));
callback(err, done);
});
methodNames.forEach(name => { methodNames.forEach(name => {
let args = methodObj[name], let args = methodObj[name],
@ -46,18 +44,13 @@ module.exports = function testRunner(qb, callback) {
}); });
}); });
suite('DB update tests -', () => { suite('DB update tests -', () => {
setup(done => { suiteSetup(() => qb.truncate('create_test'));
let sql = qb.driver.truncate('create_test');
qb.adapter.execute(sql, (err, res) => {
done();
});
});
test('Callback - Test Insert', done => { test('Callback - Test Insert', done => {
qb.set('id', 98) qb.set('id', 98)
.set('key', '84') .set('key', '84')
.set('val', new Buffer('120')) .set('val', new Buffer('120'))
.insert('create_test', (err, rows) => { .insert('create_test', (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Test Insert Object', done => { test('Callback - Test Insert Object', done => {
@ -66,7 +59,7 @@ module.exports = function testRunner(qb, callback) {
key: 1, key: 1,
val: new Buffer('2'), val: new Buffer('2'),
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Test Update', done => { test('Callback - Test Update', done => {
@ -76,7 +69,7 @@ module.exports = function testRunner(qb, callback) {
key: 'gogle', key: 'gogle',
val: new Buffer('non-word'), val: new Buffer('non-word'),
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Test set Array Update', done => { test('Callback - Test set Array Update', done => {
@ -89,7 +82,7 @@ module.exports = function testRunner(qb, callback) {
qb.set(object) qb.set(object)
.where('id', 22) .where('id', 22)
.update('create_test', (err, rows) => { .update('create_test', (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Test where set update', done => { test('Callback - Test where set update', done => {
@ -98,18 +91,18 @@ module.exports = function testRunner(qb, callback) {
.set('key', 'gogle') .set('key', 'gogle')
.set('val', new Buffer('non-word')) .set('val', new Buffer('non-word'))
.update('create_test', (err, rows) => { .update('create_test', (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Test delete', done => { test('Callback - Test delete', done => {
qb.delete('create_test', {id: 5}, (err, rows) => { qb.delete('create_test', {id: 5}, (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Delete with where', done => { test('Callback - Delete with where', done => {
qb.where('id', 5) qb.where('id', 5)
.delete('create_test', (err, rows) => { .delete('create_test', (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Delete multiple where values', done => { test('Callback - Delete multiple where values', done => {
@ -117,7 +110,7 @@ module.exports = function testRunner(qb, callback) {
id: 5, id: 5,
key: 'gogle', key: 'gogle',
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
}); });
@ -131,7 +124,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd() .groupEnd()
.limit(2, 1) .limit(2, 1)
.get((err, rows) => { .get((err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Using where first grouping', done => { test('Callback - Using where first grouping', done => {
@ -144,7 +137,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd() .groupEnd()
.limit(2, 1) .limit(2, 1)
.get((err, rows) => { .get((err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Using or grouping method', done => { test('Callback - Using or grouping method', done => {
@ -159,7 +152,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd() .groupEnd()
.limit(2, 1) .limit(2, 1)
.get((err, rows) => { .get((err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
test('Callback - Using or not grouping method', done => { test('Callback - Using or not grouping method', done => {
@ -174,7 +167,7 @@ module.exports = function testRunner(qb, callback) {
.groupEnd() .groupEnd()
.limit(2, 1) .limit(2, 1)
.get((err, rows) => { .get((err, rows) => {
return callback(err, done); return callback(err, rows, done);
}); });
}); });
}); });
@ -184,32 +177,32 @@ module.exports = function testRunner(qb, callback) {
.from('create_test') .from('create_test')
.getCompiledSelect(true); .getCompiledSelect(true);
expect(helpers.isString(sql)).to.be.true; return expect(helpers.isString(sql)).to.be.true;
}); });
test('select from', () => { test('select from', () => {
let sql = qb.select('id') let sql = qb.select('id')
.getCompiledSelect('create_test', true); .getCompiledSelect('create_test', true);
expect(helpers.isString(sql)).to.be.true; return expect(helpers.isString(sql)).to.be.true;
}); });
test('insert', () => { test('insert', () => {
let sql = qb.set('id', 3) let sql = qb.set('id', 3)
.getCompiledInsert('create_test'); .getCompiledInsert('create_test');
expect(helpers.isString(sql)).to.be.true; return expect(helpers.isString(sql)).to.be.true;
}); });
test('update', () => { test('update', () => {
let sql = qb.set('id', 3) let sql = qb.set('id', 3)
.where('id', 5) .where('id', 5)
.getCompiledUpdate('create_test'); .getCompiledUpdate('create_test');
expect(helpers.isString(sql)).to.be.true; return expect(helpers.isString(sql)).to.be.true;
}); });
test('delete', () => { test('delete', () => {
let sql = qb.where('id', 5) let sql = qb.where('id', 5)
.getCompiledDelete('create_test'); .getCompiledDelete('create_test');
expect(helpers.isString(sql)).to.be.true; return expect(helpers.isString(sql)).to.be.true;
}); });
}); });
suite('Misc tests -', () => { suite('Misc tests -', () => {

View File

@ -40,7 +40,7 @@ module.exports = function promiseTestRunner(qb) {
}); });
let promise = results.pop(); let promise = results.pop();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
}); });
}); });
@ -48,11 +48,8 @@ module.exports = function promiseTestRunner(qb) {
suite('DB update tests -', () => { suite('DB update tests -', () => {
suiteSetup(done => { suiteSetup(done => {
let sql = qb.driver.truncate('create_test'); let sql = qb.driver.truncate('create_test');
qb.adapter.execute(sql).then(res => { qb.query(sql).then(res => done())
return done(); .catch(err => done(err));
}).catch(err => {
return done(err);
});
}); });
test('Promise - Test Insert', () => { test('Promise - Test Insert', () => {
let promise = qb.set('id', 98) let promise = qb.set('id', 98)
@ -60,7 +57,7 @@ module.exports = function promiseTestRunner(qb) {
.set('val', new Buffer('120')) .set('val', new Buffer('120'))
.insert('create_test'); .insert('create_test');
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test Insert Object', () => { test('Promise - Test Insert Object', () => {
let promise = qb.insert('create_test', { let promise = qb.insert('create_test', {
@ -69,7 +66,7 @@ module.exports = function promiseTestRunner(qb) {
val: new Buffer('2'), val: new Buffer('2'),
}); });
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test Update', () => { test('Promise - Test Update', () => {
let promise = qb.where('id', 7) let promise = qb.where('id', 7)
@ -79,7 +76,7 @@ module.exports = function promiseTestRunner(qb) {
val: new Buffer('non-word'), val: new Buffer('non-word'),
}); });
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test set Array Update', () => { test('Promise - Test set Array Update', () => {
let object = { let object = {
@ -92,7 +89,7 @@ module.exports = function promiseTestRunner(qb) {
.where('id', 22) .where('id', 22)
.update('create_test'); .update('create_test');
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test where set update', () => { test('Promise - Test where set update', () => {
let promise = qb.where('id', 36) let promise = qb.where('id', 36)
@ -101,17 +98,17 @@ module.exports = function promiseTestRunner(qb) {
.set('val', new Buffer('non-word')) .set('val', new Buffer('non-word'))
.update('create_test'); .update('create_test');
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Test delete', () => { test('Promise - Test delete', () => {
let promise = qb.delete('create_test', {id: 5}); let promise = qb.delete('create_test', {id: 5});
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Delete with where', () => { test('Promise - Delete with where', () => {
let promise = qb.where('id', 5) let promise = qb.where('id', 5)
.delete('create_test'); .delete('create_test');
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Delete multiple where values', () => { test('Promise - Delete multiple where values', () => {
let promise = qb.delete('create_test', { let promise = qb.delete('create_test', {
@ -119,7 +116,7 @@ module.exports = function promiseTestRunner(qb) {
key: 'gogle', key: 'gogle',
}); });
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
}); });
suite('Grouping tests -', () => { suite('Grouping tests -', () => {
@ -133,7 +130,7 @@ module.exports = function promiseTestRunner(qb) {
.limit(2, 1) .limit(2, 1)
.get(); .get();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Using where first grouping', () => { test('Promise - Using where first grouping', () => {
let promise = qb.select('id, key as k, val') let promise = qb.select('id, key as k, val')
@ -146,7 +143,7 @@ module.exports = function promiseTestRunner(qb) {
.limit(2, 1) .limit(2, 1)
.get(); .get();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Using or grouping method', () => { test('Promise - Using or grouping method', () => {
let promise = qb.select('id, key as k, val') let promise = qb.select('id, key as k, val')
@ -161,7 +158,7 @@ module.exports = function promiseTestRunner(qb) {
.limit(2, 1) .limit(2, 1)
.get(); .get();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
test('Promise - Using or not grouping method', () => { test('Promise - Using or not grouping method', () => {
let promise = qb.select('id, key as k, val') let promise = qb.select('id, key as k, val')
@ -176,7 +173,7 @@ module.exports = function promiseTestRunner(qb) {
.limit(2, 1) .limit(2, 1)
.get(); .get();
expect(promise).to.be.fulfilled; return expect(promise).to.be.fulfilled;
}); });
}); });
}; };

View File

@ -3,7 +3,7 @@
let expect = require('chai').expect, let expect = require('chai').expect,
reload = require('require-reload')(require), reload = require('require-reload')(require),
glob = require('glob'), glob = require('glob'),
nodeQuery = reload('../lib/NodeQuery'), nodeQuery = reload('../lib/NodeQuery')(),
Adapter = reload('../lib/Adapter'); Adapter = reload('../lib/Adapter');
suite('Base tests -', () => { suite('Base tests -', () => {
@ -30,7 +30,9 @@ suite('Base tests -', () => {
test('Invalid driver type', () => { test('Invalid driver type', () => {
expect(() => { expect(() => {
nodeQuery.init('foo', {}, 'bar'); reload('../lib/NodeQuery')({
driver: 'Foo',
});
}).to.throw(Error, 'Selected driver (Foo) does not exist!'); }).to.throw(Error, 'Selected driver (Foo) does not exist!');
}); });
@ -40,4 +42,11 @@ suite('Base tests -', () => {
a.execute(); a.execute();
}).to.throw(Error, 'Correct adapter not defined for query execution'); }).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');
});
}); });

View File

@ -1,28 +0,0 @@
{
"mysql": {
"driver": "mysql",
"conn": {
"host": "localhost",
"user": "root",
"password": "",
"database": "test"
}
},
"mysql2": {
"driver": "mysql",
"conn": {
"host": "localhost",
"user": "root",
"password": "",
"database": "test"
}
},
"pg": {
"driver": "pg",
"conn": "postgres://postgres@localhost/test"
},
"dblite": {
"driver": "sqlite",
"conn": ":memory:"
}
}

View File

@ -1,37 +0,0 @@
{
"mysql": {
"driver": "mysql",
"conn": {
"host": "localhost",
"user": "test",
"password": "",
"database": "test"
}
},
"mysql2": {
"driver": "mysql",
"conn": {
"host": "localhost",
"user": "test",
"password": "",
"database": "test"
}
},
"pg": {
"driver": "pg",
"conn": "postgres://test:test@localhost/test"
},
"dblite": {
"driver": "sqlite",
"conn": ":memory:"
},
"node-firebird": {
"driver": "firebird",
"conn": {
"host": "127.0.0.1",
"database": "/../FB_TEST_DB.FDB",
"user": "SYSDBA",
"password": "masterkey"
}
}
}

View File

@ -148,5 +148,11 @@ suite('Helper Module Tests -', () => {
expect(helpers.regexInArray([], /.*/)).to.be.false; expect(helpers.regexInArray([], /.*/)).to.be.false;
}); });
}); });
suite('upperCaseFirst -', () => {
test('Capitalizes only the first letter of the string', () => {
expect(helpers.upperCaseFirst('foobar')).to.equal('Foobar');
expect(helpers.upperCaseFirst('FOOBAR')).to.equal('FOOBAR');
});
});
}); });
}); });