Socket
Socket
Sign inDemoInstall

better-sqlite3

Package Overview
Dependencies
Maintainers
1
Versions
129
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

better-sqlite3 - npm Package Compare versions

Comparing version 4.0.3 to 4.1.0

deps/sqlite-autoconf-3210000.tar.gz

103

benchmark/factory.js
'use strict';
var dbs = require('./implementations')();
var rows = 1000;
const dbs = require('./implementations')();
const rows = 1000;
exports.buildTables = function () {
return createTables([
const buildTables = () => createTables([
'allSmall (integer INTEGER, real REAL, text TEXT, blob BLOB, nul)',

@@ -15,38 +14,38 @@ 'allLarge (text TEXT, blob BLOB)',

'textLarge (text TEXT)',
'blobLarge (blob BLOB)'
]).then(function () {
return fillTable('allSmall', getFakeData('small', ['integer', 'real', 'text', 'blob', 'nul']));
}).then(function () {
return fillTable('allLarge', getFakeData('large', ['text', 'blob']));
});
};
exports.params = params;
'blobLarge (blob BLOB)',
])
.then(() => fillTable('allSmall', getFakeData('small', ['integer', 'real', 'text', 'blob', 'nul'])))
.then(() => fillTable('allLarge', getFakeData('large', ['text', 'blob'])));
function createTables(strings) {
return strings.reduce(function (promise, SQL) {
return promise.then(function () {return createTable(SQL);});
}, Promise.resolve());
}
const createTables = strings => strings
.reduce((previous, SQL) => previous.then(() => createTable(SQL)), Promise.resolve());
function createTable(SQL) {
return dbs.each('connect').then(function () {
return dbs.each('run', 'CREATE TABLE ' + SQL);
}).then(function () {return dbs.each('close');});
}
const createTable = SQL => dbs.each('connect')
.then(() => dbs.each('run', `CREATE TABLE ${SQL}`))
.then(() => dbs.each('close'));
function fillTable(table, values) {
var i = 0;
var SQL = 'INSERT INTO ' + table + ' VALUES ' + params(values.length);
return dbs.each('connect').then(function () {
return dbs.each('run', 'BEGIN').then(function insert() {
if (++i < rows) {
return dbs.each('run', SQL, values).then(insert);
}
return dbs.each('run', SQL, values).then(function () {return dbs.each('run', 'COMMIT');});
});
}).then(function () {return dbs.each('close');});
}
const fillTable = (table, values) => {
const SQL = `INSERT INTO ${table} VALUES ${params(values.length)}`;
let i = 0;
return dbs.each('connect')
.then(() => dbs.each('run', 'BEGIN')
.then(function insert() {
if (++i < rows) return dbs.each('run', SQL, values).then(insert);
return dbs.each('run', SQL, values).then(() => dbs.each('run', 'COMMIT'));
}))
.then(() => dbs.each('close'));
};
var getFakeData = (function () {
var smallData = {
const bufferOf = (str, size) => {
let bytesWritten = 0;
const source = Buffer.from(String(str));
const result = Buffer.allocUnsafe(size >>> 0);
while (bytesWritten < size) {
bytesWritten += source.copy(result, bytesWritten, 0, Math.min(source.length, size - bytesWritten));
}
return result;
};
const getFakeData = (() => {
const smallData = {
integer: 12345,

@@ -56,35 +55,23 @@ real: 0.12345,

blob: Buffer.from('John Peter Smith'),
nul: null
nul: null,
};
var largeData = {
const largeData = {
text: bufferOf('John Peter Smith', 1024 * 100).toString(),
blob: bufferOf('John Peter Smith', 1024 * 100)
blob: bufferOf('John Peter Smith', 1024 * 100),
};
function getColumn(column) {
if (!this.hasOwnProperty(column)) {
var table = this === largeData ? 'large' : 'small';
throw new TypeError('No data defined for column "' + table + '.' + column + '"');
const table = this === largeData ? 'large' : 'small';
throw new TypeError(`No data defined for column "${table}.${column}"`);
}
return this[column];
}
return function (size, columns) {
var isLarge = size.toLowerCase().indexOf('large') !== -1;
return (size, columns) => {
const isLarge = size.toLowerCase().includes('large');
return columns.map(getColumn, isLarge ? largeData : smallData);
};
}());
})();
function bufferOf(str, size) {
var bytesWritten = 0;
var source = Buffer.from(String(str));
var result = Buffer.allocUnsafe(size >>> 0);
while (bytesWritten < size) {
bytesWritten += source.copy(result, bytesWritten, 0, Math.min(source.length, size - bytesWritten));
}
return result;
}
const params = count => `(${new Array(count >>> 0).fill('?').join(', ')})`;
function params(count) {
return '(' + new Array(count >>> 0).fill('?').join(', ') + ')';
}
module.exports = Object.assign(getFakeData, exports);
module.exports = Object.assign(getFakeData, { buildTables, params });
'use strict';
var path = require('path');
var slice = Array.prototype.slice;
var concat = Array.prototype.concat;
const path = require('path');
var implementations = {
const implementations = {
'better-sqlite3': {
connect: function () {return new (require('../.'))(path.join('temp', 'better-sqlite3.db'));},
close: function () {return this.close();},
run: function (SQL) {return this.prepare(SQL).run(concat.apply([], slice.call(arguments, 1)));}
connect: () => new (require('../.'))(path.join('temp', 'better-sqlite3.db')),
close: function () { return this.close(); },
run: function (SQL, ...args) { return this.prepare(SQL).run([].concat(...args)); },
},
'node-sqlite3': {
connect: function () {return require('sqlite').open(path.join('temp', 'node-sqlite3.db'), {Promise: Promise});},
close: function () {return this.close();},
run: function (SQL) {return this.run.apply(this, concat.apply([SQL], slice.call(arguments, 1)));}
}
connect: () => require('sqlite').open(path.join('temp', 'node-sqlite3.db'), { Promise }),
close: function () { return this.close(); },
run: function (SQL, ...args) { return this.run(...[SQL].concat(...args)); },
},
};
module.exports = function () {
var prototype = Object.create(null);
var promiseTry = function (fn, ctx, args) {
try {return Promise.resolve(fn.apply(ctx, args));}
catch (ex) {return Promise.reject(ex);}
module.exports = () => {
const prototype = Object.create(null);
const promiseTry = (fn, ctx, args) => {
try { return Promise.resolve(fn.apply(ctx, args)); }
catch (ex) { return Promise.reject(ex); }
};
prototype.each = function (action) {
var controller = this;
var args = slice.call(arguments, 1);
return Promise.all(Object.keys(implementations).map(function (key) {
if (action === 'connect') {
var after = function (result) {controller[key] = result;};
}
return promiseTry(implementations[key][action], controller[key], args).then(after);
})).then(function () {});
prototype.each = function (action, ...args) {
return Promise.all(Object.keys(implementations).map((key) => {
const promise = promiseTry(implementations[key][action], this[key], args);
if (action === 'connect') return promise.then((result) => { this[key] = result; });
return promise;
})).then(() => undefined);
};
return Object.create(prototype);
};
'use strict';
var path = require('path');
var fs = require('fs-extra');
var clc = require('cli-color');
var spawn = require('child_process').spawn;
var factory = require('./factory');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs-extra');
const clc = require('cli-color');
const factory = require('./factory');
process.chdir(path.dirname(__dirname));

@@ -11,3 +12,3 @@ process.on('SIGINT', exit);

process.on('SIGTERM', exit);
var trials;
let trials;

@@ -25,6 +26,6 @@ (function init() {

console.log('Generating tables...');
factory.buildTables().then(function () {
factory.buildTables().then(() => {
console.log(clc.magenta('--- Benchmarks ---'));
nextTrial();
}, function (err) {
}, (err) => {
console.log(clc.red(err && err.stack || err));

@@ -36,9 +37,12 @@ exit(1);

function getTrials() {
if (process.argv.length === 2) {return require('./trials').default.map(addSearchTerms);}
// Without any command-line arguments, we do a general-purpose benchmark.
if (process.argv.length === 2) return require('./trials').default.map(addSearchTerms);
// With command-line arguments, the user can run specific groups of trials.
return process.argv.slice(2).reduce(filterByArgs, require('./trials').searchable.map(addSearchTerms));
function addSearchTerms(trial) {
var size = trial.table.toLowerCase().indexOf('large') === -1 ? 'small' : 'large';
var columns = trial.columns.join(',').toLowerCase();
if (trial.columns.length > 1) {columns = '(' + columns + ')';}
const size = trial.table.toLowerCase().includes('large') ? 'large' : 'small';
let columns = trial.columns.join(',').toLowerCase();
if (trial.columns.length > 1) columns = `(${columns})`;
trial.terms = [trial.type.toLowerCase(), size, columns];

@@ -50,10 +54,8 @@ trial.looseTerms = (trial.pragma || []).filter(customPragma).join('; ').toLowerCase();

arg = arg.toLowerCase();
return trials.filter(function (obj) {
return obj.terms.indexOf(arg) !== -1 || obj.looseTerms.indexOf(arg) !== -1;
});
return trials.filter(obj => obj.terms.includes(arg) || obj.looseTerms.includes(arg));
}
function customPragma(str) {
return str.indexOf('cache_size') === -1 && str.indexOf('synchronous') === -1;
return !str.includes('cache_size') && !str.includes('synchronous');
}
}
};

@@ -71,13 +73,13 @@ function exit(code) {

var trial = trials.shift();
var extraName = trial.looseTerms ? clc.yellow(' | ' + trial.looseTerms) : '';
// Consume the next trial and display its name.
const trial = trials.shift();
const extraName = trial.looseTerms ? clc.yellow(` | ${trial.looseTerms}`) : '';
console.log(clc.cyan(trial.terms.join(' ')) + extraName);
var child = spawn('node', [path.join(__dirname, 'types', trial.type), JSON.stringify(trial)], {stdio: 'inherit'});
child.on('exit', function (code) {
if (code !== 0) {
console.log(clc.red('ERROR (probably out of memory)'));
}
// Spawn each trial within its own process.
const child = spawn('node', [path.join(__dirname, 'types', trial.type), JSON.stringify(trial)], { stdio: 'inherit' });
child.on('exit', (code) => {
if (code !== 0) console.log(clc.red('ERROR (probably out of memory)'));
setTimeout(nextTrial, 0);
});
}
'use strict';
var Benchmark = require('benchmark');
var dbs = require('./implementations')();
const Benchmark = require('benchmark');
const dbs = require('./implementations')();
const trial = JSON.parse(process.argv[2]);
module.exports = function (callback) {
var trial = JSON.parse(process.argv[2]);
var suite = new Benchmark.Suite;
var addBenchmark = suite.add;
module.exports = (callback, multiplier = 1) => {
// Setup the benchmark suite.
const suite = new Benchmark.Suite;
const addBenchmark = suite.add;
suite.add = function (name, fn) {
var options = {maxTime: 0.5};
if (fn.length !== 0) {options.defer = true;}
const options = { maxTime: 0.5, defer: fn.length !== 0 };
return addBenchmark.call(this, pad(name, 14), fn, options);
};
suite.on('cycle', function (ev) {
suite.on('cycle', (ev) => {
ev.target.hz *= multiplier;
console.log(String(ev.target));
});
dbs.each('connect').then(function () {
return runPragmas(trial.pragma || []);
}).then(function () {
suite.on('complete', function () {dbs.each('close');});
setImmediate(function () {
callback(suite, dbs, trial);
suite.run({async: true});
// Run this process' trial within the benchmark suite.
dbs.each('connect')
.then(() => runPragmas(trial.pragma || []))
.then(() => {
suite.on('complete', () => void dbs.each('close'));
setImmediate(() => {
callback(suite, dbs, trial); // Load trial to bootstrap benchmarks
suite.run({ async: true });
});
}, (err) => {
console.log(err && err.stack || err);
process.exit(1);
});
}, function (err) {
console.log(err && err.stack || err);
process.exit(1);
});
};
function runPragmas(strings) {
return strings.reduce(function (promise, SQL) {
return promise.then(function () {return dbs.each('run', 'PRAGMA ' + SQL);});
}, Promise.resolve());
}
const runPragmas = strings => strings
.reduce((previous, SQL) => previous.then(() => dbs.each('run', `PRAGMA ${SQL}`)), Promise.resolve());
function pad(str, length) {
while (str.length < length) {str = str + ' ';}
const pad = (str, length) => {
while (str.length < length) str = str + ' ';
return str;
}
};
'use strict';
exports.default = [
{type: 'select', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul']},
{type: 'select-all', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul']},
{type: 'select-iterate', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul']},
{type: 'insert', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'transaction', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul']},
{type: 'real-world', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'real-world', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2']}
{ type: 'select', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'] },
{ type: 'select-all', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'] },
{ type: 'insert', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'transaction', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'] },
{ type: 'real-world', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'real-world', table: 'allSmall', columns: ['integer', 'real', 'text', 'nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
];
exports.searchable = [
{type: 'select', table: 'allSmall', columns: ['integer']},
{type: 'select', table: 'allSmall', columns: ['real']},
{type: 'select', table: 'allSmall', columns: ['text']},
{type: 'select', table: 'allSmall', columns: ['blob']},
{type: 'select', table: 'allSmall', columns: ['nul']},
{type: 'select', table: 'allLarge', columns: ['text']},
{type: 'select', table: 'allLarge', columns: ['blob']},
{type: 'select-all', table: 'allSmall', columns: ['integer']},
{type: 'select-all', table: 'allSmall', columns: ['real']},
{type: 'select-all', table: 'allSmall', columns: ['text']},
{type: 'select-all', table: 'allSmall', columns: ['blob']},
{type: 'select-all', table: 'allSmall', columns: ['nul']},
{type: 'select-all', table: 'allLarge', columns: ['text']},
{type: 'select-all', table: 'allLarge', columns: ['blob']},
{type: 'select-iterate', table: 'allSmall', columns: ['integer']},
{type: 'select-iterate', table: 'allSmall', columns: ['real']},
{type: 'select-iterate', table: 'allSmall', columns: ['text']},
{type: 'select-iterate', table: 'allSmall', columns: ['blob']},
{type: 'select-iterate', table: 'allSmall', columns: ['nul']},
{type: 'select-iterate', table: 'allLarge', columns: ['text']},
{type: 'select-iterate', table: 'allLarge', columns: ['blob']},
{type: 'insert', table: 'integerSmall', columns: ['integer'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'realSmall', columns: ['real'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'textSmall', columns: ['text'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'blobSmall', columns: ['blob'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'nulSmall', columns: ['nul'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'textLarge', columns: ['text'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'blobLarge', columns: ['blob'], pragma: ['journal_mode = WAL', 'synchronous = 1']},
{type: 'insert', table: 'integerSmall', columns: ['integer'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'realSmall', columns: ['real'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'textSmall', columns: ['text'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'blobSmall', columns: ['blob'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'nulSmall', columns: ['nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'textLarge', columns: ['text'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'insert', table: 'blobLarge', columns: ['blob'], pragma: ['journal_mode = DELETE', 'synchronous = 2']},
{type: 'transaction', table: 'integerSmall', columns: ['integer']},
{type: 'transaction', table: 'realSmall', columns: ['real']},
{type: 'transaction', table: 'textSmall', columns: ['text']},
{type: 'transaction', table: 'blobSmall', columns: ['blob']},
{type: 'transaction', table: 'nulSmall', columns: ['nul']},
{type: 'transaction', table: 'textLarge', columns: ['text']},
{type: 'transaction', table: 'blobLarge', columns: ['blob']}
{ type: 'select', table: 'allSmall', columns: ['integer'] },
{ type: 'select', table: 'allSmall', columns: ['real'] },
{ type: 'select', table: 'allSmall', columns: ['text'] },
{ type: 'select', table: 'allSmall', columns: ['blob'] },
{ type: 'select', table: 'allSmall', columns: ['nul'] },
{ type: 'select', table: 'allLarge', columns: ['text'] },
{ type: 'select', table: 'allLarge', columns: ['blob'] },
{ type: 'select-all', table: 'allSmall', columns: ['integer'] },
{ type: 'select-all', table: 'allSmall', columns: ['real'] },
{ type: 'select-all', table: 'allSmall', columns: ['text'] },
{ type: 'select-all', table: 'allSmall', columns: ['blob'] },
{ type: 'select-all', table: 'allSmall', columns: ['nul'] },
{ type: 'select-all', table: 'allLarge', columns: ['text'] },
{ type: 'select-all', table: 'allLarge', columns: ['blob'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['integer'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['real'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['text'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['blob'] },
{ type: 'select-iterate', table: 'allSmall', columns: ['nul'] },
{ type: 'select-iterate', table: 'allLarge', columns: ['text'] },
{ type: 'select-iterate', table: 'allLarge', columns: ['blob'] },
{ type: 'insert', table: 'integerSmall', columns: ['integer'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'realSmall', columns: ['real'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'textSmall', columns: ['text'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'blobSmall', columns: ['blob'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'nulSmall', columns: ['nul'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'textLarge', columns: ['text'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'blobLarge', columns: ['blob'], pragma: ['journal_mode = WAL', 'synchronous = 1'] },
{ type: 'insert', table: 'integerSmall', columns: ['integer'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'realSmall', columns: ['real'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'textSmall', columns: ['text'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'blobSmall', columns: ['blob'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'nulSmall', columns: ['nul'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'textLarge', columns: ['text'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'insert', table: 'blobLarge', columns: ['blob'], pragma: ['journal_mode = DELETE', 'synchronous = 2'] },
{ type: 'transaction', table: 'integerSmall', columns: ['integer'] },
{ type: 'transaction', table: 'realSmall', columns: ['real'] },
{ type: 'transaction', table: 'textSmall', columns: ['text'] },
{ type: 'transaction', table: 'blobSmall', columns: ['blob'] },
{ type: 'transaction', table: 'nulSmall', columns: ['nul'] },
{ type: 'transaction', table: 'textLarge', columns: ['text'] },
{ type: 'transaction', table: 'blobLarge', columns: ['blob'] },
];
(function () {
var cacheSize = /^(1|true|on|yes)$/i.test(process.env.NO_CACHE) ? 'cache_size = 0' : 'cache_size = -16000';
var trials = [].concat.apply([], Object.keys(exports).map(function (key) {return exports[key];}));
trials.forEach(function (trial) {
(() => {
const cacheSize = /^(1|true|on|yes)$/i.test(process.env.NO_CACHE) ? 'cache_size = 0' : 'cache_size = -16000';
const trials = [].concat(...Object.keys(exports).map(key => exports[key]));
for (const trial of trials) {
trial.pragma = [cacheSize].concat(trial.pragma || []);
});
}());
}
})();
'use strict';
// Inserts 1 row
require('../runner')(function (benchmark, dbs, ctx) {
var factory = require('../factory');
var SQL = 'INSERT INTO ' + ctx.table + ' (' + ctx.columns.join(', ') + ') VALUES ' + factory.params(ctx.columns.length);
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var data = factory(ctx.table, ctx.columns);
require('../runner')((benchmark, dbs, ctx) => {
const factory = require('../factory');
const SQL = `INSERT INTO ${ctx.table} (${ctx.columns.join(', ')}) VALUES ${factory.params(ctx.columns.length)}`;
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
const data = factory(ctx.table, ctx.columns);
var betterSqlite3Insert = betterSqlite3.prepare(SQL);
const betterSqlite3Insert = betterSqlite3.prepare(SQL);
benchmark.add('better-sqlite3', function () {
benchmark.add('better-sqlite3', () => {
betterSqlite3Insert.run(data);
});
benchmark.add('node-sqlite3', function (deferred) {
nodeSqlite3.run(SQL, data).then(function () {deferred.resolve();});
benchmark.add('node-sqlite3', (deferred) => {
nodeSqlite3.run(SQL, data).then(() => void deferred.resolve());
});
});
'use strict';
// Concurrently reads and writes single rows
require('../runner')(function (benchmark, dbs, ctx) {
var factory = require('../factory');
var SELECT = 'SELECT ' + ctx.columns.join(', ') + ' FROM ' + ctx.table + ' WHERE rowid=?';
var INSERT = 'INSERT INTO ' + ctx.table + ' (' + ctx.columns.join(', ') + ') VALUES ' + factory.params(ctx.columns.length);
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var data = factory(ctx.table, ctx.columns);
var rowid = 0;
benchmark.on('cycle', function () {rowid = 0;});
require('../runner')((benchmark, dbs, ctx) => {
const factory = require('../factory');
const SELECT = `SELECT ${ctx.columns.join(', ')} FROM ${ctx.table} WHERE rowid=?`;
const INSERT = `INSERT INTO ${ctx.table} (${ctx.columns.join(', ')}) VALUES ${factory.params(ctx.columns.length)}`;
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
const data = factory(ctx.table, ctx.columns);
let rowid = 0;
var betterSqlite3Select = betterSqlite3.prepare(SELECT);
var betterSqlite3Insert = betterSqlite3.prepare(INSERT);
const betterSqlite3Select = betterSqlite3.prepare(SELECT);
const betterSqlite3Insert = betterSqlite3.prepare(INSERT);
benchmark.add('better-sqlite3', function () {
if (rowid % 2) {betterSqlite3Select.get(rowid % 1000 + 1);}
else {betterSqlite3Insert.run(data);}
rowid += 1;
benchmark.add('better-sqlite3', () => {
for (rowid = 0; rowid < 1000; ++rowid) {
if (rowid % 2) betterSqlite3Select.get(rowid + 1);
else betterSqlite3Insert.run(data);
}
});
benchmark.add('node-sqlite3', function (deferred) {
if (rowid % 2) {
nodeSqlite3.get(SELECT, rowid % 1000 + 1).then(function () {deferred.resolve();});
} else {
nodeSqlite3.run(INSERT, data).then(function () {deferred.resolve();});
benchmark.add('node-sqlite3', (deferred) => {
let count = 0;
const done = () => void (++count === 1000 && deferred.resolve());
for (rowid = 0; rowid < 1000; ++rowid) {
if (rowid % 2) nodeSqlite3.get(SELECT, rowid + 1).then(() => done());
else nodeSqlite3.run(INSERT, data).then(() => done());
}
rowid += 1;
});
});
}, 1000);
'use strict';
// Selects 100 rows
require('../runner')(function (benchmark, dbs, ctx) {
var SQL = 'SELECT ' + ctx.columns.join(', ') + ' FROM ' + ctx.table + ' WHERE rowid>=? LIMIT 100';
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var rowid = 99;
benchmark.on('cycle', function () {rowid = 99;});
require('../runner')((benchmark, dbs, ctx) => {
const SQL = `SELECT ${ctx.columns.join(', ')} FROM ${ctx.table} WHERE rowid>=? LIMIT 100`;
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
var betterSqlite3Select = betterSqlite3.prepare(SQL);
let rowid = 99;
benchmark.on('cycle', () => { rowid = 99; });
benchmark.add('better-sqlite3', function () {
betterSqlite3Select.all(rowid % 1000 - 98);
rowid += 100;
const betterSqlite3Select = betterSqlite3.prepare(SQL);
benchmark.add('better-sqlite3', () => {
betterSqlite3Select.all(rowid - 98);
rowid = (rowid + 100) % 1000;
});
benchmark.add('node-sqlite3', function (deferred) {
nodeSqlite3.all(SQL, rowid % 1000 - 98).then(function () {deferred.resolve();});
rowid += 100;
benchmark.add('node-sqlite3', (deferred) => {
nodeSqlite3.all(SQL, rowid - 98).then(() => void deferred.resolve());
rowid = (rowid + 100) % 1000;
});
});
'use strict';
// Selects 100 rows
require('../runner')(function (benchmark, dbs, ctx) {
var SQL = 'SELECT ' + ctx.columns.join(', ') + ' FROM ' + ctx.table + ' WHERE rowid>=? LIMIT 100';
var oneByOneSQL = SQL.replace(/\bLIMIT\s+\d+/i, 'LIMIT 1');
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var rowid = 99;
benchmark.on('cycle', function () {rowid = 99;});
require('../runner')((benchmark, dbs, ctx) => {
const SQL = `SELECT ${ctx.columns.join(', ')} FROM ${ctx.table} WHERE rowid>=? LIMIT 100`;
const oneByOneSQL = SQL.replace(/\bLIMIT\s+\d+/i, 'LIMIT 1');
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
var betterSqlite3Select = betterSqlite3.prepare(SQL);
let rowid = 99;
benchmark.on('cycle', () => { rowid = 99; });
benchmark.add('better-sqlite3', function () {
for (var obj of betterSqlite3Select.iterate(rowid % 1000 - 98)) {}
rowid += 100;
const betterSqlite3Select = betterSqlite3.prepare(SQL);
benchmark.add('better-sqlite3', () => {
for (const obj of betterSqlite3Select.iterate(rowid - 98)) {}
rowid = (rowid + 100) % 1000;
});
benchmark.add('node-sqlite3', function (deferred) {
var goal = rowid + 100;
benchmark.add('node-sqlite3', (deferred) => {
let count = 0;
function next() {
if (++rowid === goal) {
if (++count === 100) {
rowid = (rowid + 100) % 1000;
deferred.resolve();
} else {
nodeSqlite3.get(oneByOneSQL, rowid % 1000 - 98).then(next);
nodeSqlite3.get(oneByOneSQL, rowid + count - 98).then(next);
}
}
nodeSqlite3.get(oneByOneSQL, rowid % 1000 - 98).then(next);
nodeSqlite3.get(oneByOneSQL, rowid + count - 98).then(next);
});
});
'use strict';
// Selects 1 row
require('../runner')(function (benchmark, dbs, ctx) {
var SQL = 'SELECT ' + ctx.columns.join(', ') + ' FROM ' + ctx.table + ' WHERE rowid=?';
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var rowid = 0;
benchmark.on('cycle', function () {rowid = 0;});
require('../runner')((benchmark, dbs, ctx) => {
const SQL = `SELECT ${ctx.columns.join(', ')} FROM ${ctx.table} WHERE rowid=?`;
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
var betterSqlite3Select = betterSqlite3.prepare(SQL);
let rowid = 0;
benchmark.on('cycle', () => { rowid = 0; });
benchmark.add('better-sqlite3', function () {
betterSqlite3Select.get(rowid++ % 1000 + 1);
const betterSqlite3Select = betterSqlite3.prepare(SQL);
benchmark.add('better-sqlite3', () => {
betterSqlite3Select.get(rowid + 1);
rowid = (rowid + 1) % 1000;
});
benchmark.add('node-sqlite3', function (deferred) {
nodeSqlite3.get(SQL, rowid++ % 1000 + 1).then(function () {deferred.resolve();});
benchmark.add('node-sqlite3', (deferred) => {
nodeSqlite3.get(SQL, rowid + 1).then(() => void deferred.resolve());
rowid = (rowid + 1) % 1000;
});
});
'use strict';
// Inserts 100 rows
require('../runner')(function (benchmark, dbs, ctx) {
var SQL = 'INSERT INTO ' + ctx.table + ' (' + ctx.columns.join(', ') + ') VALUES (' + namedParams(ctx.columns).join(', ') + ')';
var betterSqlite3 = dbs['better-sqlite3'];
var nodeSqlite3 = dbs['node-sqlite3'];
var data = namedData(ctx.table, ctx.columns);
var dataWithPrefix = namedData(ctx.table, ctx.columns, true);
require('../runner')((benchmark, dbs, ctx) => {
const SQL = `INSERT INTO ${ctx.table} (${ctx.columns.join(', ')}) VALUES (${namedParams(ctx.columns).join(', ')})`;
const betterSqlite3 = dbs['better-sqlite3'];
const nodeSqlite3 = dbs['node-sqlite3'];
const data = namedData(ctx.table, ctx.columns);
const dataWithPrefix = namedData(ctx.table, ctx.columns, true);
var betterSqlite3Transaction = betterSqlite3.transaction(new Array(100).fill(SQL));
const betterSqlite3Transaction = betterSqlite3.transaction(new Array(100).fill(SQL));
benchmark.add('better-sqlite3', function () {
benchmark.add('better-sqlite3', () => {
betterSqlite3Transaction.run(data);
});
benchmark.add('node-sqlite3', function (deferred) {
var count = 0;
benchmark.add('node-sqlite3', (deferred) => {
let count = 0;
nodeSqlite3.run('BEGIN').then(function insert() {
if (++count < 100) {
return nodeSqlite3.run(SQL, dataWithPrefix).then(insert);
} else {
return nodeSqlite3.run(SQL, dataWithPrefix).then(() => {
return nodeSqlite3.run('COMMIT').then(() => void deferred.resolve());
});
}
return nodeSqlite3.run(SQL, dataWithPrefix).then(function () {
return nodeSqlite3.run('COMMIT').then(function () {deferred.resolve();});
});
});

@@ -29,14 +30,10 @@ });

function namedParams(columns) {
return columns.map(function (_, i) {return '@x' + i;});
return columns.map((_, i) => '@x' + i);
}
function namedData(table, columns, withPrefix) {
var data = require('../factory')(table, columns);
var bindNames = namedParams(columns);
var wrappedData = data.map(function (item, i) {
var wrappedItem = {};
wrappedItem[withPrefix ? bindNames[i] : bindNames[i].slice(1)] = item;
return wrappedItem;
});
return Object.assign.apply(Object, [{}].concat(wrappedData));
const data = require('../factory')(table, columns);
const bindNames = namedParams(columns);
const wrappedData = data.map((item, i) => ({ [bindNames[i].slice(+!withPrefix)]: item }));
return Object.assign({}, ...wrappedData);
}
'use strict';
var moduleRoot = require('path').dirname(__dirname);
var lzzArgs = [
const moduleRoot = require('path').dirname(__dirname);
const lzzArgs = [
'-hx', 'hpp',

@@ -11,9 +11,8 @@ '-sx', 'cpp',

'-e',
'./src/better_sqlite3.lzz'
'./src/better_sqlite3.lzz',
];
require('lzz-gyp')(lzzArgs, moduleRoot, process.env.CI === 'true')
.catch(function (err) {
require('lzz-gyp')(lzzArgs, moduleRoot, process.env.CI === 'true').catch((err) => {
console.error(err);
process.exit(1);
});
'use strict';
var path = require('path');
var toDescriptor = require('to-descriptor');
var util = require('./util');
var CPPDatabase = require('bindings')({
const path = require('path');
const util = require('./util');
const CPPDatabase = require('bindings')({
bindings: 'better_sqlite3.node',
module_root: path.resolve(__dirname, '..')
module_root: path.resolve(__dirname, '..'),
}).Database;

@@ -14,3 +13,3 @@

}
var filename = filenameGiven.trim();
let filename = filenameGiven.trim();
if (!filename) {

@@ -32,5 +31,5 @@ throw new TypeError('A database filename cannot be an empty string');

}
var memory = util.getBooleanOption(options, 'memory');
var readonly = util.getBooleanOption(options, 'readonly');
var fileMustExist = util.getBooleanOption(options, 'fileMustExist');
const memory = util.getBooleanOption(options, 'memory');
const readonly = util.getBooleanOption(options, 'readonly');
const fileMustExist = util.getBooleanOption(options, 'fileMustExist');

@@ -57,5 +56,3 @@ if (memory) {

CPPDatabase.prototype.constructor = Database;
Database.prototype = Object.create(Object.prototype, toDescriptor(CPPDatabase.prototype));
Object.keys(CPPDatabase.prototype).forEach(function (method) {delete CPPDatabase.prototype[method];});
Object.setPrototypeOf(CPPDatabase.prototype, Database.prototype);
Database.prototype = CPPDatabase.prototype;
module.exports = Database;
'use strict';
module.exports = function (setPragmaMode) {
return function (source, simplify) {
module.exports = (setPragmaMode) => {
return function pragma(source, simplify) {
if (typeof source !== 'string') {

@@ -14,11 +14,9 @@ throw new TypeError('Expected first argument to be a string');

try {
var result = simplify
? this.prepare('PRAGMA ' + source).pluck().get()
: this.prepare('PRAGMA ' + source).all();
return simplify
? this.prepare(`PRAGMA ${source}`).pluck().get()
: this.prepare(`PRAGMA ${source}`).all();
} finally {
setPragmaMode.call(this, false);
}
return result;
};
};
'use strict';
var util = require('./util');
var GeneratorFunctionProto = Object.getPrototypeOf(function*(){});
const util = require('./util');
const GeneratorFunctionProto = Object.getPrototypeOf(function*(){});
module.exports = function (createFunction) {
module.exports = (createFunction) => {
return function register(options, func) {

@@ -17,3 +17,3 @@ if (typeof options === 'function') {

var name = 'name' in options ? options.name : func.name;
const name = 'name' in options ? options.name : func.name;
if (typeof name !== 'string') {

@@ -26,12 +26,13 @@ throw new TypeError('Expected the "name" option to be a string');

var defaultSafeIntegers = !('safeIntegers' in options);
var safeIntegers = util.getBooleanOption(options, 'safeIntegers');
var deterministic = util.getBooleanOption(options, 'deterministic');
var varargs = util.getBooleanOption(options, 'varargs');
var aggregate = Object.getPrototypeOf(func) === GeneratorFunctionProto;
var argCount = -1;
const defaultSafeIntegers = !('safeIntegers' in options);
const safeIntegers = util.getBooleanOption(options, 'safeIntegers');
const deterministic = util.getBooleanOption(options, 'deterministic');
const varargs = util.getBooleanOption(options, 'varargs');
const aggregate = Object.getPrototypeOf(func) === GeneratorFunctionProto;
let argCount = -1;
let entry;
if (aggregate) {
var generator = func.call(undefined);
var entry = generator.next();
const generator = func.call(undefined);
entry = generator.next();
if (entry.done || typeof entry.value !== 'function') {

@@ -38,0 +39,0 @@ throw new TypeError('Custom aggregates must yield a function');

'use strict';
var descriptor = { writable: true, enumerable: false, configurable: true, value: 'SqliteError' };
const descriptor = { value: 'SqliteError', writable: true, enumerable: false, configurable: true };
function SqliteError(message, code) {
if (!(this instanceof SqliteError)) {
if (new.target !== SqliteError) {
return new SqliteError(message, code);

@@ -7,0 +7,0 @@ }

'use strict';
var fs = require('fs');
const fs = require('fs');
exports.getBooleanOption = function (options, key) {
var value = false;
exports.getBooleanOption = (options, key) => {
let value = false;
if (key in options && typeof (value = options[key]) !== 'boolean') {
throw new TypeError('Expected the "' + key + '" option to be a boolean');
throw new TypeError(`Expected the "${key}" option to be a boolean`);
}

@@ -12,13 +12,13 @@ return value;

exports.pathExists = function (path) {
try {fs.accessSync(path); return true;}
catch (ex) {return false;}
exports.pathExists = (path) => {
try { fs.accessSync(path); return true; }
catch (_) { return false; }
};
exports.wrap = function (Class, methodName, wrapper) {
var originalMethod = Class.prototype[methodName];
exports.wrap = (Class, methodName, wrapper) => {
const originalMethod = Class.prototype[methodName];
if (typeof originalMethod !== 'function') {
throw new TypeError('Missing method ' + methodName);
throw new TypeError(`Missing method ${methodName}`);
}
Class.prototype[methodName] = wrapper(originalMethod);
};
{
"name": "better-sqlite3",
"version": "4.0.3",
"version": "4.1.0",
"description": "The fastest and simplest library for SQLite3 in Node.js.",

@@ -13,14 +13,13 @@ "homepage": "http://github.com/JoshuaWise/better-sqlite3",

"dependencies": {
"bindings": "^1.2.1",
"integer": "^1.0.1",
"lzz-gyp": "^0.4.2",
"to-descriptor": "^1.0.1"
"bindings": "^1.3.0",
"integer": "^1.0.3",
"lzz-gyp": "^0.4.2"
},
"devDependencies": {
"benchmark": "^2.1.4",
"chai": "^3.5.0",
"cli-color": "^1.1.0",
"fs-extra": "^0.30.0",
"mocha": "^3.0.2",
"sqlite": "^2.5.0"
"chai": "^4.1.2",
"cli-color": "^1.2.0",
"fs-extra": "^5.0.0",
"mocha": "^4.1.0",
"sqlite": "^2.9.0"
},

@@ -27,0 +26,0 @@ "scripts": {

@@ -19,3 +19,3 @@ # better-sqlite3 [![Build Status](https://travis-ci.org/JoshuaWise/better-sqlite3.svg?branch=master)](https://travis-ci.org/JoshuaWise/better-sqlite3)

> You can verify these results by [running the benchmark yourself](https://github.com/JoshuaWise/better-sqlite3/wiki/Benchmark).
> *Both [sqlite](https://www.npmjs.com/package/sqlite) and [sqlite3](https://www.npmjs.com/package/sqlite3) have nearly identical performance because they both use the [same engine](https://github.com/mapbox/node-sqlite3).*
> *Both [npm/sqlite](https://www.npmjs.com/package/sqlite) and [npm/sqlite3](https://www.npmjs.com/package/sqlite3) have nearly identical performance because they both use the [same engine](https://github.com/mapbox/node-sqlite3).*

@@ -22,0 +22,0 @@ ## Installation

@@ -1,3 +0,3 @@

var expect = require('chai').expect;
var SqliteError = require('../.').SqliteError;
const { expect } = require('chai');
const { SqliteError } = require('../.');

@@ -16,3 +16,3 @@ describe('SqliteError', function () {

it('should accept two arguments for setting the message and error code', function () {
var err = SqliteError('foobar', 'baz');
const err = SqliteError('foobar', 'baz');
expect(err.message).to.equal('foobar');

@@ -19,0 +19,0 @@ expect(err.code).to.equal('baz');

@@ -1,39 +0,29 @@

var expect = require('chai').expect;
var fs = require('fs');
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const fs = require('fs');
const Database = require('../.');
const util = require('./util');
describe('new Database()', function () {
it('should throw an exception when file path is not a string', function () {
expect(function () {new Database();}).to.throw(TypeError);
expect(function () {new Database(null);}).to.throw(TypeError);
expect(function () {new Database(0);}).to.throw(TypeError);
expect(function () {new Database(123);}).to.throw(TypeError);
expect(function () {new Database(new String(util.next()));}).to.throw(TypeError);
expect(function () {new Database(function () {});}).to.throw(TypeError);
expect(function () {new Database([util.next()]);}).to.throw(TypeError);
expect(() => new Database()).to.throw(TypeError);
expect(() => new Database(null)).to.throw(TypeError);
expect(() => new Database(0)).to.throw(TypeError);
expect(() => new Database(123)).to.throw(TypeError);
expect(() => new Database(new String(util.next()))).to.throw(TypeError);
expect(() => new Database(() => {})).to.throw(TypeError);
expect(() => new Database([util.next()])).to.throw(TypeError);
});
it('should throw an exception when file path is empty', function () {
expect(function () {new Database('');}).to.throw(TypeError);
expect(() => new Database('')).to.throw(TypeError);
});
it('should not allow URI file paths', function () {
expect(function () {new Database('file:' + util.next());}).to.throw(TypeError);
expect(function () {new Database('file:' + util.next() + '?mode=memory&cache=shared');}).to.throw(TypeError);
expect(() => new Database(`file: ${util.next()}`)).to.throw(TypeError);
expect(() => new Database(`file: ${util.next()}?mode=memory&cache=shared`)).to.throw(TypeError);
});
it('should not allow ":memory:" databases', function () {
expect(function () {new Database(':memory:');}).to.throw(TypeError);
expect(() => new Database(':memory:')).to.throw(TypeError);
});
it('should allow disk-based databases to be created', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
var db = Database(util.current());
expect(() => fs.accessSync(util.next())).to.throw(Error);
const db = Database(util.current());
expect(db.name).to.equal(util.current());

@@ -47,4 +37,4 @@ expect(db.memory).to.be.false;

it('should allow in-memory databases to be created', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
var db = new Database(util.current(), {memory: true});
expect(() => fs.accessSync(util.next())).to.throw(Error);
const db = new Database(util.current(), { memory: true });
expect(db.name).to.equal(util.current());

@@ -55,10 +45,10 @@ expect(db.memory).to.be.true;

expect(db.inTransaction).to.be.false;
expect(function () {fs.accessSync(util.current());}).to.throw(Error);
expect(() => fs.accessSync(util.current())).to.throw(Error);
});
it('should allow readonly database connections to be created', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
expect(function () {new Database(util.current(), {readonly: true});}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CANTOPEN');;
expect(() => fs.accessSync(util.next())).to.throw(Error);
expect(() => new Database(util.current(), { readonly: true })).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CANTOPEN');
(new Database(util.current())).close();
fs.accessSync(util.current());
var db = new Database(util.current(), {readonly: true});
const db = new Database(util.current(), { readonly: true });
expect(db.name).to.equal(util.current());

@@ -72,4 +62,4 @@ expect(db.memory).to.be.false;

it('should allow the "readonly" and "memory" options on the same connection', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
var db = new Database(util.current(), {memory: true, readonly: true});
expect(() => fs.accessSync(util.next())).to.throw(Error);
const db = new Database(util.current(), { memory: true, readonly: true });
expect(db.name).to.equal(util.current());

@@ -80,10 +70,10 @@ expect(db.memory).to.be.true;

expect(db.inTransaction).to.be.false;
expect(function () {fs.accessSync(util.current());}).to.throw(Error);
expect(() => fs.accessSync(util.current())).to.throw(Error);
});
it('should accept the "fileMustExist" option', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
expect(function () {new Database(util.current(), {fileMustExist: true});}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CANTOPEN');;
expect(() => fs.accessSync(util.next())).to.throw(Error);
expect(() => new Database(util.current(), { fileMustExist: true })).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CANTOPEN');
(new Database(util.current())).close();
fs.accessSync(util.current());
var db = new Database(util.current(), {fileMustExist: true});
const db = new Database(util.current(), { fileMustExist: true });
expect(db.name).to.equal(util.current());

@@ -97,4 +87,4 @@ expect(db.memory).to.be.false;

it('should ignore "fileMustExist" when the "memory" option is true', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
var db = new Database(util.current(), {memory: true, fileMustExist: true});
expect(() => fs.accessSync(util.next())).to.throw(Error);
const db = new Database(util.current(), { memory: true, fileMustExist: true });
expect(db.name).to.equal(util.current());

@@ -105,11 +95,11 @@ expect(db.memory).to.be.true;

expect(db.inTransaction).to.be.false;
expect(function () {fs.accessSync(util.current());}).to.throw(Error);
expect(() => fs.accessSync(util.current())).to.throw(Error);
});
it('should throw an Error if opening the database failed', function () {
expect(function () {fs.accessSync(util.next());}).to.throw(Error);
expect(function () {new Database('temp/nonexistent/abcfoobar123/' + util.current());}).to.throw(TypeError);
expect(function () {fs.accessSync(util.current());}).to.throw(Error);
expect(() => fs.accessSync(util.next())).to.throw(Error);
expect(() => new Database(`temp/nonexistent/abcfoobar123/${util.current()}`)).to.throw(TypeError);
expect(() => fs.accessSync(util.current())).to.throw(Error);
})
it('should have a proper prototype chain', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db).to.be.an.instanceof(Database);

@@ -120,5 +110,4 @@ expect(db.constructor).to.equal(Database);

expect(Database.prototype.close).to.equal(db.close);
expect(Object.getOwnPropertyNames(Object.getPrototypeOf(db)).length).to.equal(1);
expect(Object.getOwnPropertyNames(Object.getPrototypeOf(db))[0]).to.equal('constructor');
expect(Database.prototype).to.equal(Object.getPrototypeOf(db));
});
});

@@ -1,18 +0,8 @@

var expect = require('chai').expect;
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const Database = require('../.');
const util = require('./util');
describe('Database#close()', function () {
it('should cause db.open to return false', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db.open).to.be.true;

@@ -23,3 +13,3 @@ db.close();

it('should return the database object', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db.open).to.be.true;

@@ -32,9 +22,9 @@ expect(db.close()).to.equal(db);

it('should prevent any further database operations', function () {
var db = new Database(util.next());
const db = new Database(util.next());
db.close();
expect(function () {db.prepare('CREATE TABLE people (name TEXT)');}).to.throw(TypeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)']);}).to.throw(TypeError);
expect(function () {db.pragma('cache_size');}).to.throw(TypeError);
expect(function () {db.checkpoint();}).to.throw(TypeError);
expect(() => db.prepare('CREATE TABLE people (name TEXT)')).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)'])).to.throw(TypeError);
expect(() => db.pragma('cache_size')).to.throw(TypeError);
expect(() => db.checkpoint()).to.throw(TypeError);
});
});

@@ -1,32 +0,22 @@

var expect = require('chai').expect;
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const Database = require('../.');
const util = require('./util');
describe('Database#pragma()', function () {
it('should throw an exception if a string is not provided', function () {
var db = new Database(util.next());
expect(function () {db.pragma(123);}).to.throw(TypeError);
expect(function () {db.pragma(0);}).to.throw(TypeError);
expect(function () {db.pragma(null);}).to.throw(TypeError);
expect(function () {db.pragma();}).to.throw(TypeError);
expect(function () {db.pragma(new String('cache_size'));}).to.throw(TypeError);
const db = new Database(util.next());
expect(() => db.pragma(123)).to.throw(TypeError);
expect(() => db.pragma(0)).to.throw(TypeError);
expect(() => db.pragma(null)).to.throw(TypeError);
expect(() => db.pragma()).to.throw(TypeError);
expect(() => db.pragma(new String('cache_size'))).to.throw(TypeError);
});
it('should throw an exception if invalid/redundant SQL is provided', function () {
var db = new Database(util.next());
expect(function () {db.pragma('PRAGMA cache_size');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {db.pragma('cache_size; PRAGMA cache_size');}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.pragma('PRAGMA cache_size')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => db.pragma('cache_size; PRAGMA cache_size')).to.throw(RangeError);
});
it('should execute the pragma, returning rows of results', function () {
var db = new Database(util.next());
var rows = db.pragma('cache_size');
const db = new Database(util.next());
const rows = db.pragma('cache_size');
expect(rows[0].cache_size).to.be.a('number');

@@ -36,15 +26,15 @@ expect(rows[0].cache_size).to.equal(-16000);

it('should optionally return simpler results', function () {
var db = new Database(util.next());
var cache_size = db.pragma('cache_size', true);
const db = new Database(util.next());
const cache_size = db.pragma('cache_size', true);
expect(cache_size).to.be.a('number');
expect(cache_size).to.equal(-16000);
expect(function () {db.pragma('cache_size', undefined)}).to.throw(TypeError);
expect(function () {db.pragma('cache_size', null)}).to.throw(TypeError);
expect(function () {db.pragma('cache_size', 123)}).to.throw(TypeError);
expect(function () {db.pragma('cache_size', function () {})}).to.throw(TypeError);
expect(function () {db.pragma('cache_size', NaN)}).to.throw(TypeError);
expect(function () {db.pragma('cache_size', 'true')}).to.throw(TypeError);
expect(() => db.pragma('cache_size', undefined)).to.throw(TypeError);
expect(() => db.pragma('cache_size', null)).to.throw(TypeError);
expect(() => db.pragma('cache_size', 123)).to.throw(TypeError);
expect(() => db.pragma('cache_size', function () {})).to.throw(TypeError);
expect(() => db.pragma('cache_size', NaN)).to.throw(TypeError);
expect(() => db.pragma('cache_size', 'true')).to.throw(TypeError);
});
it('should obey PRAGMA changes', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db.pragma('cache_size', true)).to.equal(-16000);

@@ -59,3 +49,3 @@ db.pragma('cache_size = -8000');

(new Database(util.next())).close();
var db = new Database(util.current(), {readonly: true, fileMustExist: true});
const db = new Database(util.current(), { readonly: true, fileMustExist: true });
expect(db.pragma('cache_size', true)).to.equal(-16000);

@@ -65,9 +55,9 @@ db.pragma('cache_size = -8000');

expect(db.pragma('journal_mode', true)).to.equal('delete');
expect(function () {db.pragma('journal_mode = wal');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
expect(() => db.pragma('journal_mode = wal')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
expect(db.pragma('journal_mode', true)).to.equal('delete');
});
it('should return undefined if no rows exist and simpler results are desired', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db.pragma('table_info', true)).to.be.undefined;
});
});

@@ -1,17 +0,7 @@

var expect = require('chai').expect;
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const Database = require('../.');
const util = require('./util');
describe('Database#prepare()', function () {
function assertStmt(stmt, source, db, returnsData) {
const assertStmt = (stmt, source, db, returnsData) => {
expect(stmt.source).to.equal(source);

@@ -21,34 +11,32 @@ expect(stmt.constructor.name).to.equal('Statement');

expect(stmt.returnsData).to.equal(returnsData);
expect(function () {
new stmt.constructor(source);
}).to.throw(TypeError);
}
expect(() => new stmt.constructor(source)).to.throw(TypeError);
};
it('should throw an exception if a string is not provided', function () {
var db = new Database(util.next());
expect(function () {db.prepare(123);}).to.throw(TypeError);
expect(function () {db.prepare(0);}).to.throw(TypeError);
expect(function () {db.prepare(null);}).to.throw(TypeError);
expect(function () {db.prepare();}).to.throw(TypeError);
expect(function () {db.prepare(new String('CREATE TABLE people (name TEXT)'));}).to.throw(TypeError);
const db = new Database(util.next());
expect(() => db.prepare(123)).to.throw(TypeError);
expect(() => db.prepare(0)).to.throw(TypeError);
expect(() => db.prepare(null)).to.throw(TypeError);
expect(() => db.prepare()).to.throw(TypeError);
expect(() => db.prepare(new String('CREATE TABLE people (name TEXT)'))).to.throw(TypeError);
});
it('should throw an exception if invalid SQL is provided', function () {
var db = new Database(util.next());
expect(function () {db.prepare('CREATE TABLE people (name TEXT');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {db.prepare('INSERT INTO people VALUES (?)');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
const db = new Database(util.next());
expect(() => db.prepare('CREATE TABLE people (name TEXT')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => db.prepare('INSERT INTO people VALUES (?)')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
});
it('should throw an exception if no statements are provided', function () {
var db = new Database(util.next());
expect(function () {db.prepare('');}).to.throw(RangeError);
expect(function () {db.prepare(';');}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.prepare('')).to.throw(RangeError);
expect(() => db.prepare(';')).to.throw(RangeError);
});
it('should throw an exception if more than one statement is provided', function () {
var db = new Database(util.next());
expect(function () {db.prepare('CREATE TABLE people (name TEXT);CREATE TABLE animals (name TEXT)');}).to.throw(RangeError);
expect(function () {db.prepare('CREATE TABLE people (name TEXT); ');}).to.throw(RangeError);
expect(function () {db.prepare('CREATE TABLE people (name TEXT);;');}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.prepare('CREATE TABLE people (name TEXT);CREATE TABLE animals (name TEXT)')).to.throw(RangeError);
expect(() => db.prepare('CREATE TABLE people (name TEXT); ')).to.throw(RangeError);
expect(() => db.prepare('CREATE TABLE people (name TEXT);;')).to.throw(RangeError);
});
it('should create a prepared Statement object', function () {
var db = new Database(util.next());
var stmt1 = db.prepare('CREATE TABLE people (name TEXT)');
var stmt2 = db.prepare('CREATE TABLE people (name TEXT);');
const db = new Database(util.next());
const stmt1 = db.prepare('CREATE TABLE people (name TEXT)');
const stmt2 = db.prepare('CREATE TABLE people (name TEXT);');
assertStmt(stmt1, 'CREATE TABLE people (name TEXT)', db, false);

@@ -60,6 +48,6 @@ assertStmt(stmt2, 'CREATE TABLE people (name TEXT);', db, false);

it('should create a prepared Statement object with just an expression', function () {
var db = new Database(util.next());
var stmt = db.prepare('SELECT 555');
const db = new Database(util.next());
const stmt = db.prepare('SELECT 555');
assertStmt(stmt, 'SELECT 555', db, true);
});
});

@@ -1,75 +0,65 @@

var expect = require('chai').expect;
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const Database = require('../.');
const util = require('./util');
describe('Database#transaction()', function () {
it('should throw an exception if an array of strings is not provided', function () {
var db = new Database(util.next());
expect(function () {db.transaction(123);}).to.throw(TypeError);
expect(function () {db.transaction(0);}).to.throw(TypeError);
expect(function () {db.transaction(null);}).to.throw(TypeError);
expect(function () {db.transaction();}).to.throw(TypeError);
expect(function () {db.transaction(new String('CREATE TABLE people (name TEXT)'));}).to.throw(TypeError);
expect(function () {db.transaction({0: 'CREATE TABLE people (name TEXT)', length: 1});}).to.throw(TypeError);
expect(function () {db.transaction([123]);}).to.throw(TypeError);
expect(function () {db.transaction([0]);}).to.throw(TypeError);
expect(function () {db.transaction([null]);}).to.throw(TypeError);
expect(function () {db.transaction([new String('CREATE TABLE people (name TEXT)')]);}).to.throw(TypeError);
const db = new Database(util.next());
expect(() => db.transaction(123)).to.throw(TypeError);
expect(() => db.transaction(0)).to.throw(TypeError);
expect(() => db.transaction(null)).to.throw(TypeError);
expect(() => db.transaction()).to.throw(TypeError);
expect(() => db.transaction(new String('CREATE TABLE people (name TEXT)'))).to.throw(TypeError);
expect(() => db.transaction({ 0: 'CREATE TABLE people (name TEXT)', length: 1 })).to.throw(TypeError);
expect(() => db.transaction([123])).to.throw(TypeError);
expect(() => db.transaction([0])).to.throw(TypeError);
expect(() => db.transaction([null])).to.throw(TypeError);
expect(() => db.transaction([new String('CREATE TABLE people (name TEXT)')])).to.throw(TypeError);
});
it('should throw an exception if no strings are provided', function () {
var db = new Database(util.next());
expect(function () {db.transaction([]);}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.transaction([])).to.throw(RangeError);
});
it('should propagate exceptions thrown from array accessors', function () {
var db = new Database(util.next());
var err = new Error('foobar');
var arr = ['foo'];
Object.defineProperty(arr, '0', {get: function () {throw err;}});
expect(function () {db.transaction(arr);}).to.throw(err);
const db = new Database(util.next());
const err = new Error('foobar');
const arr = ['foo'];
Object.defineProperty(arr, '0', { get: () => { throw err; } });
expect(() => db.transaction(arr)).to.throw(err);
});
it('should throw an exception if invalid SQL is provided', function () {
var db = new Database(util.next());
expect(function () {db.transaction(['CREATE TABLE people (name TEXT']);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {db.transaction(['INSERT INTO people VALUES (?)']);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
const db = new Database(util.next());
expect(() => db.transaction(['CREATE TABLE people (name TEXT'])).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => db.transaction(['INSERT INTO people VALUES (?)'])).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
});
it('should throw an exception if a string contains no statements', function () {
var db = new Database(util.next());
expect(function () {db.transaction(['']);}).to.throw(RangeError);
expect(function () {db.transaction([';']);}).to.throw(RangeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', '']);}).to.throw(RangeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', ';']);}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.transaction([''])).to.throw(RangeError);
expect(() => db.transaction([';'])).to.throw(RangeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', ''])).to.throw(RangeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', ';'])).to.throw(RangeError);
});
it('should throw an exception if multiple statements exist in one string', function () {
var db = new Database(util.next());
expect(function () {db.transaction(['CREATE TABLE people (name TEXT);CREATE TABLE animals (name TEXT)']);}).to.throw(RangeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT); ']);}).to.throw(RangeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT);;']);}).to.throw(RangeError);
const db = new Database(util.next());
expect(() => db.transaction(['CREATE TABLE people (name TEXT);CREATE TABLE animals (name TEXT)'])).to.throw(RangeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT); '])).to.throw(RangeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT);;'])).to.throw(RangeError);
});
it('should throw an exception if any read-only statements are provided', function () {
var db = new Database(util.next());
expect(function () {db.transaction(['SELECT 555']);}).to.throw(TypeError);
expect(function () {db.transaction(['BEGIN TRANSACTION']);}).to.throw(TypeError);
expect(function () {db.transaction(['COMMIT TRANSACTION']);}).to.throw(TypeError);
expect(function () {db.transaction(['ROLLBACK TRANSACTION']);}).to.throw(TypeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', 'SELECT 555']);}).to.throw(TypeError);
expect(function () {db.transaction(['SELECT 555', 'CREATE TABLE people (name TEXT)']);}).to.throw(TypeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', 'BEGIN TRANSACTION']);}).to.throw(TypeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', 'COMMIT TRANSACTION']);}).to.throw(TypeError);
expect(function () {db.transaction(['CREATE TABLE people (name TEXT)', 'ROLLBACK TRANSACTION']);}).to.throw(TypeError);
const db = new Database(util.next());
expect(() => db.transaction(['SELECT 555'])).to.throw(TypeError);
expect(() => db.transaction(['BEGIN TRANSACTION'])).to.throw(TypeError);
expect(() => db.transaction(['COMMIT TRANSACTION'])).to.throw(TypeError);
expect(() => db.transaction(['ROLLBACK TRANSACTION'])).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', 'SELECT 555'])).to.throw(TypeError);
expect(() => db.transaction(['SELECT 555', 'CREATE TABLE people (name TEXT)'])).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', 'BEGIN TRANSACTION'])).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', 'COMMIT TRANSACTION'])).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE people (name TEXT)', 'ROLLBACK TRANSACTION'])).to.throw(TypeError);
});
it('should create a prepared Transaction object', function () {
var db = new Database(util.next());
var trans1 = db.transaction(['CREATE TABLE people (name TEXT)']);
var trans2 = db.transaction(['CREATE TABLE people (name TEXT)', 'CREATE TABLE animals (name TEXT);']);
var trans3 = db.transaction(['CREATE TABLE people (name TEXT);', 'CREATE TABLE animals (name TEXT)']);
const db = new Database(util.next());
const trans1 = db.transaction(['CREATE TABLE people (name TEXT)']);
const trans2 = db.transaction(['CREATE TABLE people (name TEXT)', 'CREATE TABLE animals (name TEXT);']);
const trans3 = db.transaction(['CREATE TABLE people (name TEXT);', 'CREATE TABLE animals (name TEXT)']);
expect(trans1.source).to.equal('CREATE TABLE people (name TEXT);');

@@ -84,5 +74,3 @@ expect(trans2.source).to.equal('CREATE TABLE people (name TEXT);\nCREATE TABLE animals (name TEXT);');

expect(trans3.database).to.equal(db);
expect(function () {
new trans1.constructor(['CREATE TABLE people (name TEXT)']);
}).to.throw(TypeError);
expect(() => new trans1.constructor(['CREATE TABLE people (name TEXT)'])).to.throw(TypeError);
expect(trans1).to.not.equal(trans2);

@@ -89,0 +77,0 @@ expect(trans1).to.not.equal(trans3);

@@ -1,31 +0,27 @@

var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Database#exec()', function () {
it('should throw an exception if a string is not provided', function () {
expect(function () {db.exec(123);}).to.throw(TypeError);
expect(function () {db.exec(0);}).to.throw(TypeError);
expect(function () {db.exec(null);}).to.throw(TypeError);
expect(function () {db.exec();}).to.throw(TypeError);
expect(function () {db.exec(new String('CREATE TABLE entries (a TEXT, b INTEGER)'));}).to.throw(TypeError);
expect(() => db.exec(123)).to.throw(TypeError);
expect(() => db.exec(0)).to.throw(TypeError);
expect(() => db.exec(null)).to.throw(TypeError);
expect(() => db.exec()).to.throw(TypeError);
expect(() => db.exec(new String('CREATE TABLE entries (a TEXT, b INTEGER)'))).to.throw(TypeError);
});
it('should throw an exception if invalid SQL is provided', function () {
expect(function () {db.exec('CREATE TABLE entries (a TEXT, b INTEGER');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => db.exec('CREATE TABLE entries (a TEXT, b INTEGER')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
});
it('should obey the restrictions of readonly mode', function () {
var db2 = new Database(db.name, {readonly: true});
expect(function () {db2.exec('CREATE TABLE people (name TEXT)');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
const db2 = new Database(db.name, { readonly: true });
expect(() => db2.exec('CREATE TABLE people (name TEXT)')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
db2.exec('SELECT 555');
});
it('should execute the SQL, returning the database object itself', function () {
var returnValues = [];
const returnValues = [];
var r1 = db.exec('CREATE TABLE entries (a TEXT, b INTEGER)');
var r2 = db.exec('INSERT INTO entries VALUES (\'foobar\', 44); INSERT INTO entries VALUES (\'baz\', NULL);');
var r3 = db.exec('SELECT * FROM entries');
const r1 = db.exec('CREATE TABLE entries (a TEXT, b INTEGER)');
const r2 = db.exec('INSERT INTO entries VALUES (\'foobar\', 44); INSERT INTO entries VALUES (\'baz\', NULL);');
const r3 = db.exec('SELECT * FROM entries');

@@ -36,3 +32,3 @@ expect(r1).to.equal(db);

var rows = db.prepare('SELECT * FROM entries ORDER BY rowid').all();
const rows = db.prepare('SELECT * FROM entries ORDER BY rowid').all();
expect(rows.length).to.equal(2);

@@ -39,0 +35,0 @@ expect(rows[0].a).to.equal('foobar');

'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Statement#run()', function () {
it('should throw an exception when used on a statement that returns data', function () {
var stmt = db.prepare('SELECT 555');
expect(function () {stmt.run();}).to.throw(TypeError);
const stmt = db.prepare('SELECT 555');
expect(() => stmt.run()).to.throw(TypeError);
});
it('should work with CREATE TABLE', function () {
var stmt = db.prepare('CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB)');
var info = stmt.run();
const stmt = db.prepare('CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB)');
const info = stmt.run();
expect(info.changes).to.equal(0);

@@ -22,4 +18,4 @@ expect(info.lastInsertROWID).to.equal(0);

it('should work with CREATE TABLE IF NOT EXISTS', function () {
var stmt = db.prepare('CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB)');
var info = stmt.run();
const stmt = db.prepare('CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB)');
const info = stmt.run();
expect(info.changes).to.equal(0);

@@ -29,4 +25,4 @@ expect(info.lastInsertROWID).to.equal(0);

it('should work with INSERT INTO', function () {
var stmt = db.prepare("INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')");
var info = stmt.run();
let stmt = db.prepare("INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')");
let info = stmt.run();
expect(info.changes).to.equal(1);

@@ -45,11 +41,11 @@ expect(info.lastInsertROWID).to.equal(1);

it('should work with UPDATE', function () {
var stmt = db.prepare("UPDATE entries SET a='bar' WHERE rowid=1");
const stmt = db.prepare("UPDATE entries SET a='bar' WHERE rowid=1");
expect(stmt.run().changes).to.equal(1);
});
it('should work with DELETE FROM', function () {
var stmt = db.prepare("DELETE FROM entries WHERE a='foo'");
let stmt = db.prepare("DELETE FROM entries WHERE a='foo'");
expect(stmt.run().changes).to.equal(3);
stmt = db.prepare("INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')");
var info = stmt.run();
const info = stmt.run();
expect(info.changes).to.equal(1);

@@ -62,3 +58,3 @@ expect(info.lastInsertROWID).to.equal(2);

expect(db.inTransaction).to.equal(true);
var info = db.prepare("INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')").run();
const info = db.prepare("INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')").run();
expect(info.changes).to.equal(1);

@@ -71,3 +67,3 @@ expect(info.lastInsertROWID).to.equal(3);

it('should work with DROP TABLE', function () {
var stmt = db.prepare("DROP TABLE entries");
const stmt = db.prepare("DROP TABLE entries");
expect(stmt.run().changes).to.equal(0);

@@ -83,6 +79,6 @@ });

db.prepare("INSERT INTO ages VALUES (35, 2)").run();
var stmt = db.prepare("INSERT INTO ages VALUES (30, 3)");
expect(function () {stmt.run();}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
let stmt = db.prepare("INSERT INTO ages VALUES (30, 3)");
expect(() => stmt.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
stmt = db.prepare("INSERT INTO ages VALUES (30, NULL)");
expect(function () {stmt.run();}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_NOTNULL');
expect(() => stmt.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_NOTNULL');
});

@@ -92,58 +88,58 @@ it('should allow ad-hoc transactions', function () {

expect(db.prepare("INSERT INTO ages VALUES (45, 2)").run().changes).to.equal(1);
var stmt = db.prepare("INSERT INTO ages VALUES (30, 3)");
expect(function () {stmt.run()}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
const stmt = db.prepare("INSERT INTO ages VALUES (30, 3)");
expect(() => stmt.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
expect(db.prepare("ROLLBACK TRANSACTION").run().changes).to.equal(0);
});
it('should not count changes from indirect mechanisms', function () {
var stmt = db.prepare("UPDATE people SET id=55 WHERE id=2");
const stmt = db.prepare("UPDATE people SET id=55 WHERE id=2");
expect(stmt.run().changes).to.equal(1);
});
it('should count accurate DELETE changes when a dropped table has side effects', function () {
var stmt = db.prepare("DROP TABLE people");
const stmt = db.prepare("DROP TABLE people");
expect(stmt.run().changes).to.equal(2);
});
it('should obey the restrictions of readonly mode', function () {
var db2 = new Database(db.name, {readonly: true});
var stmt = db2.prepare('CREATE TABLE people (name TEXT)');
expect(function () {stmt.run()}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
const db2 = new Database(db.name, { readonly: true });
const stmt = db2.prepare('CREATE TABLE people (name TEXT)');
expect(() => stmt.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
});
it('should accept bind parameters', function () {
db.prepare("CREATE TABLE entries (a TEXT CHECK(typeof(a)=='text'), b INTEGER CHECK(typeof(b)=='integer' OR typeof(b)=='real'), c REAL CHECK(typeof(c)=='real' OR typeof(c)=='integer'), d BLOB CHECK(typeof(d)=='blob'))").run();
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, bufferOfSize(8).fill(0xdd));
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(['foo', 25, 25, bufferOfSize(8).fill(0xdd)]);
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(['foo', 25], [25], bufferOfSize(8).fill(0xdd));
db.prepare('INSERT INTO entries VALUES (@a, @b, @c, @d)').run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
db.prepare('INSERT INTO entries VALUES ($a, $b, $c, $d)').run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
db.prepare('INSERT INTO entries VALUES (:a, :b, :c, :d)').run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({a: 25}, ['foo'], bufferOfSize(8).fill(0xdd));
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({a: 25}, ['foo'], bufferOfSize(8).fill(0xdd), bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({a: 25}, ['foo']);
}).to.throw(RangeError);
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({a: 25, c: 25}, ['foo'], bufferOfSize(8).fill(0xdd));
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({}, ['foo'], bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(25, 'foo', 25, bufferOfSize(8).fill(0xdd));
}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_CHECK');
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, bufferOfSize(8).fill(0xdd), {});
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, bufferOfSize(8).fill(0xdd), {foo: 'foo'});
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, {4: bufferOfSize(8).fill(0xdd)});
}).to.throw(RangeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run();
}).to.throw(RangeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run({length: 4, 0: 'foo', 1: 25, 2: 25, 3: bufferOfSize(8).fill(0xdd)});
}).to.throw(RangeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, new Number(25), bufferOfSize(8).fill(0xdd));
}).to.throw(TypeError);
expect(function () {
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', {low: 25, high: 25}, 25, bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, Buffer.alloc(8).fill(0xdd));
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(['foo', 25, 25, Buffer.alloc(8).fill(0xdd)]);
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(['foo', 25], [25], Buffer.alloc(8).fill(0xdd));
db.prepare('INSERT INTO entries VALUES (@a, @b, @c, @d)').run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.prepare('INSERT INTO entries VALUES ($a, $b, $c, $d)').run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.prepare('INSERT INTO entries VALUES (:a, :b, :c, :d)').run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({ a: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd));
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({ a: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd), Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({ a: 25 }, ['foo'])
).to.throw(RangeError);
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({ a: 25, c: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd));
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, @a, @a, ?)').run({}, ['foo'], Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run(25, 'foo', 25, Buffer.alloc(8).fill(0xdd))
).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_CHECK');
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, Buffer.alloc(8).fill(0xdd), {});
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, Buffer.alloc(8).fill(0xdd), { foo: 'foo' });
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, 25, { 4: Buffer.alloc(8).fill(0xdd) })
).to.throw(RangeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run()
).to.throw(RangeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run({ length: 4, 0: 'foo', 1: 25, 2: 25, 3: Buffer.alloc(8).fill(0xdd) })
).to.throw(RangeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', 25, new Number(25), Buffer.alloc(8).fill(0xdd))
).to.throw(TypeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?)').run('foo', { low: 25, high: 25 }, 25, Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
function Foo() {

@@ -153,13 +149,13 @@ this.a = 'foo';

this.c = 25;
this.d = bufferOfSize(8).fill(0xdd);
this.d = Buffer.alloc(8).fill(0xdd);
}
expect(function () {
db.prepare('INSERT INTO entries VALUES (@a, @b, @c, @d)').run(new Foo);
}).to.throw(TypeError);
expect(() =>
db.prepare('INSERT INTO entries VALUES (@a, @b, @c, @d)').run(new Foo)
).to.throw(TypeError);
// This part of the test may fail is Statement#get() does not work.
var i = 0;
var row;
while (row = db.prepare('SELECT * FROM entries WHERE rowid=' + ++i).get()) {
expect(row).to.deep.equal({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
let i = 0;
let row;
while (row = db.prepare(`SELECT * FROM entries WHERE rowid=${++i}`).get()) {
expect(row).to.deep.equal({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
}

@@ -169,5 +165,1 @@ expect(i).to.equal(11);

});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Statement#get()', function () {

@@ -14,13 +10,13 @@ it('should throw an exception when used on a statement that returns no data', function () {

var stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
let stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.get();}).to.throw(TypeError);
expect(() => stmt.get()).to.throw(TypeError);
var stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.get();}).to.throw(TypeError);
expect(() => stmt.get()).to.throw(TypeError);
var stmt = db.prepare("BEGIN TRANSACTION");
stmt = db.prepare("BEGIN TRANSACTION");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.get();}).to.throw(TypeError);
expect(() => stmt.get()).to.throw(TypeError);
});

@@ -30,12 +26,12 @@ it('should return the first matching row', function () {

var stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
let stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
expect(stmt.returnsData).to.be.true;
expect(stmt.get()).to.deep.equal({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null});
expect(stmt.get()).to.deep.equal({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null });
stmt = db.prepare("SELECT * FROM entries WHERE b > 5 ORDER BY rowid");
expect(stmt.get()).to.deep.equal({a: 'foo', b: 6, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null});
expect(stmt.get()).to.deep.equal({ a: 'foo', b: 6, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null });
});
it('should obey the current pluck setting', function () {
var stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
const stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
expect(stmt.get()).to.deep.equal(row);

@@ -50,3 +46,3 @@ expect(stmt.pluck(true).get()).to.equal('foo');

it('should return undefined when no rows were found', function () {
var stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
const stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
expect(stmt.get()).to.be.undefined;

@@ -56,36 +52,32 @@ expect(stmt.pluck().get()).to.be.undefined;

it('should accept bind parameters', function () {
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
var SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
var SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
var result = db.prepare(SQL1).get('foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null);
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
const SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
const SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
let result = db.prepare(SQL1).get('foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null);
expect(result).to.deep.equal(row);
result = db.prepare(SQL1).get(['foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null]);
result = db.prepare(SQL1).get(['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]);
expect(result).to.deep.equal(row);
result = db.prepare(SQL1).get(['foo', 1], [3.14], bufferOfSize(4).fill(0xdd), [,]);
result = db.prepare(SQL1).get(['foo', 1], [3.14], Buffer.alloc(4).fill(0xdd), [,]);
expect(result).to.deep.equal(row);
result = db.prepare(SQL2).get({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: undefined});
result = db.prepare(SQL2).get({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: undefined });
expect(result).to.deep.equal(row);
result = db.prepare(SQL2).get({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xaa), e: undefined});
result = db.prepare(SQL2).get({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xaa), e: undefined });
expect(result).to.be.undefined;
expect(function () {
db.prepare(SQL2).get({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd)});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).get({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd) })
).to.throw(RangeError);
expect(function () {
db.prepare(SQL1).get();
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL1).get()
).to.throw(RangeError);
expect(function () {
db.prepare(SQL2).get({});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).get({})
).to.throw(RangeError);
});
});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Statement#all()', function () {

@@ -14,19 +10,19 @@ it('should throw an exception when used on a statement that returns no data', function () {

var stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
let stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.all();}).to.throw(TypeError);
expect(() => stmt.all()).to.throw(TypeError);
var stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.all();}).to.throw(TypeError);
expect(() => stmt.all()).to.throw(TypeError);
var stmt = db.prepare("BEGIN TRANSACTION");
stmt = db.prepare("BEGIN TRANSACTION");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.all();}).to.throw(TypeError);
expect(() => stmt.all()).to.throw(TypeError);
});
it('should return an array of every matching row', function () {
db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
var stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
let stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
expect(stmt.returnsData).to.be.true;

@@ -39,3 +35,4 @@ matchesFrom(stmt.all(), 1);

function matchesFrom(rows, i) {
for (var index = 0; i<=10; ++i, ++index) {
let index = 0;
for (; i <= 10; ++i, ++index) {
row.b = i;

@@ -48,4 +45,4 @@ expect(rows[index]).to.deep.equal(row);

it('should obey the current pluck setting', function () {
var stmt = db.prepare("SELECT * FROM entries");
var plucked = new Array(10).fill('foo');
const stmt = db.prepare("SELECT * FROM entries");
const plucked = new Array(10).fill('foo');
expect(stmt.all()).to.not.deep.equal(plucked);

@@ -60,3 +57,3 @@ expect(stmt.pluck(true).all()).to.deep.equal(plucked);

it('should return an empty array when no rows were found', function () {
var stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
const stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
expect(stmt.all()).to.deep.equal([]);

@@ -66,36 +63,32 @@ expect(stmt.pluck().all()).to.deep.equal([]);

it('should accept bind parameters', function () {
var rows = [{a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null}];
var SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
var SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
var result = db.prepare(SQL1).all('foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null);
const rows = [{ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null }];
const SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
const SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
let result = db.prepare(SQL1).all('foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null);
expect(result).to.deep.equal(rows);
result = db.prepare(SQL1).all(['foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null]);
result = db.prepare(SQL1).all(['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]);
expect(result).to.deep.equal(rows);
result = db.prepare(SQL1).all(['foo', 1], [3.14], bufferOfSize(4).fill(0xdd), [,]);
result = db.prepare(SQL1).all(['foo', 1], [3.14], Buffer.alloc(4).fill(0xdd), [,]);
expect(result).to.deep.equal(rows);
result = db.prepare(SQL2).all({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: undefined});
result = db.prepare(SQL2).all({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: undefined });
expect(result).to.deep.equal(rows);
result = db.prepare(SQL2).all({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xaa), e: undefined});
result = db.prepare(SQL2).all({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xaa), e: undefined });
expect(result).to.deep.equal([]);
expect(function () {
db.prepare(SQL2).all({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd)});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).all({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd) })
).to.throw(RangeError);
expect(function () {
db.prepare(SQL1).all();
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL1).all()
).to.throw(RangeError);
expect(function () {
db.prepare(SQL2).all({});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).all({})
).to.throw(RangeError);
});
});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Statement#iterate()', function () {

@@ -14,13 +10,13 @@ it('should throw an exception when used on a statement that returns no data', function () {

var stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
let stmt = db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.iterate();}).to.throw(TypeError);
expect(() => stmt.iterate()).to.throw(TypeError);
var stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
stmt = db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.iterate();}).to.throw(TypeError);
expect(() => stmt.iterate()).to.throw(TypeError);
var stmt = db.prepare("BEGIN TRANSACTION");
stmt = db.prepare("BEGIN TRANSACTION");
expect(stmt.returnsData).to.be.false;
expect(function () {stmt.iterate();}).to.throw(TypeError);
expect(() => stmt.iterate()).to.throw(TypeError);

@@ -30,9 +26,9 @@ db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();

it('should return an iterator over each matching row', function () {
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
var count = 0;
var stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
let count = 0;
let stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
expect(stmt.returnsData).to.be.true;
var iterator = stmt.iterate();
const iterator = stmt.iterate();
expect(iterator).to.not.be.null;

@@ -46,3 +42,3 @@ expect(typeof iterator).to.equal('object');

for (var data of iterator) {
for (const data of iterator) {
row.b = ++count;

@@ -55,5 +51,5 @@ expect(data).to.deep.equal(row);

stmt = db.prepare("SELECT * FROM entries WHERE b > 5 ORDER BY rowid");
var iterator2 = stmt.iterate();
const iterator2 = stmt.iterate();
expect(iterator).to.not.equal(iterator2);
for (var data of iterator2) {
for (const data of iterator2) {
row.b = ++count + 5;

@@ -65,4 +61,4 @@ expect(data).to.deep.equal(row);

it('should obey the current pluck setting', function () {
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
var stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
const stmt = db.prepare("SELECT * FROM entries ORDER BY rowid");
shouldHave(row);

@@ -80,4 +76,4 @@ stmt.pluck(true);

function shouldHave(desiredData) {
var i = 0;
for (var data of stmt.iterate()) {
let i = 0;
for (const data of stmt.iterate()) {
++i;

@@ -93,11 +89,11 @@ if (typeof desiredData === 'object' && desiredData !== null) {

it('should not be able to invoke .pluck() while the database is busy', function () {
var stmt1 = db.prepare("SELECT * FROM entries");
var stmt2 = db.prepare("SELECT * FROM entries LIMIT 2");
var i = 0;
for (var data of stmt1.iterate()) {
const stmt1 = db.prepare("SELECT * FROM entries");
const stmt2 = db.prepare("SELECT * FROM entries LIMIT 2");
let i = 0;
for (const data of stmt1.iterate()) {
++i;
expect(function () {stmt1.pluck();}).to.throw(TypeError);
expect(function () {stmt2.pluck();}).to.throw(TypeError);
expect(function () {stmt1.pluck(false);}).to.throw(TypeError);
expect(function () {stmt2.pluck(false);}).to.throw(TypeError);
expect(() => stmt1.pluck()).to.throw(TypeError);
expect(() => stmt2.pluck()).to.throw(TypeError);
expect(() => stmt1.pluck(false)).to.throw(TypeError);
expect(() => stmt2.pluck(false)).to.throw(TypeError);
}

@@ -107,32 +103,32 @@ expect(i).to.equal(10);

it('should close the iterator when throwing in a for-of loop', function () {
var err = new Error('foobar');
var stmt = db.prepare("SELECT * FROM entries");
var iterator = stmt.iterate();
var count = 0;
expect(function () {
for (var row of iterator) {++count; throw err;}
const err = new Error('foobar');
const stmt = db.prepare("SELECT * FROM entries");
const iterator = stmt.iterate();
let count = 0;
expect(() => {
for (const row of iterator) { ++count; throw err; }
}).to.throw(err);
expect(count).to.equal(1);
expect(iterator.next()).to.deep.equal({value: undefined, done: true});
for (var row of iterator) {++count;}
expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
for (const row of iterator) ++count;
expect(count).to.equal(1);
for (var row of stmt.iterate()) {++count;}
for (const row of stmt.iterate()) ++count;
expect(count).to.equal(11);
});
it('should close the iterator when using break in a for-of loop', function () {
var stmt = db.prepare("SELECT * FROM entries");
var iterator = stmt.iterate();
var count = 0;
for (var row of iterator) {++count; break;}
const stmt = db.prepare("SELECT * FROM entries");
const iterator = stmt.iterate();
let count = 0;
for (const row of iterator) { ++count; break; }
expect(count).to.equal(1);
expect(iterator.next()).to.deep.equal({value: undefined, done: true});
for (var row of iterator) {++count;}
expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
for (const row of iterator) ++count;
expect(count).to.equal(1);
for (var row of stmt.iterate()) {++count;}
for (const row of stmt.iterate()) ++count;
expect(count).to.equal(11);
});
it('should return an empty iterator when no rows were found', function () {
var stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
expect(stmt.iterate().next()).to.deep.equal({value: undefined, done: true});
for (var data of stmt.pluck().iterate()) {
const stmt = db.prepare("SELECT * FROM entries WHERE b == 999");
expect(stmt.iterate().next()).to.deep.equal({ value: undefined, done: true });
for (const data of stmt.pluck().iterate()) {
throw new Error('This callback should not have been invoked');

@@ -142,38 +138,18 @@ }

it('should not allow other database operations to execute while open', function () {
var stmt1 = db.prepare('SELECT * FROM entries');
var stmt2 = db.prepare('CREATE TABLE numbers (number INTEGER)');
var trans = db.transaction(['CREATE TABLE numbers (number INTEGER)']);
var count = 0;
for (var row of db.prepare('SELECT * FROM entries').iterate()) {
const stmt1 = db.prepare('SELECT * FROM entries');
const stmt2 = db.prepare('CREATE TABLE numbers (number INTEGER)');
const trans = db.transaction(['CREATE TABLE numbers (number INTEGER)']);
let count = 0;
for (const row of db.prepare('SELECT * FROM entries').iterate()) {
++count;
expect(function () {
db.close();
}).to.throw(TypeError);
expect(function () {
db.pragma('cache_size');
}).to.throw(TypeError);
expect(function () {
db.checkpoint();
}).to.throw(TypeError);
expect(function () {
db.prepare('SELECT * FROM entries');
}).to.throw(TypeError);
expect(function () {
db.transaction(['CREATE TABLE numbers (number INTEGER)']);
}).to.throw(TypeError);
expect(function () {
stmt1.get();
}).to.throw(TypeError);
expect(function () {
stmt1.all();
}).to.throw(TypeError);
expect(function () {
stmt1.iterate();
}).to.throw(TypeError);
expect(function () {
stmt2.run();
}).to.throw(TypeError);
expect(function () {
trans.run();
}).to.throw(TypeError);
expect(() => db.close()).to.throw(TypeError);
expect(() => db.pragma('cache_size')).to.throw(TypeError);
expect(() => db.checkpoint()).to.throw(TypeError);
expect(() => db.prepare('SELECT * FROM entries')).to.throw(TypeError);
expect(() => db.transaction(['CREATE TABLE numbers (number INTEGER)'])).to.throw(TypeError);
expect(() => stmt1.get()).to.throw(TypeError);
expect(() => stmt1.all()).to.throw(TypeError);
expect(() => stmt1.iterate()).to.throw(TypeError);
expect(() => stmt2.run()).to.throw(TypeError);
expect(() => trans.run()).to.throw(TypeError);
}

@@ -183,71 +159,71 @@ expect(count).to.equal(10);

it('should allow database operations after closing the iterator', function () {
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
var stmt = db.prepare("SELECT * FROM entries");
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
const stmt = db.prepare("SELECT * FROM entries");
db.prepare('SELECT 555');
var iterator = stmt.iterate();
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({value: row, done: false});
const iterator = stmt.iterate();
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({ value: row, done: false });
row.b += 1;
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({value: row, done: false});
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({ value: row, done: false });
row.b += 1;
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({value: row, done: false});
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(iterator.return()).to.deep.equal({value: undefined, done: true});
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
expect(iterator.next()).to.deep.equal({ value: row, done: false });
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
db.prepare('SELECT 555');
expect(iterator.next()).to.deep.equal({value: undefined, done: true});
expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
db.prepare('SELECT 555');
expect(iterator.return()).to.deep.equal({value: undefined, done: true});
expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
db.prepare('SELECT 555');
expect(iterator.next()).to.deep.equal({value: undefined, done: true});
expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
db.prepare('SELECT 555');
});
it('should accept bind parameters', function () {
var row = {a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: null};
var SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
var SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
const SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
const SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';
shouldHave(SQL1, row, ['foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null])
shouldHave(SQL1, row, [['foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null]])
shouldHave(SQL1, row, [['foo', 1], [3.14], bufferOfSize(4).fill(0xdd), [,]])
shouldHave(SQL2, row, [{a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd), e: undefined}])
shouldHave(SQL1, row, ['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null])
shouldHave(SQL1, row, [['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]])
shouldHave(SQL1, row, [['foo', 1], [3.14], Buffer.alloc(4).fill(0xdd), [,]])
shouldHave(SQL2, row, [{ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: undefined }])
for (var data of db.prepare(SQL2).iterate({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xaa), e: undefined})) {
for (const data of db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xaa), e: undefined })) {
throw new Error('This callback should not have been invoked');
}
expect(function () {
db.prepare(SQL2).iterate(row, function () {});
}).to.throw(TypeError);
expect(() =>
db.prepare(SQL2).iterate(row, () => {})
).to.throw(TypeError);
expect(function () {
db.prepare(SQL2).iterate({a: 'foo', b: 1, c: 3.14, d: bufferOfSize(4).fill(0xdd)});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd) })
).to.throw(RangeError);
expect(function () {
db.prepare(SQL1).iterate();
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL1).iterate()
).to.throw(RangeError);
expect(function () {
db.prepare(SQL2).iterate();
}).to.throw(TypeError);
expect(() =>
db.prepare(SQL2).iterate()
).to.throw(TypeError);
expect(function () {
db.prepare(SQL2).iterate(row, {});
}).to.throw(TypeError);
expect(() =>
db.prepare(SQL2).iterate(row, {})
).to.throw(TypeError);
expect(function () {
db.prepare(SQL2).iterate({});
}).to.throw(RangeError);
expect(() =>
db.prepare(SQL2).iterate({})
).to.throw(RangeError);
db.prepare(SQL1).iterate('foo', 1, 3.14, bufferOfSize(4).fill(0xdd), null).return();
expect(function () {
db.prepare(SQL1).iterate('foo', 1, new (function(){})(), bufferOfSize(4).fill(0xdd), null);
}).to.throw(TypeError);
db.prepare(SQL1).iterate('foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null).return();
expect(() =>
db.prepare(SQL1).iterate('foo', 1, new (function(){})(), Buffer.alloc(4).fill(0xdd), null)
).to.throw(TypeError);
function shouldHave(SQL, desiredData, args) {
var i = 0;
var stmt = db.prepare(SQL);
for (var data of stmt.iterate.apply(stmt, args)) {
let i = 0;
const stmt = db.prepare(SQL);
for (const data of stmt.iterate(...args)) {
desiredData.b = ++i;

@@ -260,5 +236,1 @@ expect(data).to.deep.equal(desiredData);

});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Statement#bind()', function () {
it('should permanently bind the given parameters', function () {
db.prepare('CREATE TABLE entries (a TEXT, b INTEGER, c BLOB)').run();
var stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
var buffer = bufferOfSize(4).fill(0xdd);
const stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
const buffer = Buffer.alloc(4).fill(0xdd);
stmt.bind('foobar', 25, buffer)

@@ -19,4 +15,4 @@ stmt.run();

stmt.run();
var row1 = db.prepare('SELECT * FROM entries WHERE rowid=1').get();
var row2 = db.prepare('SELECT * FROM entries WHERE rowid=2').get();
const row1 = db.prepare('SELECT * FROM entries WHERE rowid=1').get();
const row2 = db.prepare('SELECT * FROM entries WHERE rowid=2').get();
expect(row1.a).to.equal(row2.a);

@@ -27,37 +23,37 @@ expect(row1.b).to.equal(row2.b);

it('should not allow you to bind temporary parameters afterwards', function () {
var stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
var buffer = bufferOfSize(4).fill(0xdd);
const stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
const buffer = Buffer.alloc(4).fill(0xdd);
stmt.bind('foobar', 25, buffer)
expect(function () {stmt.run(null);}).to.throw(TypeError);
expect(function () {stmt.run(buffer);}).to.throw(TypeError);
expect(function () {stmt.run('foobar', 25, buffer);}).to.throw(TypeError);
expect(() => stmt.run(null)).to.throw(TypeError);
expect(() => stmt.run(buffer)).to.throw(TypeError);
expect(() => stmt.run('foobar', 25, buffer)).to.throw(TypeError);
});
it('should throw an exception when invoked twice on the same statement', function () {
var stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
let stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
stmt.bind('foobar', 25, null);
expect(function () {stmt.bind('foobar', 25, null);}).to.throw(TypeError);
expect(function () {stmt.bind();}).to.throw(TypeError);
expect(() => stmt.bind('foobar', 25, null)).to.throw(TypeError);
expect(() => stmt.bind()).to.throw(TypeError);
stmt = db.prepare('SELECT * FROM entries');
stmt.bind();
expect(function () {stmt.bind();}).to.throw(TypeError);
expect(() => stmt.bind()).to.throw(TypeError);
});
it('should throw an exception when invalid parameters are given', function () {
var stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
let stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
expect(function () {
stmt.bind('foo', 25);
}).to.throw(RangeError);
expect(() =>
stmt.bind('foo', 25)
).to.throw(RangeError);
expect(function () {
stmt.bind('foo', 25, null, null);
}).to.throw(RangeError);
expect(() =>
stmt.bind('foo', 25, null, null)
).to.throw(RangeError);
expect(function () {
stmt.bind('foo', new Number(25), null);
}).to.throw(TypeError);
expect(() =>
stmt.bind('foo', new Number(25), null)
).to.throw(TypeError);
expect(function () {
stmt.bind();
}).to.throw(RangeError);
expect(() =>
stmt.bind()
).to.throw(RangeError);

@@ -68,34 +64,30 @@ stmt.bind('foo', 25, null);

expect(function () {
stmt.bind({a: '123'});
}).to.throw(RangeError);
expect(() =>
stmt.bind({ a: '123' })
).to.throw(RangeError);
expect(function () {
stmt.bind({a: '123', 1: null});
}).to.throw(RangeError);
expect(() =>
stmt.bind({ a: '123', 1: null })
).to.throw(RangeError);
expect(function () {
stmt.bind({a: '123'}, null, null);
}).to.throw(RangeError);
expect(() =>
stmt.bind({ a: '123' }, null, null)
).to.throw(RangeError);
stmt.bind({a: '123'}, null);
stmt.bind({ a: '123' }, null);
stmt = db.prepare('INSERT INTO entries VALUES (@a, @a, ?)');
stmt.bind({a: '123', b: null}, null);
stmt.bind({ a: '123', b: null }, null);
});
it('should propagate exceptions thrown while accessing array/object members', function () {
var arr = [22];
var obj = {};
var err = new TypeError('foobar');
Object.defineProperty(arr, '0', {get: function () {throw err;}})
Object.defineProperty(obj, 'baz', {get: function () {throw err;}})
var stmt1 = db.prepare('SELECT ?');
var stmt2 = db.prepare('SELECT @baz');
expect(function () {stmt1.bind(arr);}).to.throw(err);
expect(function () {stmt2.bind(obj);}).to.throw(err);
const arr = [22];
const obj = {};
const err = new TypeError('foobar');
Object.defineProperty(arr, '0', { get: () => { throw err; } })
Object.defineProperty(obj, 'baz', { get: () => { throw err; } })
const stmt1 = db.prepare('SELECT ?');
const stmt2 = db.prepare('SELECT @baz');
expect(() => stmt1.bind(arr)).to.throw(err);
expect(() => stmt2.bind(obj)).to.throw(err);
});
});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Transaction#run()', function () {
it('should work with CREATE TABLE', function () {
var trans = db.transaction(['CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB)']);
var info = trans.run();
const trans = db.transaction(['CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB)']);
const info = trans.run();
expect(info.changes).to.equal(0);

@@ -18,4 +14,4 @@ expect(info.lastInsertROWID).to.equal(0);

it('should work with INSERT INTO', function () {
var trans = db.transaction(["INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')"]);
var info = trans.run();
let trans = db.transaction(["INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')"]);
let info = trans.run();
expect(info.changes).to.equal(1);

@@ -34,11 +30,11 @@ expect(info.lastInsertROWID).to.equal(1);

it('should work with UPDATE', function () {
var trans = db.transaction(["UPDATE entries SET a='bar' WHERE rowid=1"]);
const trans = db.transaction(["UPDATE entries SET a='bar' WHERE rowid=1"]);
expect(trans.run().changes).to.equal(1);
});
it('should work with DELETE FROM', function () {
var trans = db.transaction(["DELETE FROM entries WHERE a='foo'"]);
let trans = db.transaction(["DELETE FROM entries WHERE a='foo'"]);
expect(trans.run().changes).to.equal(3);
trans = db.transaction(["INSERT INTO entries VALUES ('foo', 25, 3.14, x'1133ddff')"]);
var info = trans.run();
const info = trans.run();
expect(info.changes).to.equal(1);

@@ -48,3 +44,3 @@ expect(info.lastInsertROWID).to.equal(2);

it('should work with DROP TABLE', function () {
var trans = db.transaction(["DROP TABLE entries"]);
const trans = db.transaction(["DROP TABLE entries"]);
expect(trans.run().changes).to.equal(0);

@@ -58,3 +54,3 @@ });

"INSERT INTO people VALUES (NULL, 'bob')",
"INSERT INTO people VALUES (NULL, 'sarah')"
"INSERT INTO people VALUES (NULL, 'sarah')",
]).run();

@@ -64,17 +60,17 @@ db.transaction([

"INSERT INTO ages VALUES (30, 2)",
"INSERT INTO ages VALUES (35, 2)"
"INSERT INTO ages VALUES (35, 2)",
]).run();
var trans = db.transaction([
let trans = db.transaction([
"INSERT INTO ages VALUES (40, 1)",
"INSERT INTO ages VALUES (30, 3)"
"INSERT INTO ages VALUES (30, 3)",
]);
expect(db.inTransaction).to.equal(false);
expect(function () {trans.run();}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
expect(() => trans.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_FOREIGNKEY');
expect(db.inTransaction).to.equal(false);
trans = db.transaction([
"INSERT INTO ages VALUES (40, 1)",
"INSERT INTO ages VALUES (30, NULL)"
"INSERT INTO ages VALUES (30, NULL)",
]);
expect(db.inTransaction).to.equal(false);
expect(function () {trans.run();}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_NOTNULL');
expect(() => trans.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_NOTNULL');
expect(db.inTransaction).to.equal(false);

@@ -86,3 +82,3 @@ expect(db.prepare('SELECT * FROM ages WHERE age==35').get()).to.not.be.undefined;

"INSERT INTO ages VALUES (40, 1)",
"INSERT INTO ages VALUES (30, 2)"
"INSERT INTO ages VALUES (30, 2)",
]).run();

@@ -94,96 +90,97 @@ expect(db.inTransaction).to.equal(false);

it('should not count changes from indirect mechanisms', function () {
var trans = db.transaction(["UPDATE people SET id=55 WHERE id=2"]);
const trans = db.transaction(["UPDATE people SET id=55 WHERE id=2"]);
expect(trans.run().changes).to.equal(1);
});
it('should count accurate DELETE changes when a dropped table has side effects', function () {
var trans = db.transaction(["DROP TABLE people"]);
const trans = db.transaction(["DROP TABLE people"]);
expect(trans.run().changes).to.equal(2);
});
it('should obey the restrictions of readonly mode', function () {
var db2 = new Database(db.name, {readonly: true});
var trans = db2.transaction(['CREATE TABLE people (name TEXT)']);
expect(function () {trans.run()}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
const db2 = new Database(db.name, { readonly: true });
const trans = db2.transaction(['CREATE TABLE people (name TEXT)']);
expect(() => trans.run()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_READONLY');
});
it('should accept bind parameters', function () {
db.transaction(["CREATE TABLE entries (a TEXT CHECK(typeof(a)=='text'), b INTEGER CHECK(typeof(b)=='integer' OR typeof(b)=='real'), c REAL CHECK(typeof(c)=='real' OR typeof(c)=='integer'), d BLOB CHECK(typeof(d)=='blob'))"]).run();
db.transaction(["CREATE TABLE entries (a TEXT CHECK(typeof(a)=='text'), b INTEGER CHECK(typeof(b)=='integer' OR typeof(b)=='real'), c REAL CHECK(typeof(c)=='real' OR typeof(c)=='integer'), d BLOB CHECK(typeof(d)=='blob'))"])
.run();
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, 25, bufferOfSize(8).fill(0xdd), 'foo', 25, 25, bufferOfSize(8).fill(0xdd));
.run('foo', 25, 25, Buffer.alloc(8).fill(0xdd), 'foo', 25, 25, Buffer.alloc(8).fill(0xdd));
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run(['foo', 25, 25, bufferOfSize(8).fill(0xdd), 'foo', 25, 25, bufferOfSize(8).fill(0xdd)]);
.run(['foo', 25, 25, Buffer.alloc(8).fill(0xdd), 'foo', 25, 25, Buffer.alloc(8).fill(0xdd)]);
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run(['foo', 25], [25], bufferOfSize(8).fill(0xdd), ['foo', 25, 25, bufferOfSize(8).fill(0xdd)]);
.run(['foo', 25], [25], Buffer.alloc(8).fill(0xdd), ['foo', 25, 25, Buffer.alloc(8).fill(0xdd)]);
db.transaction(['INSERT INTO entries VALUES (@a, @b, @c, @d)', 'INSERT INTO entries VALUES (@a, @b, @c, @d)'])
.run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
.run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.transaction(['INSERT INTO entries VALUES ($a, $b, $c, $d)', 'INSERT INTO entries VALUES ($a, $b, $c, $d)'])
.run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
.run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.transaction(['INSERT INTO entries VALUES (:a, :b, :c, :d)', 'INSERT INTO entries VALUES (:a, :b, :c, :d)'])
.run({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
.run({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
db.transaction(['INSERT INTO entries VALUES (?, @a, @a, ?)', 'INSERT INTO entries VALUES (?, @a, @a, ?)'])
.run({a: 25}, ['foo'], [bufferOfSize(8).fill(0xdd), 'foo'], bufferOfSize(8).fill(0xdd));
.run({ a: 25 }, ['foo'], [Buffer.alloc(8).fill(0xdd), 'foo'], Buffer.alloc(8).fill(0xdd));
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, @a, @a, ?)', 'INSERT INTO entries VALUES (?, @a, @a, ?)'])
.run({a: 25}, ['foo'], bufferOfSize(8).fill(0xdd), 'foo', bufferOfSize(8).fill(0xdd), bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
.run({ a: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd), 'foo', Buffer.alloc(8).fill(0xdd), Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, @a, @a, ?)', 'INSERT INTO entries VALUES (?, @a, @a, ?)'])
.run({a: 25}, ['foo'], bufferOfSize(8).fill(0xdd), 'foo');
}).to.throw(RangeError);
.run({ a: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd), 'foo')
).to.throw(RangeError);
db.transaction(['INSERT INTO entries VALUES (?, @a, @a, ?)', 'INSERT INTO entries VALUES (?, @a, @a, ?)'])
.run({a: 25, c: 25}, ['foo'], bufferOfSize(8).fill(0xdd), ['foo'], bufferOfSize(8).fill(0xdd));
.run({ a: 25, c: 25 }, ['foo'], Buffer.alloc(8).fill(0xdd), ['foo'], Buffer.alloc(8).fill(0xdd));
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, @a, @a, ?)'])
.run({}, ['foo'], bufferOfSize(8).fill(0xdd), ['foo'], bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
.run({}, ['foo'], Buffer.alloc(8).fill(0xdd), ['foo'], Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run(25, 'foo', 25, bufferOfSize(8).fill(0xdd), 'foo', 25, 25, bufferOfSize(8).fill(0xdd));
}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_CHECK');
.run(25, 'foo', 25, Buffer.alloc(8).fill(0xdd), 'foo', 25, 25, Buffer.alloc(8).fill(0xdd))
).to.throw(Database.SqliteError).with.property('code', 'SQLITE_CONSTRAINT_CHECK');
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, 25, bufferOfSize(8).fill(0xdd), 'foo', 25, 25, bufferOfSize(8).fill(0xdd), {foo: 'foo'});
.run('foo', 25, 25, Buffer.alloc(8).fill(0xdd), 'foo', 25, 25, Buffer.alloc(8).fill(0xdd), { foo: 'foo' });
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, 25, bufferOfSize(8).fill(0xdd), 'foo', 25, 25, bufferOfSize(8).fill(0xdd), {});
.run('foo', 25, 25, Buffer.alloc(8).fill(0xdd), 'foo', 25, 25, Buffer.alloc(8).fill(0xdd), {});
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, 25, {4: bufferOfSize(8).fill(0xdd)});
}).to.throw(RangeError);
.run('foo', 25, 25, { 4: Buffer.alloc(8).fill(0xdd) })
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run();
}).to.throw(RangeError);
.run()
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run({length: 4, 0: 'foo', 1: 25, 2: 25, 3: bufferOfSize(8).fill(0xdd)});
}).to.throw(RangeError);
.run({ length: 4, 0: 'foo', 1: 25, 2: 25, 3: Buffer.alloc(8).fill(0xdd) })
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, new Number(25), bufferOfSize(8).fill(0xdd));
}).to.throw(TypeError);
.run('foo', 25, new Number(25), Buffer.alloc(8).fill(0xdd))
).to.throw(TypeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', {low: 25, high: 25}, 25, bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
.run('foo', { low: 25, high: 25 }, 25, Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);
expect(function () {
expect(() =>
db.transaction(['INSERT INTO entries VALUES (?, ?, ?, ?)', "INSERT INTO entries VALUES ('foo', 25, 25, x'dddddddd')", 'INSERT INTO entries VALUES (?, ?, ?, ?)'])
.run('foo', 25, 25, bufferOfSize(8).fill(0xdd));
}).to.throw(RangeError);
.run('foo', 25, 25, Buffer.alloc(8).fill(0xdd))
).to.throw(RangeError);

@@ -194,12 +191,13 @@ function Foo() {

this.c = 25;
this.d = bufferOfSize(8).fill(0xdd);
this.d = Buffer.alloc(8).fill(0xdd);
}
expect(function () {
db.transaction(['INSERT INTO entries VALUES (@a, @b, @c, @d)', 'INSERT INTO entries VALUES (@a, @b, @c, @d)']).run(new Foo);
}).to.throw(TypeError);
expect(() =>
db.transaction(['INSERT INTO entries VALUES (@a, @b, @c, @d)', 'INSERT INTO entries VALUES (@a, @b, @c, @d)'])
.run(new Foo)
).to.throw(TypeError);
var i = 0;
var row;
while (row = db.prepare('SELECT * FROM entries WHERE rowid=' + ++i).get()) {
expect(row).to.deep.equal({a: 'foo', b: 25, c: 25, d: bufferOfSize(8).fill(0xdd)});
let i = 0;
let row;
while (row = db.prepare(`SELECT * FROM entries WHERE rowid=${++i}`).get()) {
expect(row).to.deep.equal({ a: 'foo', b: 25, c: 25, d: Buffer.alloc(8).fill(0xdd) });
}

@@ -209,5 +207,1 @@ expect(i).to.equal(21);

});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}
'use strict';
var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
});
describe('Transaction#bind()', function () {
it('should permanently bind the given parameters', function () {
db.transaction(['CREATE TABLE entries (a TEXT, b INTEGER, c BLOB)']).run();
var trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
var buffer = bufferOfSize(4).fill(0xdd);
const trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
const buffer = Buffer.alloc(4).fill(0xdd);
trans.bind('foobar', 25, buffer)

@@ -19,4 +15,4 @@ trans.run();

trans.run();
var row1 = db.prepare('SELECT * FROM entries WHERE rowid=1').get();
var row2 = db.prepare('SELECT * FROM entries WHERE rowid=2').get();
const row1 = db.prepare('SELECT * FROM entries WHERE rowid=1').get();
const row2 = db.prepare('SELECT * FROM entries WHERE rowid=2').get();
expect(row1.a).to.equal(row2.a);

@@ -27,37 +23,37 @@ expect(row1.b).to.equal(row2.b);

it('should not allow you to bind temporary parameters afterwards', function () {
var trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
var buffer = bufferOfSize(4).fill(0xdd);
const trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
const buffer = Buffer.alloc(4).fill(0xdd);
trans.bind('foobar', 25, buffer)
expect(function () {trans.run(null);}).to.throw(TypeError);
expect(function () {trans.run(buffer);}).to.throw(TypeError);
expect(function () {trans.run('foobar', 25, buffer);}).to.throw(TypeError);
expect(() => trans.run(null)).to.throw(TypeError);
expect(() => trans.run(buffer)).to.throw(TypeError);
expect(() => trans.run('foobar', 25, buffer)).to.throw(TypeError);
});
it('should throw an exception when invoked twice on the same transaction', function () {
var trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
let trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
trans.bind('foobar', 25, null);
expect(function () {trans.bind('foobar', 25, null);}).to.throw(TypeError);
expect(function () {trans.bind();}).to.throw(TypeError);
expect(() => trans.bind('foobar', 25, null)).to.throw(TypeError);
expect(() => trans.bind()).to.throw(TypeError);
trans = db.transaction(["INSERT INTO entries VALUES ('foobar', 25, null)"]);
trans.bind();
expect(function () {trans.bind();}).to.throw(TypeError);
expect(() => trans.bind()).to.throw(TypeError);
});
it('should throw an exception when invalid parameters are given', function () {
var trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
let trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
expect(function () {
trans.bind('foo', 25);
}).to.throw(RangeError);
expect(() =>
trans.bind('foo', 25)
).to.throw(RangeError);
expect(function () {
trans.bind('foo', 25, null, null);
}).to.throw(RangeError);
expect(() =>
trans.bind('foo', 25, null, null)
).to.throw(RangeError);
expect(function () {
trans.bind('foo', new Number(25), null);
}).to.throw(TypeError);
expect(() =>
trans.bind('foo', new Number(25), null)
).to.throw(TypeError);
expect(function () {
trans.bind();
}).to.throw(RangeError);
expect(() =>
trans.bind()
).to.throw(RangeError);

@@ -68,34 +64,30 @@ trans.bind('foo', 25, null);

expect(function () {
trans.bind({a: '123'});
}).to.throw(RangeError);
expect(() =>
trans.bind({ a: '123' })
).to.throw(RangeError);
expect(function () {
trans.bind({a: '123', 1: null});
}).to.throw(RangeError);
expect(() =>
trans.bind({ a: '123', 1: null })
).to.throw(RangeError);
expect(function () {
trans.bind({a: '123'}, null, null);
}).to.throw(RangeError);
expect(() =>
trans.bind({ a: '123' }, null, null)
).to.throw(RangeError);
trans.bind({a: '123'}, null);
trans.bind({ a: '123' }, null);
trans = db.transaction(['INSERT INTO entries VALUES (@a, @a, ?)']);
trans.bind({a: '123', b: null}, null);
trans.bind({ a: '123', b: null }, null);
});
it('should propagate exceptions thrown while accessing array/object members', function () {
var arr = [22];
var obj = {};
var err = new TypeError('foobar');
Object.defineProperty(arr, '0', {get: function () {throw err;}})
Object.defineProperty(obj, 'baz', {get: function () {throw err;}})
var trans1 = db.transaction(['INSERT INTO entries VALUES (NULL, ?, NULL)']);
var trans2 = db.transaction(['INSERT INTO entries VALUES (NULL, @baz, NULL)']);
expect(function () {trans1.bind(arr);}).to.throw(err);
expect(function () {trans2.bind(obj);}).to.throw(err);
const arr = [22];
const obj = {};
const err = new TypeError('foobar');
Object.defineProperty(arr, '0', { get: () => { throw err; } })
Object.defineProperty(obj, 'baz', { get: () => { throw err; } })
const trans1 = db.transaction(['INSERT INTO entries VALUES (NULL, ?, NULL)']);
const trans2 = db.transaction(['INSERT INTO entries VALUES (NULL, @baz, NULL)']);
expect(() => trans1.bind(arr)).to.throw(err);
expect(() => trans2.bind(obj)).to.throw(err);
});
});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}

@@ -1,11 +0,12 @@

var expect = require('chai').expect;
var fs = require('fs');
var Database = require('../.');
var db1, db2;
const { expect } = require('chai');
const fs = require('fs');
const Database = require('../.');
const util = require('./util');
let db1 = new Database(util.next());
let db2 = new Database(util.next());
before(function () {
db1 = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
db1.pragma('journal_mode = WAL');
db1.prepare('CREATE TABLE entries (a TEXT, b INTEGER)').run();
db2 = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '2.db');
db2.pragma('journal_mode = WAL');

@@ -16,8 +17,8 @@ db2.prepare('CREATE TABLE entries (a TEXT, b INTEGER)').run();

function fillWall(count, expectation) {
[db1, db2].forEach(function (db) {
var size1, size2;
for (var i=0; i<count; ++i) {
size1 = fs.statSync(db.name + '-wal').size;
[db1, db2].forEach((db) => {
let size1, size2;
for (let i = 0; i < count; ++i) {
size1 = fs.statSync(`${db.name}-wal`).size;
db.prepare('INSERT INTO entries VALUES (?, ?)').run('bar', 999);
size2 = fs.statSync(db.name + '-wal').size;
size2 = fs.statSync(`${db.name}-wal`).size;
expectation(size2, size1, db);

@@ -31,8 +32,8 @@ }

specify('every insert should increase the size of the WAL file', function () {
fillWall(10, function (b, a) {expect(b).to.be.above(a);});
fillWall(10, (b, a) => expect(b).to.be.above(a));
});
specify('inserts after a checkpoint should NOT increase the size of the WAL file', function () {
db1.prepare('ATTACH \'' + db2.name + '\' AS foobar').run();
db1.prepare(`ATTACH \'${db2.name}\' AS foobar`).run();
expect(db1.checkpoint()).to.deep.equal(db1);
fillWall(10, function (b, a) {expect(b).to.equal(a);});
fillWall(10, (b, a) => expect(b).to.equal(a));
});

@@ -49,13 +50,10 @@ });

db2.prepare('CREATE TABLE _unused (a TEXT, b INTEGER)').run();
fillWall(10, function (b, a) {expect(b).to.be.above(a);});
fillWall(10, (b, a) => expect(b).to.be.above(a));
});
specify('inserts after a checkpoint should NOT increase the size of the WAL file', function () {
db1.prepare('ATTACH \'' + db2.name + '\' AS bazqux').run();
db1.prepare(`ATTACH \'${db2.name}\' AS bazqux`).run();
expect(db1.checkpoint('bazqux')).to.equal(db1);
fillWall(10, function (b, a, db) {
if (db === db1) {
expect(b).to.be.above(a);
} else {
expect(b).to.be.equal(a);
}
fillWall(10, (b, a, db) => {
if (db === db1) expect(b).to.be.above(a);
else expect(b).to.be.equal(a);
});

@@ -62,0 +60,0 @@ });

@@ -1,23 +0,13 @@

var expect = require('chai').expect;
var fs = require('fs');
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
const { expect } = require('chai');
const fs = require('fs');
const Database = require('../.');
const util = require('./util');
describe('Database#close()', function () {
it('should prevent statements and transactions from operating', function () {
var db = new Database(util.next());
const db = new Database(util.next());
db.prepare('CREATE TABLE people (name TEXT)').run();
var stmt1 = db.prepare('SELECT * FROM people');
var stmt2 = db.prepare("INSERT INTO people VALUES ('foobar')");
var trans = db.transaction(["INSERT INTO people VALUES ('foobar')"]);
const stmt1 = db.prepare('SELECT * FROM people');
const stmt2 = db.prepare("INSERT INTO people VALUES ('foobar')");
const trans = db.transaction(["INSERT INTO people VALUES ('foobar')"]);

@@ -35,13 +25,13 @@ db.prepare('SELECT * FROM people').bind();

expect(function () {stmt1.bind();}).to.throw(TypeError);
expect(function () {stmt2.bind();}).to.throw(TypeError);
expect(function () {trans.bind();}).to.throw(TypeError);
expect(function () {stmt1.get();}).to.throw(TypeError);
expect(function () {stmt1.all();}).to.throw(TypeError);
expect(function () {stmt1.iterate();}).to.throw(TypeError);
expect(function () {stmt2.run();}).to.throw(TypeError);
expect(function () {trans.run();}).to.throw(TypeError);
expect(() => stmt1.bind()).to.throw(TypeError);
expect(() => stmt2.bind()).to.throw(TypeError);
expect(() => trans.bind()).to.throw(TypeError);
expect(() => stmt1.get()).to.throw(TypeError);
expect(() => stmt1.all()).to.throw(TypeError);
expect(() => stmt1.iterate()).to.throw(TypeError);
expect(() => stmt2.run()).to.throw(TypeError);
expect(() => trans.run()).to.throw(TypeError);
});
it('should delete the database\'s associated temporary files', function () {
var db = new Database(util.next());
const db = new Database(util.next());
fs.accessSync(util.current());

@@ -51,3 +41,3 @@ db.pragma('journal_mode = WAL');

db.prepare('INSERT INTO people VALUES (?)').run('foobar');
fs.accessSync(util.current() + '-wal');
fs.accessSync(`${util.current()}-wal`);

@@ -57,6 +47,6 @@ db.close();

fs.accessSync(util.current());
expect(function () {
fs.accessSync(util.current() + '-wal');
}).to.throw();
expect(() =>
fs.accessSync(util.current() + '-wal')
).to.throw();
});
});

@@ -1,7 +0,6 @@

var expect = require('chai').expect;
var Database = require('../.');
var db;
const { expect } = require('chai');
const Database = require('../.');
const db = new Database(require('./util').next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.db');
db.prepare('CREATE TABLE data (x)').run();

@@ -19,6 +18,6 @@ db.prepare('CREATE TABLE empty (x)').run();

function register() {
expect(db.register.apply(db, arguments)).to.equal(db);
expect(db.register(...arguments)).to.equal(db);
}
function exec(SQL) {
return db.prepare('SELECT ' + SQL).pluck().get([].slice.call(arguments, 1));
function exec(SQL, ...args) {
return db.prepare(`SELECT ${SQL}`).pluck().get(args);
}

@@ -28,9 +27,9 @@

it('should throw if a function is not provided', function () {
expect(function () {db.register()}).to.throw(TypeError);
expect(function () {db.register(null)}).to.throw(TypeError);
expect(function () {db.register({})}).to.throw(TypeError);
expect(function () {db.register('foobar')}).to.throw(TypeError);
expect(() => db.register()).to.throw(TypeError);
expect(() => db.register(null)).to.throw(TypeError);
expect(() => db.register({})).to.throw(TypeError);
expect(() => db.register('foobar')).to.throw(TypeError);
});
it('should throw if the function name is empty', function () {
expect(function () {db.register(function () {})}).to.throw(TypeError);
expect(() => db.register(function () {})).to.throw(TypeError);
});

@@ -42,3 +41,3 @@ it('should register the given function', function () {

// numbers and strings
register(function b1(a, b, c) {return a + b + c;});
register(function b1(a, b, c) { return a + b + c; });
expect(exec('b1(?, ?, ?)', 2, 10, 50)).to.equal(62);

@@ -49,3 +48,3 @@ expect(exec('b1(?, ?, ?)', 2, 10, null)).to.equal(12);

// undefined is interpreted as null
register(function b2(a, b) {return null;});
register(function b2(a, b) { return null; });
register(function b3(a, b) {});

@@ -56,8 +55,8 @@ expect(exec('b2(?, ?)', 2, 10)).to.equal(null);

// buffers
register(function b4(a) {return a;});
var buffer = exec('b4(?)', bufferOfSize(8).fill(0xdd));
expect(buffer.equals(bufferOfSize(8).fill(0xdd))).to.be.ok;
register(function b4(a) { return a; });
const buffer = exec('b4(?)', Buffer.alloc(8).fill(0xdd));
expect(buffer.equals(Buffer.alloc(8).fill(0xdd))).to.be.ok;
// zero arguments
register(function b5() {return 12;});
register(function b5() { return 12; });
expect(exec('b5()')).to.equal(12);

@@ -67,17 +66,17 @@ });

register(function c1(a, b) {});
expect(function () {exec('c1()');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {exec('c1(?)', 4);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {exec('c1(?, ?, ?)', 4, 8, 3);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('c1()')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('c1(?)', 4)).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('c1(?, ?, ?)', 4, 8, 3)).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
exec('c1(?, ?)', 4, 8);
});
it('should accept a "name" option', function () {
register({name: 'd1'}, function (a, b) {return a - b;});
register({name: 'd2'}, function sdnfjlsd(a, b) {return a * b;});
register({ name: 'd1' }, function (a, b) { return a - b; });
register({ name: 'd2' }, function sdnfjlsd(a, b) { return a * b; });
expect(exec('d1(?, ?)', 2, 10)).to.equal(-8);
expect(exec('d2(?, ?)', 2, 10)).to.equal(20);
expect(function () {exec('sdnfjlsd(?, ?)', 2, 10);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('sdnfjlsd(?, ?)', 2, 10)).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
});
it('should accept a "varargs" option', function () {
register({varargs: true}, function f1() {
return [].slice.call(arguments).reduce(function (a, b) {return a * b;}, 1);
register({ varargs: true }, function f1(...args) {
return args.reduce((a, b) => a * b, 1);
});

@@ -90,33 +89,33 @@ expect(exec('f1()')).to.equal(1);

it('should throw if name is not a valid string', function () {
expect(function () {db.register({name: ''}, function () {})}).to.throw(TypeError);
expect(function () {db.register({name: 123}, function () {})}).to.throw(TypeError);
expect(function () {db.register({name: {}}, function xa1() {})}).to.throw(TypeError);
expect(function () {db.register({name: new String('abc')}, function xa2() {})}).to.throw(TypeError);
expect(() => db.register({ name: '' }, function () {})).to.throw(TypeError);
expect(() => db.register({ name: 123 }, function () {})).to.throw(TypeError);
expect(() => db.register({ name: {} }, function xa1() {})).to.throw(TypeError);
expect(() => db.register({ name: new String('abc') }, function xa2() {})).to.throw(TypeError);
});
it('should throw if function.length is not a positive integer', function () {
function length(n, fn) {
Object.defineProperty(fn, 'length', {value: n});
Object.defineProperty(fn, 'length', { value: n });
return fn;
}
expect(function () {db.register(length(-1, function xb1() {}))}).to.throw(TypeError);
expect(function () {db.register(length(1.2, function xb2() {}))}).to.throw(TypeError);
expect(function () {db.register(length(Infinity, function xb3() {}))}).to.throw(TypeError);
expect(function () {db.register(length(NaN, function xb4() {}))}).to.throw(TypeError);
expect(function () {db.register(length('2', function xb5() {}))}).to.throw(TypeError);
expect(() => db.register(length(-1, function xb1() {}))).to.throw(TypeError);
expect(() => db.register(length(1.2, function xb2() {}))).to.throw(TypeError);
expect(() => db.register(length(Infinity, function xb3() {}))).to.throw(TypeError);
expect(() => db.register(length(NaN, function xb4() {}))).to.throw(TypeError);
expect(() => db.register(length('2', function xb5() {}))).to.throw(TypeError);
});
it('should throw if function.length is larger than 127', function () {
function length(n, fn) {
Object.defineProperty(fn, 'length', {value: n});
Object.defineProperty(fn, 'length', { value: n });
return fn;
}
expect(function () {db.register(length(128, function xc1() {}))}).to.throw(RangeError);
expect(function () {db.register(length(0xe0000000f, function xc2() {}))}).to.throw(RangeError);
expect(() => db.register(length(128, function xc1() {}))).to.throw(RangeError);
expect(() => db.register(length(0xe0000000f, function xc2() {}))).to.throw(RangeError);
db.register(length(127, function ya1() {}));
});
it('should throw if the database is busy', function () {
var ranOnce = false;
for (var a of db.prepare('SELECT 2').pluck().iterate()) {
let ranOnce = false;
for (const a of db.prepare('SELECT 2').pluck().iterate()) {
expect(a).to.equal(2);
ranOnce = true;
expect(function () {db.register(function xd1() {});}).to.throw(TypeError);
expect(() => db.register(function xd1() {})).to.throw(TypeError);
}

@@ -127,8 +126,8 @@ expect(ranOnce).to.be.true;

it('should cause the database to become busy when executing the function', function () {
var ranOnce = false;
let ranOnce = false;
register(function g1() {
ranOnce = true;
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(function () {db.pragma('cache_size');}).to.throw(TypeError);
expect(function () {db.register(function xe1() {});}).to.throw(TypeError);
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
expect(() => db.pragma('cache_size')).to.throw(TypeError);
expect(() => db.register(function xe1() {})).to.throw(TypeError);
});

@@ -142,8 +141,8 @@ expect(exec('g1()')).to.equal(null);

it('should throw if the function returns an invalid value', function () {
register(function h1(a) {return {};});
expect(function () {exec('h1(?)', 42);}).to.throw(TypeError);
register(function h1(a) { return {}; });
expect(() => exec('h1(?)', 42)).to.throw(TypeError);
});
it('should propagate exceptions thrown in the registered function', function () {
function expectError(name, exception) {
register({name: name}, function () {throw exception;});
register({ name }, function () { throw exception; });
try {

@@ -159,3 +158,3 @@ exec(name + '()');

expectError('i2', new Error('baz'));
expectError('i3', {yup: 'ok'});
expectError('i3', { yup: 'ok' });
expectError('i4', 'foobarbazqux');

@@ -167,17 +166,17 @@ expectError('i5', '');

it('should close a statement iterator that caused its function to throw', function () {
var i = 0;
var err = new Error('foo');
register(function throwsIterator1(x) {if (++i >= 5) throw err; return x});
const err = new Error('foo');
let i = 0;
register(function throwsIterator1(x) { if (++i >= 5) throw err; return x; });
db.prepare('CREATE TABLE iterable (value INTEGER)').run();
db.prepare('INSERT INTO iterable WITH RECURSIVE temp(a) AS (SELECT 1 UNION ALL SELECT a * 2 FROM temp LIMIT 10) SELECT * FROM temp').run();
var iterator = db.prepare('SELECT throwsIterator1(value) FROM iterable').pluck().iterate();
var total = 0;
expect(function () {
for (var value of iterator) {
const iterator = db.prepare('SELECT throwsIterator1(value) FROM iterable').pluck().iterate();
let total = 0;
expect(() => {
for (const value of iterator) {
total += value;
expect(function () {db.prepare('SELECT throwsIterator1(value) FROM iterable');}).to.throw(TypeError);
expect(() => db.prepare('SELECT throwsIterator1(value) FROM iterable')).to.throw(TypeError);
}
}).to.throw(err);
expect(total).to.equal(1 + 2 + 4 + 8);
expect(iterator.next()).to.deep.equal({value: undefined, done: true});
expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
db.prepare('SELECT throwsIterator1(value) FROM iterable').pluck().iterate().return();

@@ -187,7 +186,7 @@ expect(total).to.equal(1 + 2 + 4 + 8);

it('should be able to register multiple functions with the same name', function () {
register(function ia1() {return 0;});
register(function ia1(a) {return 1;});
register(function ia1(a, b) {return 2;});
register(function ia1(a, b, c) {return 3;});
register(function ia1(a, b, c, d) {return 4;});
register(function ia1() { return 0; });
register(function ia1(a) { return 1; });
register(function ia1(a, b) { return 2; });
register(function ia1(a, b, c) { return 3; });
register(function ia1(a, b, c, d) { return 4; });
expect(exec('ia1()')).to.equal(0);

@@ -198,3 +197,3 @@ expect(exec('ia1(555)')).to.equal(1);

expect(exec('ia1(555, 555, 555, 555)')).to.equal(4);
register(function ia1(a, b) {return 'foobar';});
register(function ia1(a, b) { return 'foobar'; });
expect(exec('ia1()')).to.equal(0);

@@ -207,4 +206,4 @@ expect(exec('ia1(555)')).to.equal(1);

it('should not be able to affect bound buffers mid-query', function () {
var buffer = bufferOfSize(1024 * 8).fill(0xbb);
var ranOnce = false;
const buffer = Buffer.alloc(1024 * 8).fill(0xbb);
let ranOnce = false;
register(function j1() {

@@ -214,17 +213,17 @@ ranOnce = true;

});
var returned = exec('?, j1()', buffer);
const returned = exec('?, j1()', buffer);
expect(ranOnce).to.be.true;
expect(returned.equals(bufferOfSize(1024 * 8).fill(0xbb))).to.be.ok;
expect(returned.equals(Buffer.alloc(1024 * 8).fill(0xbb))).to.be.ok;
});
describe('should not affect external environment', function () {
specify('busy state', function () {
var ranOnce = false;
let ranOnce = false;
register(function k1(n) {
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
return n * 2;
});
for (var n of db.prepare('SELECT k1(555)').pluck().iterate()) {
for (const n of db.prepare('SELECT k1(555)').pluck().iterate()) {
ranOnce = true;
expect(n).to.equal(1110);
expect(function () {db.prepare('SELECT 555');}).to.throw(TypeError);
expect(() => db.prepare('SELECT 555')).to.throw(TypeError);
}

@@ -236,8 +235,8 @@ expect(ranOnce).to.be.true;

db.prepare('CREATE TABLE abcxyz (value INTEGER)').run();
var stmt = db.prepare('SELECT value FROM abcxyz');
const stmt = db.prepare('SELECT value FROM abcxyz');
db.prepare('DROP TABLE abcxyz').run();
var err = new Error('foobarbaz');
register(function m1() {throw err;});
expect(function () {db.prepare('SELECT m1()').get();}).to.throw(err);
try {stmt.get();} catch (ex) {
const err = new Error('foobarbaz');
register(function m1() { throw err; });
expect(() => db.prepare('SELECT m1()').get()).to.throw(err);
try { stmt.get(); } catch (ex) {
expect(ex).to.be.an.instanceof(Error);

@@ -256,3 +255,3 @@ expect(ex).to.not.equal(err);

register(function* zb1() {
yield function () {};
yield () => {};
});

@@ -262,91 +261,89 @@ });

function length(n) {
var fn = function () {};
Object.defineProperty(fn, 'length', {value: n});
const fn = () => {};
Object.defineProperty(fn, 'length', { value: n });
return fn;
}
expect(function () {register(function* zc1() {
expect(() => register(function* zc1() {
yield length(-1);
})}).to.throw(TypeError);
expect(function () {register(function* zc2() {
})).to.throw(TypeError);
expect(() => register(function* zc2() {
yield length(1.2);
})}).to.throw(TypeError);
expect(function () {register(function* zc3() {
})).to.throw(TypeError);
expect(() => register(function* zc3() {
yield length(Infinity);
})}).to.throw(TypeError);
expect(function () {register(function* zc4() {
})).to.throw(TypeError);
expect(() => register(function* zc4() {
yield length(NaN);
})}).to.throw(TypeError);
expect(function () {register(function* zc5() {
})).to.throw(TypeError);
expect(() => register(function* zc5() {
yield length('2');
})}).to.throw(TypeError);
})).to.throw(TypeError);
});
it('should throw if the yielded function.length is larger than 127', function () {
function length(n) {
var fn = function () {};
Object.defineProperty(fn, 'length', {value: n});
const fn = () => {};
Object.defineProperty(fn, 'length', { value: n });
return fn;
}
expect(function () {register(function* zd1() {
expect(() => register(function* zd1() {
yield length(128);
})}).to.throw(RangeError);
expect(function () {register(function* zd2() {
})).to.throw(RangeError);
expect(() => register(function* zd2() {
yield length(0xe0000000f);
})}).to.throw(RangeError);
register(function* zd3() {yield length(127);})
})).to.throw(RangeError);
register(function* zd3() { yield length(127); })
});
it('should propagate exceptions thrown while getting function.length', function () {
var err = new Error('foobar');
expect(function () {
const err = new Error('foobar');
expect(() =>
register(function* ze1() {
var fn = function () {};
Object.defineProperty(fn, 'length', {get: function () {
throw err;
}});
const fn = () => {};
Object.defineProperty(fn, 'length', { get: () => { throw err; } });
yield fn;
});
}).to.throw(err);
})
).to.throw(err);
});
it('should throw if the generator function never yields', function () {
expect(function () {register(function* zf1() {
expect(() => register(function* zf1() {
// no yield
})}).to.throw(TypeError);
})).to.throw(TypeError);
});
it('should throw if a non-function is yielded', function () {
expect(function () {register(function* zf1() {
expect(() => register(function* zf1() {
yield;
})}).to.throw(TypeError);
expect(function () {register(function* zf1() {
})).to.throw(TypeError);
expect(() => register(function* zf1() {
yield 123;
})}).to.throw(TypeError);
expect(function () {register(function* zf1() {
})).to.throw(TypeError);
expect(() => register(function* zf1() {
yield 'foobar';
})}).to.throw(TypeError);
expect(function () {register(function* zf1() {
yield {length: 0, name: ''};
})}).to.throw(TypeError);
})).to.throw(TypeError);
expect(() => register(function* zf1() {
yield { length: 0, name: '' };
})).to.throw(TypeError);
});
it('should throw if the generator function yields twice', function () {
expect(function () {register(function* zg1() {
var fn = function () {};
expect(() => register(function* zg1() {
const fn = () => {};
yield fn;
yield fn;
})}).to.throw(TypeError);
})).to.throw(TypeError);
});
it('should propagate exceptions thrown before yielding', function () {
var err = new Error('foobar');
expect(function () {
const err = new Error('foobar');
expect(() =>
register(function* zh1() {
throw err;
yield function () {};
});
}).to.throw(err);
yield () => {};
})
).to.throw(err);
});
it('should propagate exceptions thrown after yielding', function () {
var err = new Error('foobar');
expect(function () {
const err = new Error('foobar');
expect(() =>
register(function* zi1() {
yield function () {};
yield () => {};
throw err;
});
}).to.throw(err);
})
).to.throw(err);
});

@@ -356,18 +353,18 @@ });

it('should throw if the generator function never yields', function () {
var first = true;
let first = true;
register(function* zj1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
}
});
expect(function () {exec('zj1(x) FROM data');}).to.throw(TypeError);
expect(() => exec('zj1(x) FROM data')).to.throw(TypeError);
});
it('should throw if a non-function is yielded', function () {
function registerAggregate(name, value) {
var first = true;
register({name: name}, function* () {
let first = true;
register({ name }, function* () {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {

@@ -381,79 +378,77 @@ yield value;

registerAggregate('zk3', 'foobar');
registerAggregate('zk4', {length: 0, name: ''});
registerAggregate('zk4', { length: 0, name: '' });
registerAggregate('zk5', function (x) {});
expect(function () {exec('zk1(x) FROM data');}).to.throw(TypeError);
expect(function () {exec('zk2(x) FROM data');}).to.throw(TypeError);
expect(function () {exec('zk3(x) FROM data');}).to.throw(TypeError);
expect(function () {exec('zk4(x) FROM data');}).to.throw(TypeError);
expect(() => exec('zk1(x) FROM data')).to.throw(TypeError);
expect(() => exec('zk2(x) FROM data')).to.throw(TypeError);
expect(() => exec('zk3(x) FROM data')).to.throw(TypeError);
expect(() => exec('zk4(x) FROM data')).to.throw(TypeError);
exec('zk5(x) FROM data');
});
it('should throw if the generator function yields twice', function () {
var first = true;
let first = true;
register(function* zl1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {
yield function (x) {};
yield function (x) {};
yield (x) => {};
yield (x) => {};
}
});
expect(function () {exec('zl1(x) FROM data');}).to.throw(TypeError);
expect(() => exec('zl1(x) FROM data')).to.throw(TypeError);
});
it('should propagate exceptions thrown before yielding', function () {
var first = true;
var err = new Error('foobar');
let first = true;
const err = new Error('foobar');
register(function* zm1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {
throw err;
yield function (x) {};
yield (x) => {};
}
});
expect(function () {exec('zm1(x) FROM data');}).to.throw(err);
expect(() => exec('zm1(x) FROM data')).to.throw(err);
});
it('should propagate exceptions thrown after yielding', function () {
var first = true;
var err = new Error('foobar');
let first = true;
const err = new Error('foobar');
register(function* zma1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {
yield function (x) {};
yield (x) => {};
throw err;
}
});
expect(function () {exec('zma1(x) FROM data');}).to.throw(err);
expect(() => exec('zma1(x) FROM data')).to.throw(err);
});
it('should propagate exceptions thrown while getting function.length', function () {
var first = true;
var err = new Error('foobar');
let first = true;
const err = new Error('foobar');
register(function* zn1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {
var fn = function (x) {};
Object.defineProperty(fn, 'length', {get: function () {
throw err;
}});
const fn = (x) => {};
Object.defineProperty(fn, 'length', { get: () => { throw err; } });
yield fn;
}
});
expect(function () {exec('zn1(x) FROM data');}).to.throw(err);
expect(() => exec('zn1(x) FROM data')).to.throw(err);
});
it('should throw if the yielded function.length is inconsistent', function () {
var first = true;
let first = true;
register(function* zo1() {
if (first) {
first = false;
yield function (x) {};
yield (x) => {};
} else {
yield function (x, y) {};
yield (x, y) => {};
}
});
expect(function () {exec('zo1(x) FROM data');}).to.throw(TypeError);
expect(() => exec('zo1(x) FROM data')).to.throw(TypeError);
});

@@ -463,13 +458,13 @@ });

it('should propagate exceptions thrown in the yielded callback', function () {
var err = new Error('foobar');
const err = new Error('foobar');
register(function* zp1() {
yield function (x) {throw err;};
yield (x) => { throw err; };
});
expect(function () {exec('zp1(x) FROM data');}).to.throw(err);
expect(() => exec('zp1(x) FROM data')).to.throw(err);
});
it('should throw if the generator function returns an invalid value', function () {
var err = new Error('foobar');
register(function* zq1() {yield function (x) {}; return {};});
register(function* zq2() {yield function (x) {}; return 123;});
expect(function () {exec('zq1(x) FROM data');}).to.throw(TypeError);
const err = new Error('foobar');
register(function* zq1() { yield (x) => {}; return {}; });
register(function* zq2() { yield (x) => {}; return 123; });
expect(() => exec('zq1(x) FROM data')).to.throw(TypeError);
exec('zq2(x) FROM data');

@@ -479,4 +474,4 @@ });

register(function* zr1() {
var result = 1;
yield function (x) {result *= x;};
let result = 1;
yield (x) => { result *= x; };
return result + 5;

@@ -488,4 +483,4 @@ });

register(function* zra1() {
var result = 5;
yield function (x) {result = 999;};
let result = 5;
yield (x) => { result = 999; };
return result + 2;

@@ -497,16 +492,16 @@ });

register(function* zs1() {
var result = 0;
yield function (x, y) {result += x + y};
let result = 0;
yield (x, y) => { result += x + y };
return result;
});
expect(function () {exec('zs1() FROM data');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {exec('zs1(x) FROM data');}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(function () {exec('zs1(x, ?, ?) FROM data', 8, 3);}).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('zs1() FROM data')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('zs1(x) FROM data')).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(() => exec('zs1(x, ?, ?) FROM data', 8, 3)).to.throw(Database.SqliteError).with.property('code', 'SQLITE_ERROR');
expect(exec('zs1(x, ?) FROM data', 2)).to.equal(89);
});
it('should accept a "varargs" option', function () {
register({varargs: true}, function* zt1() {
var result = 0;
yield function () {
result += [].slice.call(arguments).reduce(function (a, b) {return a + b;}, 0);
register({ varargs: true }, function* zt1() {
let result = 0;
yield (...args) => {
result += args.reduce((a, b) => a + b, 0);
};

@@ -522,5 +517,5 @@ return result;

register(function* zu1() {
var result = 1;
yield function () {
expect(arguments.length).to.equal(0);
let result = 1;
yield (...args) => {
expect(args.length).to.equal(0);
result += 2;

@@ -538,5 +533,1 @@ };

});
function bufferOfSize(size) {
return Buffer.alloc ? Buffer.alloc(+size) : new Buffer(+size);
}

@@ -1,49 +0,39 @@

var expect = require('chai').expect;
var Database = require('../.');
var util = (function () {
var path = require('path');
var dbId = 0;
var obj;
return obj = {
current: function () {
return 'temp/' + path.basename(__filename).split('.')[0] + '.' + dbId + '.db';
},
next: function () {++dbId; return obj.current();}
};
}());
var filepath = (function () {
var fs = require('fs');
var path = require('path');
function exists(loc) {try {fs.readFileSync(loc); return true;} catch (_) {return false;}}
var attemps = [
const { expect } = require('chai');
const Database = require('../.');
const util = require('./util');
const filepath = (() => {
const fs = require('fs');
const path = require('path');
function exists(loc) { try { fs.readFileSync(loc); return true; } catch (_) { return false; } }
const attempts = [
'../build/Debug/test_extension.node',
'../build/Release/test_extension.node'
].map(function (loc) {return path.join(__dirname, loc);});
for (var i=0; i<attemps.length; ++i) {
if (exists(attemps[i])) return attemps[i];
'../build/Release/test_extension.node',
].map(loc => path.join(__dirname, loc));
for (let i = 0; i < attempts.length; ++i) {
if (exists(attempts[i])) return attempts[i];
}
throw new TypeError('Could not find test_extension.node');
}());
})();
describe('Database#loadExtension()', function () {
it('should throw if a string argument is not given', function () {
var db = new Database(util.next());
expect(function () {db.loadExtension();}).to.throw(TypeError);
expect(function () {db.loadExtension(undefined);}).to.throw(TypeError);
expect(function () {db.loadExtension(null);}).to.throw(TypeError);
expect(function () {db.loadExtension(123);}).to.throw(TypeError);
expect(function () {db.loadExtension(new String(filepath));}).to.throw(TypeError);
expect(function () {db.loadExtension([filepath]);}).to.throw(TypeError);
const db = new Database(util.next());
expect(() => db.loadExtension()).to.throw(TypeError);
expect(() => db.loadExtension(undefined)).to.throw(TypeError);
expect(() => db.loadExtension(null)).to.throw(TypeError);
expect(() => db.loadExtension(123)).to.throw(TypeError);
expect(() => db.loadExtension(new String(filepath))).to.throw(TypeError);
expect(() => db.loadExtension([filepath])).to.throw(TypeError);
});
it('should throw if the database is closed', function () {
var db = new Database(util.next());
const db = new Database(util.next());
db.close();
expect(function () {db.loadExtension(filepath);}).to.throw(TypeError);
expect(() => db.loadExtension(filepath)).to.throw(TypeError);
});
it('should throw if the database is busy', function () {
var db = new Database(util.next());
var invoked = false;
for (var value of db.prepare('select 555').pluck().iterate()) {
const db = new Database(util.next());
let invoked = false;
for (const value of db.prepare('select 555').pluck().iterate()) {
expect(value).to.equal(555);
expect(function () {db.loadExtension(filepath);}).to.throw(TypeError);
expect(() => db.loadExtension(filepath)).to.throw(TypeError);
invoked = true;

@@ -54,3 +44,3 @@ }

it('should throw if the extension is not found', function () {
var db = new Database(util.next());
const db = new Database(util.next());
try {

@@ -69,3 +59,3 @@ db.loadExtension(filepath + 'x');

it('should register the specified extension', function () {
var db = new Database(util.next());
const db = new Database(util.next());
expect(db.loadExtension(filepath)).to.equal(db);

@@ -76,11 +66,11 @@ expect(db.prepare('SELECT testExtensionFunction(NULL, 123, 99, 2)').pluck().get()).to.equal(4);

it('should not allow registering extensions with SQL', function () {
var db1 = new Database(util.next());
expect(function () {db1.prepare('SELECT load_extension(?)').get(filepath);}).to.throw(Database.SqliteError);
const db1 = new Database(util.next());
expect(() => db1.prepare('SELECT load_extension(?)').get(filepath)).to.throw(Database.SqliteError);
expect(db1.loadExtension(filepath)).to.equal(db1);
expect(function () {db1.prepare('SELECT load_extension(?)').get(filepath);}).to.throw(Database.SqliteError);
var db2 = new Database(util.next());
expect(() => db1.prepare('SELECT load_extension(?)').get(filepath)).to.throw(Database.SqliteError);
const db2 = new Database(util.next());
try {
db2.loadExtension(filepath + 'x');
} catch (err) {
expect(function () {db2.prepare('SELECT load_extension(?)').get(filepath);}).to.throw(Database.SqliteError);
expect(() => db2.prepare('SELECT load_extension(?)').get(filepath)).to.throw(Database.SqliteError);
return;

@@ -87,0 +77,0 @@ }

@@ -1,10 +0,10 @@

var expect = require('chai').expect;
var Integer = require('integer');
var Database = require('../.');
var db;
var db2;
const { expect } = require('chai');
const Integer = require('integer');
const Database = require('../.');
const util = require('./util');
const db = new Database(util.next());
const db2 = new Database(util.next());
before(function () {
db = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.1.db');
db2 = new Database('temp/' + require('path').basename(__filename).split('.')[0] + '.2.db');
db.prepare('CREATE TABLE entries (a INTEGER, b REAL, c TEXT)').run();

@@ -16,3 +16,3 @@ db2.prepare('CREATE TABLE entries (a INTEGER, b REAL, c TEXT)').run();

it('should bind to statements and transactions', function () {
var int = Integer.fromBits(4243423, 234234234);
const int = Integer.fromBits(4243423, 234234234);
db.prepare('INSERT INTO entries VALUES (?, ?, ?)').run(int, int, int);

@@ -29,8 +29,8 @@ db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']).run(int, int, int);

it('should be allowed as a return value in registered functions', function () {
db.register(function returnsInteger(a) {return Integer(a + a);});
db.register(function returnsInteger(a) { return Integer(a + a); });
expect(db.prepare('SELECT returnsInteger(?)').pluck().get(42)).to.equal(84);
});
it('should get returned by operations after setting .safeIntegers()', function () {
var int = Integer.fromBits(4243423, 234234234);
var stmt = db.prepare('SELECT a FROM entries').pluck();
const int = Integer.fromBits(4243423, 234234234);
let stmt = db.prepare('SELECT a FROM entries').pluck();
expect(stmt.get()).to.equal(1006028374637854700);

@@ -52,3 +52,3 @@ expect(stmt.safeIntegers().get()).to.deep.equal(int);

var lastRowid = db.prepare('SELECT rowid FROM entries ORDER BY rowid DESC').pluck().get();
let lastRowid = db.prepare('SELECT rowid FROM entries ORDER BY rowid DESC').pluck().get();
stmt = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');

@@ -60,3 +60,3 @@ expect(stmt.run(int, int, int).lastInsertROWID).to.equal(++lastRowid);

var trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
const trans = db.transaction(['INSERT INTO entries VALUES (?, ?, ?)']);
expect(trans.run(int, int, int).lastInsertROWID).to.equal(++lastRowid);

@@ -68,3 +68,3 @@ expect(trans.safeIntegers().run(int, int, int).lastInsertROWID).to.deep.equal(Integer(++lastRowid));

it('should get passed to functions registered with the "safeIntegers" option', function () {
db.register({safeIntegers: true}, function customfunc(a) {return a.low;});
db.register({ safeIntegers: true }, function customfunc(a) { return a.low; });
expect(db.prepare('SELECT customfunc(?)').pluck().get(2)).to.equal(null);

@@ -74,7 +74,7 @@ expect(db.prepare('SELECT customfunc(?)').pluck().get(Integer.fromBits(2, 2))).to.equal(2);

it('should respect the default setting on the database', function () {
var arg;
var int = Integer.fromBits(4243423, 234234234);
let arg;
const int = Integer.fromBits(4243423, 234234234);
function customFunctionArg(options, dontRegister) {
dontRegister || db.register(options, function (a) {arg = a;});
db.prepare('SELECT ' + options.name + '(?)').get(int);
dontRegister || db.register(options, (a) => { arg = a; });
db.prepare(`SELECT ${options.name}(?)`).get(int);
return arg;

@@ -84,15 +84,15 @@ }

var stmt = db.prepare('SELECT a FROM entries').pluck();
const stmt = db.prepare('SELECT a FROM entries').pluck();
expect(stmt.get()).to.deep.equal(int);
expect(stmt.safeIntegers(false).get()).to.equal(1006028374637854700);
expect(customFunctionArg({name: 'a1'})).to.deep.equal(int);
expect(customFunctionArg({name: 'a2', safeIntegers: false})).to.equal(1006028374637854700);
expect(customFunctionArg({ name: 'a1' })).to.deep.equal(int);
expect(customFunctionArg({ name: 'a2', safeIntegers: false })).to.equal(1006028374637854700);
db.defaultSafeIntegers(false);
var stmt2 = db.prepare('SELECT a FROM entries').pluck();
const stmt2 = db.prepare('SELECT a FROM entries').pluck();
expect(stmt2.get()).to.equal(1006028374637854700);
expect(stmt2.safeIntegers().get()).to.deep.equal(int);
expect(customFunctionArg({name: 'a3'})).to.equal(1006028374637854700);
expect(customFunctionArg({name: 'a4', safeIntegers: true})).to.deep.equal(int);
expect(customFunctionArg({ name: 'a3' })).to.equal(1006028374637854700);
expect(customFunctionArg({ name: 'a4', safeIntegers: true })).to.deep.equal(int);

@@ -103,23 +103,23 @@ db.defaultSafeIntegers();

expect(stmt2.get()).to.deep.equal(int);
expect(customFunctionArg({name: 'a1'}, true)).to.deep.equal(int);
expect(customFunctionArg({name: 'a2'}, true)).to.equal(1006028374637854700);
expect(customFunctionArg({name: 'a3'}, true)).to.equal(1006028374637854700);
expect(customFunctionArg({name: 'a4'}, true)).to.deep.equal(int);
expect(customFunctionArg({ name: 'a1' }, true)).to.deep.equal(int);
expect(customFunctionArg({ name: 'a2' }, true)).to.equal(1006028374637854700);
expect(customFunctionArg({ name: 'a3' }, true)).to.equal(1006028374637854700);
expect(customFunctionArg({ name: 'a4' }, true)).to.deep.equal(int);
var stmt3 = db.prepare('SELECT a FROM entries').pluck();
const stmt3 = db.prepare('SELECT a FROM entries').pluck();
expect(stmt3.get()).to.deep.equal(int);
expect(stmt3.safeIntegers(false).get()).to.equal(1006028374637854700);
expect(customFunctionArg({name: 'a5'})).to.deep.equal(int);
expect(customFunctionArg({name: 'a6', safeIntegers: false})).to.equal(1006028374637854700);
expect(customFunctionArg({ name: 'a5' })).to.deep.equal(int);
expect(customFunctionArg({ name: 'a6', safeIntegers: false })).to.equal(1006028374637854700);
});
it('should forbid invoking .safeIntegers() while the database is busy', function () {
var ranOnce = false;
var stmt1 = db.prepare('SELECT * FROM entries LIMIT 10');
var stmt2 = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
for (var row of stmt1.iterate()) {
let ranOnce = false;
const stmt1 = db.prepare('SELECT * FROM entries LIMIT 10');
const stmt2 = db.prepare('INSERT INTO entries VALUES (?, ?, ?)');
for (const row of stmt1.iterate()) {
ranOnce = true;
expect(function () {stmt1.safeIntegers();}).to.throw(TypeError);
expect(function () {stmt2.safeIntegers();}).to.throw(TypeError);
expect(function () {stmt1.safeIntegers(false);}).to.throw(TypeError);
expect(function () {stmt2.safeIntegers(false);}).to.throw(TypeError);
expect(() => stmt1.safeIntegers()).to.throw(TypeError);
expect(() => stmt2.safeIntegers()).to.throw(TypeError);
expect(() => stmt1.safeIntegers(false)).to.throw(TypeError);
expect(() => stmt2.safeIntegers(false)).to.throw(TypeError);
}

@@ -126,0 +126,0 @@ expect(ranOnce).to.be.true;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc