All files / lib NodeQuery.js

100% Statements 15/15
100% Branches 6/6
100% Functions 3/3
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 845x     5x                                                                                                 8x   8x 7x   7x 2x     5x 5x   5x                   7x 1x     6x       8x  
const QueryBuilder = require('./QueryBuilder');
 
// Map config driver name to code class name
const dbDriverMap = new Map([
	['bettersqlite', 'Sqlite'],
	['better-sqlite', 'Sqlite'],
	['better-sqlite3', 'Sqlite'],
	['my', 'Mysql'],
	['mysql', 'Mysql'],
	['maria', 'Mysql'],
	['mariadb', 'Mysql'],
	['firebird', 'Firebird'],
	['postgresql', 'Pg'],
	['postgres', 'Pg'],
	['pg', 'Pg'],
	['sqlite3', 'Sqlite'],
	['sqlite', 'Sqlite'],
	['sqlserver', 'MSSQLServer'],
	['mssql', 'MSSQLServer']
]);
 
/**
 * Class for connection management
 *
 * @param {object} config - connection parameters
 */
class NodeQuery {
	/**
	 * Constructor
	 *
	 * @param {object} config - connection parameters
	 * @param {string} config.driver - the database driver to use, such as mysql, sqlite, mssql, or pgsql
	 * @param {object|string} config.connection - the connection options for the database
	 * @param {string} config.connection.host - the ip or hostname of the database server
	 * @param {string} config.connection.user - the user to log in as
	 * @param {string} config.connection.password - the password to log in with
	 * @param {string} config.connection.database - the name of the database to connect to
	 * @example let nodeQuery = require('ci-node-query')({
	 * 	driver: 'mysql',
	 * 	connection: {
	 * 		host: 'localhost',
	 * 		user: 'root',
	 * 		password: '',
	 * 		database: 'mysql'
	 * 	}
	 * });
	 * @example let nodeQuery = require('ci-node-query')({
	 * 	driver: 'sqlite',
	 * 	connection: ':memory:'
	 * });
	 */
	constructor (config) {
		this.instance = null;
 
		if (config !== undefined) {
			const driverName = dbDriverMap.get(config.driver);
 
			if (!driverName) {
				throw new Error(`Selected driver (${config.driver}) does not exist!`);
			}
 
			const driver = require(`./drivers/${driverName}`);
			const Adapter = require(`./adapters/${driverName}`);
 
			this.instance = new QueryBuilder(driver, Adapter(config));
		}
	}
 
	/**
	 * Return an existing query builder instance
	 *
	 * @return {QueryBuilder} - The Query Builder object
	 */
	getQuery () {
		if (this.instance == null) {
			throw new Error('No Query Builder instance to return');
		}
 
		return this.instance;
	}
}
 
module.exports = config => new NodeQuery(config);