No more callbacks in the public interface/New implementation to allow multiple adapters for a database type

This commit is contained in:
Timothy Warren 2016-11-18 21:59:22 -05:00
parent 2e661e24ff
commit d4a8231947
25 changed files with 320 additions and 174 deletions

29
.editorconfig Normal file
View File

@ -0,0 +1,29 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# Matches multiple files with brace expansion notation
# Set default charset
[*]
charset = utf-8
# Tab indentation (no size specified)
[*]
indent_style = tab
indent_size = 4
# Indentation override for all JS under lib directory
[*.js]
indent_size = 2
# Matches the exact files either package.json or .travis.yml
[*.yml]
indent_style = space
indent_size = 2

View File

@ -55,10 +55,8 @@ class NodeQuery {
const driver = require(`./drivers/${drivername}`); const driver = require(`./drivers/${drivername}`);
const Adapter = require(`./adapters/${drivername}`); const Adapter = require(`./adapters/${drivername}`);
let adapter = new Adapter(config.connection); let adapter = Adapter(config);
this.instance = new QueryBuilder(driver, adapter); this.instance = new QueryBuilder(driver, adapter);
} else {
throw new Error('What am I supposed to do without any config options, guess?');
} }
} }

View File

@ -23,8 +23,7 @@ class QueryBuilder extends QueryBuilderBase {
* @return {Promise} - Promise with result of query * @return {Promise} - Promise with result of query
*/ */
query (sql, params) { query (sql, params) {
return this.adapter.execute(sql, params) return this.adapter.execute(sql, params);
.catch(e => console.error(e));
} }
/** /**
@ -546,7 +545,6 @@ class QueryBuilder extends QueryBuilderBase {
* @return {Promise} - If no callback is passed, a promise is returned * @return {Promise} - If no callback is passed, a promise is returned
*/ */
update (table, data) { update (table, data) {
if (data) { if (data) {
this.set(data); this.set(data);
} }

View File

@ -0,0 +1,8 @@
'use strict';
const NodeFirebird = require('./node-firebird');
module.exports = config => {
return new NodeFirebird(config.connection);
};

View File

@ -1,10 +1,10 @@
'use strict'; 'use strict';
const Adapter = require('../Adapter'); const Adapter = require('../../Adapter');
const Result = require('../../Result');
const fb = require('node-firebird'); const fb = require('node-firebird');
class Firebird extends Adapter { class Firebird extends Adapter {
constructor (config) { constructor (config) {
super({}); super({});
this.instance = new Promise((resolve, reject) => { this.instance = new Promise((resolve, reject) => {
@ -13,7 +13,7 @@ class Firebird extends Adapter {
return reject(err); return reject(err);
} }
return resolve(instance) return resolve(instance);
}); });
}); });
} }
@ -33,10 +33,20 @@ class Firebird extends Adapter {
return reject(err); return reject(err);
} }
return resolve(result); return resolve(this.transformResult(result));
})
}); });
}); });
});
}
/**
* 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) {
return new Result(originalResult);
} }
/** /**

View File

@ -1,3 +0,0 @@
'use strict';
module.exports = require('./Mysql');

View File

@ -0,0 +1,3 @@
'use strict';
module.exports = require('../Mysql');

View File

@ -0,0 +1,7 @@
'use strict';
const Mysql2 = require('./mysql2');
module.exports = config => {
return new Mysql2(config.connection);
};

View File

@ -1,9 +1,8 @@
'use strict'; 'use strict';
const Adapter = require('../Adapter'); const Adapter = require('../../Adapter');
const Result = require('../Result'); const Result = require('../../Result');
const helpers = require('../helpers'); const helpers = require('../../helpers');
const getArgs = require('getargs');
const mysql2 = require('mysql2/promise'); const mysql2 = require('mysql2/promise');
class Mysql extends Adapter { class Mysql extends Adapter {
@ -41,12 +40,12 @@ class Mysql extends Adapter {
* *
* @param {String} sql - The sql with placeholders * @param {String} sql - The sql with placeholders
* @param {Array|undefined} params - The values to insert into the query * @param {Array|undefined} params - The values to insert into the query
* @return {Promise} * @return {Promise} Result of query
*/ */
execute (sql, params) { execute (sql, params) {
return this.instance.then(conn => { return this.instance
return conn.execute(sql, params); .then(conn => conn.execute(sql, params))
}).then(result => this.transformResult(result)); .then(result => this.transformResult(result));
} }
} }

