diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..2116a09 --- /dev/null +++ b/.eslintrc @@ -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] + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index f048cf0..5bf2dd4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ build/* coverage -coverage/* npm-debug.log -tests/FB_TEST_DB.FD -node_modules/* \ No newline at end of file +node_modules/* +.sonar/* +test/config.json \ No newline at end of file diff --git a/.istanbul.yml b/.istanbul.yml deleted file mode 100644 index 1a66a95..0000000 --- a/.istanbul.yml +++ /dev/null @@ -1,6 +0,0 @@ -reporting: - reports: - - lcov - - lcovonly - report-config: - lcovonly: {file: ../coverage/lcov.info} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 199d7f1..0000000 --- a/.travis.yml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/API.md b/API.md index 3e1bd3f..70e758d 100644 --- a/API.md +++ b/API.md @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 81a7d81..94b7191 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index c25cdb5..5eaefcc 100755 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/assets/fonts/source-code-pro/LICENSE.txt b/docs/assets/fonts/source-code-pro/LICENSE.txt new file mode 100755 index 0000000..d154618 --- /dev/null +++ b/docs/assets/fonts/source-code-pro/LICENSE.txt @@ -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. diff --git a/docs/assets/fonts/source-code-pro/README.md b/docs/assets/fonts/source-code-pro/README.md new file mode 100755 index 0000000..20be1f3 --- /dev/null +++ b/docs/assets/fonts/source-code-pro/README.md @@ -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). diff --git a/docs/assets/fonts/source-code-pro/WOFF/OTF/SourceCodePro-Regular.otf.woff b/docs/assets/fonts/source-code-pro/WOFF/OTF/SourceCodePro-Regular.otf.woff new file mode 100755 index 0000000..395436e Binary files /dev/null and b/docs/assets/fonts/source-code-pro/WOFF/OTF/SourceCodePro-Regular.otf.woff differ diff --git a/docs/assets/fonts/source-code-pro/source-code-pro.css b/docs/assets/fonts/source-code-pro/source-code-pro.css new file mode 100755 index 0000000..842b232 --- /dev/null +++ b/docs/assets/fonts/source-code-pro/source-code-pro.css @@ -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'); +} diff --git a/docs/assets/fonts/source-sans-pro/LICENSE.txt b/docs/assets/fonts/source-sans-pro/LICENSE.txt new file mode 100755 index 0000000..87ec82c --- /dev/null +++ b/docs/assets/fonts/source-sans-pro/LICENSE.txt @@ -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. diff --git a/docs/assets/fonts/source-sans-pro/README.md b/docs/assets/fonts/source-sans-pro/README.md new file mode 100755 index 0000000..a3e1b9d --- /dev/null +++ b/docs/assets/fonts/source-sans-pro/README.md @@ -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). diff --git a/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Bold.otf.woff b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Bold.otf.woff new file mode 100755 index 0000000..6700893 Binary files /dev/null and b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Bold.otf.woff differ diff --git a/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Light.otf.woff b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Light.otf.woff new file mode 100755 index 0000000..10490ec Binary files /dev/null and b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Light.otf.woff differ diff --git a/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Regular.otf.woff b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Regular.otf.woff new file mode 100755 index 0000000..04739e7 Binary files /dev/null and b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Regular.otf.woff differ diff --git a/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Semibold.otf.woff b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Semibold.otf.woff new file mode 100755 index 0000000..17d744d Binary files /dev/null and b/docs/assets/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Semibold.otf.woff differ diff --git a/docs/assets/fonts/source-sans-pro/bower.json b/docs/assets/fonts/source-sans-pro/bower.json new file mode 100755 index 0000000..dfe14f2 --- /dev/null +++ b/docs/assets/fonts/source-sans-pro/bower.json @@ -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": ["**/.*"] +} diff --git a/docs/assets/fonts/source-sans-pro/source-sans-pro.css b/docs/assets/fonts/source-sans-pro/source-sans-pro.css new file mode 100755 index 0000000..6d3862c --- /dev/null +++ b/docs/assets/fonts/source-sans-pro/source-sans-pro.css @@ -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'); +} diff --git a/docs/index.html b/docs/index.html index db802e2..9d2aa12 100644 --- a/docs/index.html +++ b/docs/index.html @@ -27,16 +27,16 @@ class='block bold'> NodeQuery + + #constructor + #getQuery - - #init - @@ -207,6 +207,11 @@ class='regular block'> #set + + #truncate + @@ -237,6 +242,21 @@ class='regular block'> #whereNotIn + + Result + + + #columnCount + + + #rowCount + @@ -244,11 +264,64 @@

