node-query/lib/drivers/Sqlite.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-12-07 17:03:36 -05:00
'use strict';
/**
* Driver for Sqlite databases
*
* @module drivers/sqlite
*/
2016-02-12 12:50:59 -05:00
module.exports = (() => {
delete require.cache[require.resolve('../Driver')];
2015-12-08 10:40:52 -05:00
let 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
2015-12-07 17:03:36 -05:00
let sql = '',
vals = [],
cols = [],
fields = [],
2015-12-08 10:40:52 -05:00
first = data.shift();
2015-12-07 15:58:31 -05:00
data.forEach(obj => {
2015-12-07 12:03:42 -05:00
let 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
fields = Object.keys(first);
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 => {
let 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,
2015-12-07 17:03:36 -05:00
values: null,
};
2015-12-07 17:03:36 -05:00
};
return driver;
2016-02-12 12:50:59 -05:00
})();