All files / lib/drivers Sqlite.js

100% Statements 25/25
100% Branches 0/0
100% Functions 7/7
100% Lines 24/24
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          4x 4x 4x     4x                   4x     3x 3x   3x 3x 6x 6x 18x   6x     3x       3x 3x 3x 9x     3x   3x 18x 6x     3x           4x    
/**
 * Driver for SQLite databases
 *
 * @module drivers/Sqlite
 */
module.exports = (() => {
	delete require.cache[require.resolve('../Driver')];
	const driver = require('../Driver');
 
	// Sqlite doesn't have a truncate command
	driver.hasTruncate = false;
 
	/**
	 * SQL to insert a group of rows
	 * Override default to have better compatibility
	 *
	 * @param {String} table - The table to insert to
	 * @param {Array} [data] - The array of object containing data to insert
	 * @return {String} - The generated sql statement
	 */
	driver.insertBatch = (table, data) => {
		// Get the data values to insert, so they can
		// be parameterized
		let sql = '';
		const first = data.shift();
 
		const vals = [];
		data.forEach(obj => {
			const row = [];
			Object.keys(obj).forEach(key => {
				row.push(obj[key]);
			});
			vals.push(row);
		});
 
		sql += `INSERT INTO ${driver.quoteTable(table)}\n`;
 
		// Get the field names from the keys of the first
		// object to be inserted
		const fields = Object.keys(first);
		const cols = [];
		fields.forEach(key => {
			cols.push(`'${driver._quote(first[key])}' AS ${driver.quoteIdentifiers(key)}`);
		});
 
		sql += `SELECT ${cols.join(', ')}\n`;
 
		vals.forEach(rowValues => {
			const quoted = rowValues.map(value => String(value).replace('\'', '\'\''));
			sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`;
		});
 
		return {
			sql: sql,
			values: undefined
		};
	};
 
	return driver;
})();