node-query/lib/drivers/Sqlite.js

61 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

/**
* Driver for SQLite databases
*
* @module drivers/Sqlite
*/
2016-02-12 12:50:59 -05:00
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
2015-12-07 15:58:31 -05:00
* @return {String} - The generated sql statement
*/
2016-02-12 12:50:59 -05:00
driver.insertBatch = (table, data) => {
// Get the data values to insert, so they can
// be parameterized
let sql = '';
const first = data.shift();
const vals = [];
2015-12-07 15:58:31 -05:00
data.forEach(obj => {
const row = [];
2015-12-07 15:58:31 -05:00
Object.keys(obj).forEach(key => {
row.push(obj[key]);
});
vals.push(row);
});
2015-12-07 15:58:31 -05:00
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 = [];
2015-12-08 10:40:52 -05:00
fields.forEach(key => {
2015-12-07 15:58:31 -05:00
cols.push(`'${driver._quote(first[key])}' AS ${driver.quoteIdentifiers(key)}`);
});
2015-12-07 15:58:31 -05:00
sql += `SELECT ${cols.join(', ')}\n`;
2015-12-07 17:03:36 -05:00
vals.forEach(rowValues => {
const quoted = rowValues.map(value => String(value).replace('\'', '\'\''));
2015-12-07 17:03:36 -05:00
sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`;
});
return {
sql: sql,
values: undefined
};
2015-12-07 17:03:36 -05:00
};
return driver;
})();