- NodeQuery + NodeQuery(config)

Class for connection management

+

Parameters

+
    +
  • object config + : +
    +

    connection parameters

    + +
    +
  • +

Instance members

+
+ + + #constructor(config) + +
+

Constructor

+ +
+
+
+
+

+ constructor(config) +

+

Constructor

+ +

Parameters

+
    +
  • object config + : +
    +

    connection parameters

    + +
    +
  • +
+

Examples

+
let nodeQuery = require('ci-node-query')({
+            	driver: 'mysql',
+            	connection: {
+            		host: 'localhost',
+            		user: 'root',
+            		password: '',
+            		database: 'mysql'
+            	}
+            });
let nodeQuery = require('ci-node-query')({
+            	driver: 'sqlite',
+            	connection: ':memory:'
+            });
+
+
+
-
- - - #init(driverType, connObject, [connLib]) - -
-

Create a query builder object

- -
-
-
-
-

- init(driverType, connObject, [connLib]) -

-

Create a query builder object

- -

Parameters

-
    -
  • String driverType - : -
    -

    The name of the database type, eg. mysql or pg

    - -
    -
  • -
  • Object connObject - : -
    -

    A connection object from the database library - you are connecting with

    - -
    -
  • -
  • [String] connLib - : -
    -

    The name of the db connection library you are - using, eg. mysql or mysql2. Optional if the same as driverType

    - -
    -
  • -
-

Returns

- QueryBuilder - : -
-

The Query Builder object

- -
-
-
-

@@ -1613,7 +1633,7 @@ prefixed with 'OR NOT'

#query(sql, [params], [callback])
-

Manually make an sql query

+

Run an arbitrary sql query. Run as a prepared statement.

@@ -1622,7 +1642,7 @@ prefixed with 'OR NOT'

query(sql, [params], [callback])

-

Manually make an sql query

+

Run an arbitrary sql query. Run as a prepared statement.

Parameters

+
+ + + #truncate(table, [callback]) + +
+

Empties the selected database table

+ +
+
+
+
+

+ truncate(table, [callback]) +

+

Empties the selected database table

+ +

Parameters

+
    +
  • string table + : +
    +

    the name of the table to truncate

    + +
    +
  • +
  • [function] callback + : +
    +

    Optional callback

    + +
    +
  • +
+

Returns

+ void or Promise + : +
+

Returns a promise if no callback is supplied

+ +
+
+
+
@@ -2027,6 +2091,85 @@ prefixed with 'OR NOT'

+
+

+ Result(rows, columns) +

+

Query result object

+ +

Parameters

+
    +
  • Array rows + : +
    +

    the data rows of the result

    + +
    +
  • +
  • Array columns + : +
    +

    the column names in the result

    + +
    +
  • +
+

Instance members

+
+ + + #columnCount + +
+

Get the number of columns returned by the query

+ +
+
+
+
+

+ 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

+ +
+
+
+
+

+ rowCount +

+

Get the number of rows returned by the query

+ +

Returns

+ Number + : +
+

the number of rows in the result

