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]
}
}

6
.gitignore vendored
View File

@ -1,6 +1,6 @@
build/*
coverage
coverage/*
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
## getQuery
**Parameters**
Return an existing query builder instance
- `config` **object** connection parameters
Returns **QueryBuilder** The Query Builder object
## constructor
## init
Create a query builder object
Constructor
**Parameters**
- `driverType` **String** The name of the database type, eg. mysql or pg
- `connObject` **Object** A connection object from the database library
you are connecting with
- `connLib` **[String]** The name of the db connection library you are
using, eg. mysql or mysql2. Optional if the same as driverType
- `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
Return an existing query builder instance
Returns **QueryBuilder** The Query Builder object
@ -370,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**
@ -427,6 +446,17 @@ query.set({foo:'bar'}); // Set with an object
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
Run the generated update query
@ -491,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

@ -1,5 +1,11 @@
# 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
* 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.

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.
[![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
* Callback and Promise API for making database calls.
### Supported adapters
### Supported databases
* mysql
* mysql2
* pg
* dblite
* node-firebird (Not supported as of version 3.1.0, as the adapter is very difficult to test)
* Mysql (via `mysql2`)
* PostgreSQL (via `pg`)
* Sqlite (via `dblite`)
### 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/)
(Versions 3.x and below work differently. Their documentation is [here](https://git.timshomepage.net/timw4mail/node-query/tree/v3#README))
### Basic use
```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
var query = nodeQuery.init('mysql', connection, 'mysql2');
// 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();
// Get the query builder
const query = nodeQuery.getQuery();
query.select('foo')
.from('bar')
@ -48,8 +45,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
@ -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
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

@ -27,16 +27,16 @@
class='block bold'>
NodeQuery
</a>
<a
href='#NodeQuery.constructor'
class='regular block'>
#constructor
</a>
<a
href='#NodeQuery.getQuery'
class='regular block'>
#getQuery
</a>
<a
href='#NodeQuery.init'
class='regular block'>
#init
</a>
<a
href='#QueryBuilder'
class='block bold'>
@ -207,6 +207,11 @@
class='regular block'>
#set
</a>
<a
href='#QueryBuilder.truncate'
class='regular block'>
#truncate
</a>
<a
href='#QueryBuilder.update'
class='regular block'>
@ -237,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>
@ -244,11 +264,64 @@
<div class='px2'>
<div class='py1'><section class='py2 clearfix'>
<h2 id='NodeQuery' class='mt0'>
NodeQuery<span class='gray'></span>
NodeQuery<span class='gray'>(config)</span>
</h2>
<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>
<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'>
<a href='#NodeQuery.getQuery'>
<code>
@ -276,59 +349,6 @@
</section>
</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>
</div><div class='py1'><section class='py2 clearfix'>
<h2 id='QueryBuilder' class='mt0'>
@ -1613,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>
@ -1622,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'>
@ -1769,6 +1789,50 @@ prefixed with &apos;OR NOT&apos;</p>
</section>
</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'>
<a href='#QueryBuilder.update'>
<code>
@ -2027,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

@ -15,45 +15,6 @@ const TEST_FILES = [
'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 = {
ui: 'tdd',
bail: true,
@ -63,7 +24,7 @@ const MOCHA_OPTIONS = {
gulp.task('lint', () => {
pipe(gulp.src(SRC_FILES), [
eslint(ESLINT_SETTINGS),
eslint(),
eslint.format(),
eslint.failAfterError()
]);
@ -75,7 +36,7 @@ gulp.task('lint', () => {
gulp.task('lint-tests', ['lint'], () => {
pipe(gulp.src(['test/**/*.js']), [
eslint(ESLINT_SETTINGS),
eslint(),
eslint.format(),
eslint.failAfterError()
]);
@ -101,11 +62,11 @@ gulp.task('mocha', ['lint-tests', 'sloc'], () => {
return gulp.src(TEST_FILES)
.pipe(mocha(MOCHA_OPTIONS))
.once('error', () => {
process.exit(1);
})
process.exit(1);
})
.once('end', () => {
process.exit();
});
process.exit();
});
});
gulp.task('test', ['test-sloc', 'lint-tests'], function(cb) {
@ -117,14 +78,8 @@ gulp.task('test', ['test-sloc', 'lint-tests'], function(cb) {
mocha(MOCHA_OPTIONS),
istanbul.writeReports({
dir: './coverage',
reporters: ['clover', 'lcov', 'lcovonly', 'html', 'text']
})
.once('error', () => {
process.exit(1);
})
.once('end', () => {
process.exit();
})
reporters: ['clover', 'lcov', 'lcovonly', 'html', 'text'],
}),
]);
});
});

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

@ -1,59 +1,63 @@
'use strict';
let fs = require('fs'),
helpers = require('./helpers'),
QueryBuilder = require('./QueryBuilder');
const helpers = require('./helpers');
const 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
*
* @param {object} config - connection parameters
*/
class NodeQuery {
/**
* Constructor
*
* @private
* @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() {
constructor(config) {
this.instance = null;
}
/**
* Create a query builder object
*
* @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;
if (config != null) {
let drivername = dbDriverMap.get(config.driver);
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!`
);
if (! drivername) {
throw new Error(`Selected driver (${config.driver}) does not exist!`);
}
});
let driver = require(paths.driver);
let $adapter = require(paths.adapter);
let adapter = new $adapter(connObject);
let driver = require(`./drivers/${drivername}`);
let $adapter = require(`./adapters/${drivername}`);
this.instance = new QueryBuilder(driver, adapter);
return this.instance;
let adapter = new $adapter(config.connection);
this.instance = new QueryBuilder(driver, adapter);
}
}
/**
@ -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 {array} [params] - The query parameters
@ -339,6 +339,21 @@ class QueryBuilder extends QueryBuilderBase {
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
*
@ -865,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) {

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: `