View File

@ -1,13 +1,12 @@
'use strict'; 'use strict';
const Adapter = require('../Adapter'); const Adapter = require('../../Adapter');
const Result = require('../Result'); const Result = require('../../Result');
const helpers = require('../helpers'); const helpers = require('../../helpers');
const pg = require('pg'); const pg = require('pg');
const url = require('url'); const url = require('url');
class Pg extends Adapter { class Pg extends Adapter {
constructor (config) { constructor (config) {
let instance = null; let instance = null;
let connectionString = ''; let connectionString = '';
@ -71,7 +70,6 @@ class Pg extends Adapter {
* @return {void|Promise} - Returns a promise if no callback is provided * @return {void|Promise} - Returns a promise if no callback is provided
*/ */
execute (sql, params) { execute (sql, params) {
// Replace question marks with numbered placeholders, because this adapter is different... // Replace question marks with numbered placeholders, because this adapter is different...
let count = 0; let count = 0;
sql = sql.replace(/\?/g, () => { sql = sql.replace(/\?/g, () => {

7
lib/adapters/Pg/index.js Normal file
View File

@ -0,0 +1,7 @@
'use strict';
const Pg = require('./pg');
module.exports = config => {
return new Pg(config.connection);
};

View File

@ -0,0 +1,67 @@
'use strict';
const Adapter = require('../../Adapter');
const Result = require('../../Result');
const helpers = require('../../helpers');
const dbliteAdapter = require('dblite');
class SqliteDblite extends Adapter {
constructor (config) {
let file = (helpers.isString(config)) ? config : config.file;
const instance = new Promise((resolve, reject) => {
let conn = dbliteAdapter(file);
// Stop the stupid 'bye bye' message being output
conn.on('close', () => {});
conn.on('error', err => {
reject(err);
});
// Make sure to actually pass on the connection!
return resolve(conn);
});
super(instance);
}
/**
* 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
* @return {Promise} - Returns a promise if no callback is provided
*/
execute (sql, params) {
return this.instance.then(conn => new Promise((resolve, reject) => {
return conn.query(sql, params, (err, rows) => {
if (err) {
return reject(err);
}
return resolve(this.transformResult(rows));
});
}));
}
/**
* 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) {
return new Result(originalResult);
}
/**
* Close the current database connection
*
* @return {void}
*/
close () {
this.instance.then(conn => conn.close());
}
}
module.exports = SqliteDblite;

View File

@ -0,0 +1,10 @@
'use strict';
module.exports = config => {
const Implementation = (config.adapter && config.adapter === 'dblite')
? require('./dblite')
: require('./sqlite3');
return new Implementation(config.connection);
};

View File

@ -1,25 +1,23 @@
'use strict'; 'use strict';
const Adapter = require('../Adapter'); const Adapter = require('../../Adapter');
const Result = require('../Result'); const Result = require('../../Result');
const helpers = require('../helpers'); const helpers = require('../../helpers');
const dbliteAdapter = require('dblite'); const sqlite3 = require('sqlite3').verbose();
class Sqlite extends Adapter { class SqliteSqlite3 extends Adapter {
constructor (config) { constructor (config) {
let file = (helpers.isString(config)) ? config : config.file; let file = (helpers.isString(config)) ? config : config.file;
const instance = Promise.resolve(dbliteAdapter(file)).then(conn => { const instance = new Promise((resolve, reject) => {
// Stop the stupid 'bye bye' message being output let conn = new sqlite3.Database(file, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, err => {
conn.on('close', () => {}); if (err) {
reject(err);
conn.on('error', (err) => { }
throw new Error(err);
}); });
// Make sure to actually pass on the connection! conn.on('open', resolve(conn));
return conn; });
}).catch(e => console.error(e));
super(instance); super(instance);
} }
@ -42,15 +40,14 @@ class Sqlite extends Adapter {
* @return {Promise} - Returns a promise if no callback is provided * @return {Promise} - Returns a promise if no callback is provided
*/ */
execute (sql, params) { execute (sql, params) {
return this.instance.then(conn => new Promise((resolve, reject) => {
return this.instance.then(conn => { conn.all(sql, params, (err, rows) => {
return conn.query(sql, params, (err, result) => {
if (err) { if (err) {
throw new Error(err); return reject(err);
} }
return Promise.resolve(this.instance).then(() => result); return resolve(this.transformResult(rows));
});
}); });
}));
} }
/** /**
@ -63,4 +60,4 @@ class Sqlite extends Adapter {
} }
} }
module.exports = Sqlite; module.exports = SqliteSqlite3;

View File

@ -24,8 +24,7 @@ module.exports = (() => {
driver.limit = (origSql, limit, offset) => { driver.limit = (origSql, limit, offset) => {
let sql = `FIRST ${limit}`; let sql = `FIRST ${limit}`;
if (helpers.isNumber(offset)) if (helpers.isNumber(offset)) {
{
sql += ` SKIP ${offset}`; sql += ` SKIP ${offset}`;
} }

View File

@ -54,7 +54,7 @@ module.exports = (() => {
return { return {
sql: sql, sql: sql,
values: null values: undefined
}; };
}; };

View File

@ -42,6 +42,7 @@
"node-firebird": "^0.7.5", "node-firebird": "^0.7.5",
"pg": "^6.0.0", "pg": "^6.0.0",
"require-reload": "~0.2.2", "require-reload": "~0.2.2",
"sqlite3": "^3.1.8",
"xregexp": "^3.0.0" "xregexp": "^3.0.0"
}, },
"devDependencies": { "devDependencies": {

View File

@ -0,0 +1,38 @@
/* eslint-env node, mocha */
'use strict';
// Load the test base
const path = require('path');
const reload = require('require-reload')(require);
const testBase = reload('../base');
const expect = testBase.expect;
const testRunner = testBase.promiseTestRunner;
// Skip on CI
if (!(process.env.CI || process.env.TRAVIS)) {
// Load the test config file
let adapterName = 'node-firebird';
const config = reload('../config.json')[adapterName];
config.connection.database = path.join(__dirname, config.connection.database);
let nodeQuery = reload('../../lib/NodeQuery')(config);
let qb = nodeQuery.getQuery();
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');
});
testRunner(qb);
suiteTeardown(() => {
qb.end();
});
});
}

View File

@ -4,11 +4,9 @@
// Load the test base // Load the test base
const reload = require('require-reload')(require); const reload = require('require-reload')(require);
reload.emptyCache(); reload.emptyCache();
const fs = require('fs');
const testBase = reload('../base'); const testBase = reload('../base');
const expect = testBase.expect; const expect = testBase.expect;
const testRunner = testBase.promiseTestRunner; const testRunner = testBase.promiseTestRunner;
// let tests = reload('../base/tests');
// Load the test config file // Load the test config file
const config = testBase.config; const config = testBase.config;
@ -20,33 +18,16 @@ let qb = nodeQuery.getQuery();
suite('Dblite adapter tests -', () => { suite('Dblite adapter tests -', () => {
suiteSetup(done => { suiteSetup(done => {
// Set up the sqlite database // Set up the sqlite database
fs.readFile(`${__dirname}/../sql/sqlite.sql`, 'utf8', (err, data) => { const createTest = 'CREATE TABLE IF NOT EXISTS "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);';
if (err) { const createJoin = 'CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);';
return done(err);
}
qb.query(data) qb.query(createTest)
.then(() => done) .then(() => qb.query(createJoin))
.catch(e => done(e)); .then(() => {
return done();
}); });
}); });
// ---------------------------------------------------------------------------
// 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();
}); */
// ---------------------------------------------------------------------------
// Promise Tests
// ---------------------------------------------------------------------------
testRunner(qb); testRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => { test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id') let promise = qb.select('id')

View File

@ -22,21 +22,6 @@ suite('Mysql2 adapter tests -', () => {
.to.be.deep.equal(qb); .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();
}); */
// ---------------------------------------------------------------------------
// Promise Tests
// ---------------------------------------------------------------------------
testRunner(qb); testRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => { test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id') let promise = qb.select('id')
@ -70,7 +55,7 @@ suite('Mysql2 adapter tests -', () => {
return expect(qb.insertBatch('create_test', data)).to.be.fulfilled; return expect(qb.insertBatch('create_test', data)).to.be.fulfilled;
}); });
suiteTeardown(() => { /* suiteTeardown(() => {
qb.end(); qb.end();
}); }); */
}); });

View File

@ -1,40 +0,0 @@
'use strict';
// Load the test base
const path = require('path');
const reload = require('require-reload')(require);
const testBase = reload('../base');
const expect = testBase.expect;
const testRunner = testBase.promiseTestRunner;
// Skip on CI
if (process.env.CI || process.env.TRAVIS) {
return;
}
// Load the test config file
let adapterName = 'node-firebird';
let Firebird = reload(adapterName);
const config = reload('../config.json')[adapterName];
config.connection.database = path.join(__dirname, config.connection.database);
let nodeQuery = reload('../../lib/NodeQuery')(config);
let qb = nodeQuery.getQuery();
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');
});
testRunner(qb);
suiteTeardown(() => {
qb.end();
});
});

View File

@ -43,20 +43,6 @@ suite('Pg adapter tests -', () => {
} }
}); });
// --------------------------------------------------------------------------
// 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();
}); */
// --------------------------------------------------------------------------
// Promise Tests
// --------------------------------------------------------------------------
testRunner(qb); testRunner(qb);
test('Promise - Select with function and argument in WHERE clause', () => { test('Promise - Select with function and argument in WHERE clause', () => {
let promise = qb.select('id') let promise = qb.select('id')

View File

@ -0,0 +1,63 @@
/* eslint-env node, mocha */
'use strict';
// Load the test base
const reload = require('require-reload')(require);
reload.emptyCache();
const testBase = reload('../base');
const expect = testBase.expect;
const testRunner = testBase.promiseTestRunner;
// Load the test config file
const config = testBase.config;
// Set up the query builder object
let nodeQuery = require('../../lib/NodeQuery')(config.sqlite3);
let qb = nodeQuery.getQuery();
suite('Sqlite3 adapter tests -', () => {
suiteSetup(done => {
// Set up the sqlite database
const createTest = 'CREATE TABLE IF NOT EXISTS "create_test" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);';
const createJoin = 'CREATE TABLE IF NOT EXISTS "create_join" ("id" INTEGER PRIMARY KEY, "key" TEXT, "val" TEXT);';
qb.query(createTest)
.then(() => qb.query(createJoin))
.then(() => {
return done();
});
});
testRunner(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: Buffer.from('7')
}, {
id: 89,
key: 34,
val: Buffer.from('10 o\'clock')
}, {
id: 48,
key: 403,
val: Buffer.from('97')
}
];
let promise = qb.insertBatch('create_test', data);
expect(promise).to.be.fulfilled;
});
suiteTeardown(() => {
qb.end();
});
});

View File

@ -15,7 +15,7 @@ module.exports = function promiseTestRunner (qb) {
suite(suiteName, () => { suite(suiteName, () => {
let currentSuite = tests[suiteName]; let currentSuite = tests[suiteName];
Object.keys(currentSuite).forEach(testDesc => { Object.keys(currentSuite).forEach(testDesc => {
test(testDesc, () => { test(testDesc, done => {
const methodObj = currentSuite[testDesc]; const methodObj = currentSuite[testDesc];
const methodNames = Object.keys(methodObj); const methodNames = Object.keys(methodObj);
let results = []; let results = [];
@ -35,7 +35,12 @@ module.exports = function promiseTestRunner (qb) {
}); });
let promise = results.pop(); let promise = results.pop();
return expect(promise).to.be.fulfilled; promise.then(result => {
expect(result.rows).is.an('array');
expect(result.rowCount()).to.not.be.undefined;
expect(result.columnCount()).to.not.be.undefined;
return done();
}).catch(e => done(e));
}); });
}); });
}); });