+ +
+
+
+
+
diff --git a/gulpfile.js b/gulpfile.js index 487e2eb..f44752f 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -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'], + }), ]); }); }); diff --git a/lib/Adapter.js b/lib/Adapter.js index c5a249b..8ac77ac 100755 --- a/lib/Adapter.js +++ b/lib/Adapter.js @@ -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} diff --git a/lib/NodeQuery.js b/lib/NodeQuery.js index 58d4652..4cedd6c 100755 --- a/lib/NodeQuery.js +++ b/lib/NodeQuery.js @@ -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(); \ No newline at end of file +module.exports = (config => new NodeQuery(config)); \ No newline at end of file diff --git a/lib/QueryBuilder.js b/lib/QueryBuilder.js index d097b2a..216ef2c 100755 --- a/lib/QueryBuilder.js +++ b/lib/QueryBuilder.js @@ -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) { diff --git a/lib/Result.js b/lib/Result.js new file mode 100644 index 0000000..7f0b185 --- /dev/null +++ b/lib/Result.js @@ -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; \ No newline at end of file diff --git a/lib/adapters/Mysql.js b/lib/adapters/Mysql.js new file mode 100644 index 0000000..817013b --- /dev/null +++ b/lib/adapters/Mysql.js @@ -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; \ No newline at end of file diff --git a/lib/adapters/Pg.js b/lib/adapters/Pg.js new file mode 100644 index 0000000..996737c --- /dev/null +++ b/lib/adapters/Pg.js @@ -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; \ No newline at end of file diff --git a/lib/adapters/Sqlite.js b/lib/adapters/Sqlite.js new file mode 100644 index 0000000..19e4a1a --- /dev/null +++ b/lib/adapters/Sqlite.js @@ -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; diff --git a/lib/adapters/dblite.js b/lib/adapters/dblite.js deleted file mode 100644 index 6502721..0000000 --- a/lib/adapters/dblite.js +++ /dev/null @@ -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(); - } -}; \ No newline at end of file diff --git a/lib/adapters/mysql.js b/lib/adapters/mysql.js deleted file mode 100644 index cdbe571..0000000 --- a/lib/adapters/mysql.js +++ /dev/null @@ -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); - } -}; \ No newline at end of file diff --git a/lib/adapters/mysql2.js b/lib/adapters/mysql2.js deleted file mode 100644 index e3e1c28..0000000 --- a/lib/adapters/mysql2.js +++ /dev/null @@ -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); - } -}; \ No newline at end of file diff --git a/lib/adapters/node-firebird.js b/lib/adapters/node-firebird.js deleted file mode 100644 index 0c121a0..0000000 --- a/lib/adapters/node-firebird.js +++ /dev/null @@ -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(); - } -}; \ No newline at end of file diff --git a/lib/adapters/pg.js b/lib/adapters/pg.js deleted file mode 100644 index e1d8294..0000000 --- a/lib/adapters/pg.js +++ /dev/null @@ -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); - } -}; \ No newline at end of file diff --git a/lib/drivers/Firebird.js b/lib/drivers/Firebird.js deleted file mode 100644 index 7f6d93c..0000000 --- a/lib/drivers/Firebird.js +++ /dev/null @@ -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; -})(); \ No newline at end of file diff --git a/lib/drivers/Sqlite.js b/lib/drivers/Sqlite.js index 6a7e6a3..f771128 100644 --- a/lib/drivers/Sqlite.js +++ b/lib/drivers/Sqlite.js @@ -50,9 +50,7 @@ module.exports = (() => { sql += `SELECT ${cols.join(', ')}\n`; vals.forEach(rowValues => { - let quoted = rowValues.map(value => { - return String(value).replace('\'', '\'\''); - }); + let quoted = rowValues.map(value => String(value).replace('\'', '\'\'')); sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`; }); diff --git a/lib/promisify.js b/lib/promisify.js deleted file mode 100644 index 1079b49..0000000 --- a/lib/promisify.js +++ /dev/null @@ -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*/ \ No newline at end of file diff --git a/package.json b/package.json index 4f68965..1190477 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ci-node-query", - "version": "3.2.0", + "version": "4.0.0", "description": "A query builder for node based on the one in CodeIgniter", "author": "Timothy J Warren ", "engines": { @@ -22,14 +22,12 @@ "keywords": [ "codeigniter", "mysql2", - "mysql", "query builder", "pg", "postgres", + "sqlite3", "sqlite", - "dblite", - "firebird", - "node-firebird" + "dblite" ], "bugs": { "url": "https://git.timshomepage.net/timw4mail/node-query/issues" @@ -38,32 +36,33 @@ "dependencies": { "dblite": "~0.7.6", "getargs": "~0.0.8", - "mysql": "~2.10.2", - "mysql2": "~0.15.8", - "node-firebird": "~0.7.2", - "pg": "~4.4.3", + "glob": "^7.0.3", + "mysql2": "^1.0.0-rc.1", + "pg": "^4.5.1", "require-reload": "~0.2.2", "xregexp": "^3.0.0" }, "devDependencies": { - "chai": "~3.4.1", + "chai": "^3.5.0", "chai-as-promised": "^5.2.0", "documentation": "", - "eslint": "~1.10.3", + "eslint": "^2.4.0", "glob": "~6.0.4", "gulp": "~3.9.0", - "gulp-documentation": "~2.1.0", - "gulp-eslint": "~1.1.1", + "gulp-documentation": "^2.2.0", + "gulp-eslint": "^2.0.0", "gulp-istanbul": "^0.10.3", "gulp-jscs": "^3.0.2", "gulp-mocha": "^2.2.0", "gulp-pipe": "^1.0.4", "gulp-sloc": "~1.0.4", "istanbul": "~0.4.2", - "mocha": "" + "mocha": "^2.4.5" }, "license": "MIT", "scripts": { + "predocs": "documentation build -f md -o API.md lib/*.js", + "docs": "documentation build -f html -o docs lib/*.js", "test": "gulp test" } } diff --git a/test/.jscsrc b/test/.jscsrc deleted file mode 100644 index 49f6214..0000000 --- a/test/.jscsrc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "preset": "airbnb", - "validateIndentation": null, - "requireLineFeedAtFileEnd": null, - "disallowSpaceAfterPrefixUnaryOperators": null, - "disallowMultipleVarDecl": null -} \ No newline at end of file diff --git a/test/FB_TEST_DB.FDB b/test/FB_TEST_DB.FDB deleted file mode 100755 index b682cad..0000000 Binary files a/test/FB_TEST_DB.FDB and /dev/null differ diff --git a/test/adapters/dblite_test.js b/test/adapters/dblite_test.js index 714a447..f90ae30 100644 --- a/test/adapters/dblite_test.js +++ b/test/adapters/dblite_test.js @@ -3,96 +3,111 @@ // Load the test base const reload = require('require-reload')(require); reload.emptyCache(); +const fs = require('fs'); const testBase = reload('../base'); -const expect = testBase.expect, - promiseTestRunner = testBase.promiseTestRunner, - testRunner = testBase.testRunner; - +const expect = testBase.expect; +const promiseTestRunner = testBase.promiseTestRunner; +const testRunner = testBase.testRunner; let tests = reload('../base/tests'); // Load the test config file -let adapterName = 'dblite'; -let sqlite = null; -let connection = null; +const config = testBase.config; -// 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 -} +// Set up the query builder object +let nodeQuery = require('../../lib/NodeQuery')(config.dblite); +let qb = nodeQuery.getQuery(); -if (connection) { - // Set up the query builder object - let nodeQuery = require('../../lib/NodeQuery'); - let qb = nodeQuery.init('sqlite', connection, adapterName); +suite('Dblite adapter tests -', () => { + suiteSetup(done => { + // Set up the sqlite database + fs.readFile(`${__dirname}/../sql/sqlite.sql`, 'utf8', (err, data) => { + if (err) { + return done(err); + } - suite('Dblite adapter tests -', () => { - suiteSetup(done => { - // Set up the sqlite database - let sql = 'CREATE TABLE IF NOT EXISTS "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);' + - 'CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);'; - connection.query(sql, () => { - return done(); - }); - }); - test('nodeQuery.getQuery = nodeQuery.init', () => { - expect(nodeQuery.getQuery()) - .to.be.deep.equal(qb); + qb.query(data, () => done()); }); + }); - /*--------------------------------------------------------------------------- - Callback Tests - ---------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------- + 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', 'ABS(-88)') - .get((err, rows) => { - expect(err).is.not.ok; - return done(); - }); - }); - test('Callback - 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) => { + 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', 'ABS(-88)') + .get((err, rows) => { expect(err).is.not.ok; return done(); }); - }); + }); + test('Callback - 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'), + }, + ]; - /*--------------------------------------------------------------------------- - Promise Tests - ---------------------------------------------------------------------------*/ - promiseTestRunner(qb); - test('Promise - Select with function and argument in WHERE clause', () => { - let promise = qb.select('id') - .from('create_test') - .where('id', 'ABS(-88)') - .get(); - - expect(promise).to.be.fulfilled; + qb.insertBatch('create_test', data, err => { + expect(err).is.not.ok; + return done(); }); }); -} \ No newline at end of file + + /*--------------------------------------------------------------------------- + Promise Tests + ---------------------------------------------------------------------------*/ + promiseTestRunner(qb); + test('Promise - Select with function and argument in WHERE clause', () => { + let promise = qb.select('id') + .from('create_test') + .where('id', 'ABS(-88)') + .get(); + + 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(); + }); +}); diff --git a/test/adapters/mysql-base.js b/test/adapters/mysql-base.js deleted file mode 100644 index 504ecd7..0000000 --- a/test/adapters/mysql-base.js +++ /dev/null @@ -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(); - }); -}; \ No newline at end of file diff --git a/test/adapters/mysql2_test.js b/test/adapters/mysql2_test.js index 791702b..c325be1 100644 --- a/test/adapters/mysql2_test.js +++ b/test/adapters/mysql2_test.js @@ -1,54 +1,107 @@ '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'); +const expect = testBase.expect; +const promiseTestRunner = testBase.promiseTestRunner; +const testRunner = testBase.testRunner; // Load the test config file let adapterName = 'mysql2'; -let config = reload(configFile)[adapterName]; - -// Set up the connection -let mysql2 = reload(adapterName); -let connection = mysql2.createConnection(config.conn); +const config = testBase.config[adapterName]; // Set up the query builder object -let nodeQuery = reload('../../lib/NodeQuery'); -let qb = nodeQuery.init('mysql', connection, adapterName); -qb.query(qb.driver.truncate('create_test')).then(() => { - suite('Mysql2 adapter tests -', () => { +let nodeQuery = reload('../../lib/NodeQuery')(config); +let qb = nodeQuery.getQuery(); - require('./mysql-base')(qb, nodeQuery, expect, testRunner, promiseTestRunner); +suite('Mysql2 adapter tests -', () => { - test('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'), - }, - ]; + suiteSetup(done => qb.truncate('create_test').then(() => done())); - qb.insertBatch('create_test', data, (err, rows) => { + 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 = [ + { + 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); }); }); -}); \ No newline at end of file + + //--------------------------------------------------------------------------- + // 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(); + }); +}); diff --git a/test/adapters/mysql_test.js b/test/adapters/mysql_test.js deleted file mode 100644 index b1d95d5..0000000 --- a/test/adapters/mysql_test.js +++ /dev/null @@ -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(); - }); - }); - }); -}); \ No newline at end of file diff --git a/test/adapters/node-firebird_test.js b/test/adapters/node-firebird_test.js deleted file mode 100644 index a546466..0000000 --- a/test/adapters/node-firebird_test.js +++ /dev/null @@ -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); - }); -})(); diff --git a/test/adapters/pg_test.js b/test/adapters/pg_test.js index 935ca59..c701685 100644 --- a/test/adapters/pg_test.js +++ b/test/adapters/pg_test.js @@ -1,41 +1,45 @@ 'use strict'; -let configFile = (process.env.CI) ? '../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; +const expect = testBase.expect; +const promiseTestRunner = testBase.promiseTestRunner; +const testRunner = testBase.testRunner; // Load the test config file let adapterName = 'pg'; -let config = reload(configFile)[adapterName]; - -// Set up the connection -let pg = reload(adapterName); -let connection = new pg.Client(config.conn); +const allConfig = testBase.config; +const config = allConfig[adapterName]; // Set up the query builder object -let nodeQuery = reload('../../lib/NodeQuery'); -let qb = nodeQuery.init('pg', connection); +let nodeQuery = reload('../../lib/NodeQuery')(config); +let qb = nodeQuery.getQuery(); +let qb2 = null; suite('Pg adapter tests -', () => { - suiteSetup(done => { - return connection.connect(done); - }); test('nodeQuery.getQuery = nodeQuery.init', () => { expect(nodeQuery.getQuery()) .to.be.deep.equal(qb); }); - /*--------------------------------------------------------------------------- - Callback Tests - ---------------------------------------------------------------------------*/ - testRunner(qb, (err, done) => { + test('Connecting with an object also works', () => { + let config = allConfig[`${adapterName}-object`]; + let nodeQuery = reload('../../lib/NodeQuery')(config); + qb2 = nodeQuery.getQuery(); + + return expect(qb2).to.be.ok; + }); + + //-------------------------------------------------------------------------- + // Callback Tests + //-------------------------------------------------------------------------- + testRunner(qb, (err, result, done) => { 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(); }); test('Callback - Select with function and argument in WHERE clause', done => { @@ -43,14 +47,37 @@ suite('Pg adapter tests -', () => { .from('create_test') .where('id', 'CEILING(SQRT(88))') .get((err, rows) => { + expect(rows).is.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'), + }, + ]; - /*--------------------------------------------------------------------------- - Promise Tests - ---------------------------------------------------------------------------*/ + qb.insertBatch('create_test', data, (err, res) => { + expect(err).is.not.ok; + return done(err); + }); + }); + + //-------------------------------------------------------------------------- + // Promise Tests + //-------------------------------------------------------------------------- promiseTestRunner(qb); test('Promise - Select with function and argument in WHERE clause', () => { let promise = qb.select('id') @@ -58,7 +85,7 @@ suite('Pg adapter tests -', () => { .where('id', 'CEILING(SQRT(88))') .get(); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test Insert Batch', () => { let data = [ @@ -80,4 +107,8 @@ suite('Pg adapter tests -', () => { let promise = qb.insertBatch('create_test', data); return expect(promise).to.be.fulfilled; }); + suiteTeardown(() => { + qb.end(); + qb2.end(); + }); }); \ No newline at end of file diff --git a/test/base.js b/test/base.js index 49a9cce..4e29ca7 100644 --- a/test/base.js +++ b/test/base.js @@ -4,7 +4,11 @@ const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); +// Load the test config file +const configFile = './config.json'; + module.exports = { + config: require(configFile), expect: chai.expect, tests: require('./base/tests'), testRunner: require('./base/adapterCallbackTestRunner'), diff --git a/test/base/adapterCallbackTestRunner.js b/test/base/adapterCallbackTestRunner.js index 4555cd0..9304d7b 100644 --- a/test/base/adapterCallbackTestRunner.js +++ b/test/base/adapterCallbackTestRunner.js @@ -23,9 +23,7 @@ module.exports = function testRunner(qb, callback) { let methodNames = Object.keys(methodObj); let lastMethodIndex = methodNames[methodNames.length - 1]; - methodObj[lastMethodIndex].push((err, rows) => { - callback(err, done); - }); + methodObj[lastMethodIndex].push((err, rows) => callback(err, rows, done)); methodNames.forEach(name => { let args = methodObj[name], @@ -46,18 +44,13 @@ module.exports = function testRunner(qb, callback) { }); }); suite('DB update tests -', () => { - setup(done => { - let sql = qb.driver.truncate('create_test'); - qb.adapter.execute(sql, (err, res) => { - done(); - }); - }); + suiteSetup(() => qb.truncate('create_test')); test('Callback - Test Insert', done => { qb.set('id', 98) .set('key', '84') .set('val', new Buffer('120')) .insert('create_test', (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Test Insert Object', done => { @@ -66,7 +59,7 @@ module.exports = function testRunner(qb, callback) { key: 1, val: new Buffer('2'), }, (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Test Update', done => { @@ -76,7 +69,7 @@ module.exports = function testRunner(qb, callback) { key: 'gogle', val: new Buffer('non-word'), }, (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Test set Array Update', done => { @@ -89,7 +82,7 @@ module.exports = function testRunner(qb, callback) { qb.set(object) .where('id', 22) .update('create_test', (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Test where set update', done => { @@ -98,18 +91,18 @@ module.exports = function testRunner(qb, callback) { .set('key', 'gogle') .set('val', new Buffer('non-word')) .update('create_test', (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Test delete', done => { qb.delete('create_test', {id: 5}, (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Delete with where', done => { qb.where('id', 5) .delete('create_test', (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Delete multiple where values', done => { @@ -117,7 +110,7 @@ module.exports = function testRunner(qb, callback) { id: 5, key: 'gogle', }, (err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); }); @@ -131,7 +124,7 @@ module.exports = function testRunner(qb, callback) { .groupEnd() .limit(2, 1) .get((err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Using where first grouping', done => { @@ -144,7 +137,7 @@ module.exports = function testRunner(qb, callback) { .groupEnd() .limit(2, 1) .get((err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Using or grouping method', done => { @@ -159,7 +152,7 @@ module.exports = function testRunner(qb, callback) { .groupEnd() .limit(2, 1) .get((err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); test('Callback - Using or not grouping method', done => { @@ -174,7 +167,7 @@ module.exports = function testRunner(qb, callback) { .groupEnd() .limit(2, 1) .get((err, rows) => { - return callback(err, done); + return callback(err, rows, done); }); }); }); @@ -184,32 +177,32 @@ module.exports = function testRunner(qb, callback) { .from('create_test') .getCompiledSelect(true); - expect(helpers.isString(sql)).to.be.true; + return expect(helpers.isString(sql)).to.be.true; }); test('select from', () => { let sql = qb.select('id') .getCompiledSelect('create_test', true); - expect(helpers.isString(sql)).to.be.true; + return expect(helpers.isString(sql)).to.be.true; }); test('insert', () => { let sql = qb.set('id', 3) .getCompiledInsert('create_test'); - expect(helpers.isString(sql)).to.be.true; + return expect(helpers.isString(sql)).to.be.true; }); test('update', () => { let sql = qb.set('id', 3) .where('id', 5) .getCompiledUpdate('create_test'); - expect(helpers.isString(sql)).to.be.true; + return expect(helpers.isString(sql)).to.be.true; }); test('delete', () => { let sql = qb.where('id', 5) .getCompiledDelete('create_test'); - expect(helpers.isString(sql)).to.be.true; + return expect(helpers.isString(sql)).to.be.true; }); }); suite('Misc tests -', () => { diff --git a/test/base/adapterPromiseTestRunner.js b/test/base/adapterPromiseTestRunner.js index 4ccc9da..4ee2dc5 100644 --- a/test/base/adapterPromiseTestRunner.js +++ b/test/base/adapterPromiseTestRunner.js @@ -40,7 +40,7 @@ module.exports = function promiseTestRunner(qb) { }); 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 -', () => { suiteSetup(done => { let sql = qb.driver.truncate('create_test'); - qb.adapter.execute(sql).then(res => { - return done(); - }).catch(err => { - return done(err); - }); + qb.query(sql).then(res => done()) + .catch(err => done(err)); }); test('Promise - Test Insert', () => { let promise = qb.set('id', 98) @@ -60,7 +57,7 @@ module.exports = function promiseTestRunner(qb) { .set('val', new Buffer('120')) .insert('create_test'); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test Insert Object', () => { let promise = qb.insert('create_test', { @@ -69,7 +66,7 @@ module.exports = function promiseTestRunner(qb) { val: new Buffer('2'), }); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test Update', () => { let promise = qb.where('id', 7) @@ -79,7 +76,7 @@ module.exports = function promiseTestRunner(qb) { val: new Buffer('non-word'), }); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test set Array Update', () => { let object = { @@ -92,7 +89,7 @@ module.exports = function promiseTestRunner(qb) { .where('id', 22) .update('create_test'); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test where set update', () => { let promise = qb.where('id', 36) @@ -101,17 +98,17 @@ module.exports = function promiseTestRunner(qb) { .set('val', new Buffer('non-word')) .update('create_test'); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Test delete', () => { let promise = qb.delete('create_test', {id: 5}); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Delete with where', () => { let promise = qb.where('id', 5) .delete('create_test'); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Delete multiple where values', () => { let promise = qb.delete('create_test', { @@ -119,7 +116,7 @@ module.exports = function promiseTestRunner(qb) { key: 'gogle', }); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); }); suite('Grouping tests -', () => { @@ -133,7 +130,7 @@ module.exports = function promiseTestRunner(qb) { .limit(2, 1) .get(); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Using where first grouping', () => { let promise = qb.select('id, key as k, val') @@ -146,7 +143,7 @@ module.exports = function promiseTestRunner(qb) { .limit(2, 1) .get(); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Using or grouping method', () => { let promise = qb.select('id, key as k, val') @@ -161,7 +158,7 @@ module.exports = function promiseTestRunner(qb) { .limit(2, 1) .get(); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); test('Promise - Using or not grouping method', () => { let promise = qb.select('id, key as k, val') @@ -176,7 +173,7 @@ module.exports = function promiseTestRunner(qb) { .limit(2, 1) .get(); - expect(promise).to.be.fulfilled; + return expect(promise).to.be.fulfilled; }); }); }; \ No newline at end of file diff --git a/test/base_test.js b/test/base_test.js index 81a4ac1..883813c 100644 --- a/test/base_test.js +++ b/test/base_test.js @@ -3,7 +3,7 @@ let expect = require('chai').expect, reload = require('require-reload')(require), glob = require('glob'), - nodeQuery = reload('../lib/NodeQuery'), + nodeQuery = reload('../lib/NodeQuery')(), Adapter = reload('../lib/Adapter'); suite('Base tests -', () => { @@ -30,7 +30,9 @@ suite('Base tests -', () => { test('Invalid driver type', () => { expect(() => { - nodeQuery.init('foo', {}, 'bar'); + reload('../lib/NodeQuery')({ + driver: 'Foo', + }); }).to.throw(Error, 'Selected driver (Foo) does not exist!'); }); @@ -40,4 +42,11 @@ suite('Base tests -', () => { a.execute(); }).to.throw(Error, 'Correct adapter not defined for query execution'); }); + + test('Invalid adapter - missing transformResult', () => { + expect(() => { + let a = new Adapter(); + a.transformResult([]); + }).to.throw(Error, 'Result transformer method not defined for current adapter'); + }); }); \ No newline at end of file diff --git a/test/config-travis.json b/test/config-travis.json deleted file mode 100644 index 6a6bc62..0000000 --- a/test/config-travis.json +++ /dev/null @@ -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:" - } -} \ No newline at end of file diff --git a/test/config.json b/test/config.json deleted file mode 100644 index 8750235..0000000 --- a/test/config.json +++ /dev/null @@ -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" - } - } -} \ No newline at end of file diff --git a/test/helpers_test.js b/test/helpers_test.js index ae60d5f..2e5a0b6 100644 --- a/test/helpers_test.js +++ b/test/helpers_test.js @@ -148,5 +148,11 @@ suite('Helper Module Tests -', () => { 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'); + }); + }); }); }); diff --git a/test/sql/sqlite.sql b/test/sql/sqlite.sql index b600651..fff3d04 100644 --- a/test/sql/sqlite.sql +++ b/test/sql/sqlite.sql @@ -1,3 +1,3 @@ -- sample data to test SQLite CREATE TABLE IF NOT EXISTS "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT); -CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT); \ No newline at end of file +CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);