Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active October 8, 2022 10:50
Show Gist options
  • Save Ivannnnn/58754a8028e25e7aa519746a5f2ede6a to your computer and use it in GitHub Desktop.
Save Ivannnnn/58754a8028e25e7aa519746a5f2ede6a to your computer and use it in GitHub Desktop.
Wrapper around better-sqlite3
const betterSqlite = require("better-sqlite3");
const proxify = (get, set) => new Proxy({}, { get, set });
const valuesFragment = (obj) => {
const keys = Object.keys(obj);
return `(${keys.join(",")}) VALUES (${keys.map((k) => "@" + k).join(",")})`;
};
module.exports = (dir, options) => {
const sqlite = betterSqlite(dir, options);
sqlite.pragma("journal_mode = WAL");
var table;
const createTable = (propsStr) =>
sqlite.prepare(`CREATE TABLE IF NOT EXISTS ${table} (${propsStr})`).run();
const get = (query = "", cols = ["*"]) => {
console.log(`SELECT ${cols.join(",")} FROM ${table} ` + query);
return sqlite
.prepare(`SELECT ${cols.join(",")} FROM ${table} ` + query)
.all();
};
const insert = (arr) => {
const statement = sqlite.prepare(
`INSERT OR IGNORE INTO ${table} ${valuesFragment(arr[0])}`
);
return sqlite
.transaction((data) => data.map((obj) => statement.run(obj)))(arr)
.reduce((acc, val) => (acc += val.changes), 0);
};
const drop = () => sqlite.prepare(`DROP TABLE ${table}`).run();
const truncate = () => sqlite.prepare(`DELETE FROM TABLE ${table}`).run();
const methods = { createTable, drop, truncate, insert, get };
return proxify((_, tableName) => {
if (tableName === "sqlite") return sqlite;
table = tableName;
return proxify((_, func) => (...args) => {
if (!methods[func]) throw new Error("Method does not exist!");
return methods[func](...args);
});
});
};
/* USAGE
//
const db = require('./db')(`${__dirname}/db.sqlite`, options)
db.posts.createTable(`
id INTEGER PRIMARY KEY AUTOINCREMENT,
author VARCHAR,
body TEXT
`)
db.posts.insert([
{ author: 'drogba', body: 'hello' }
])
db.posts.get() -> gets [{ id: 1, author: 'drogba', body: 'hello'}]
db.posts.get(`WHERE author = 'ivannnnn'`) -> must be single quotes
db.posts.get(`WHERE id = 1`, ['body'])
db.posts.truncate()
db.posts.drop()
db.sqlite -> better-sqlite3 instance
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment