54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
import init from "../functions/init";
|
|
import grabSQLiteClient from "../functions/grab-sqlite-client";
|
|
/**
|
|
* Resolve the SQLite client. The global client is used unless a `config`
|
|
* for another database is passed.
|
|
*/
|
|
function resolveClient(config) {
|
|
if (config) {
|
|
return grabSQLiteClient({ config });
|
|
}
|
|
init();
|
|
return global.SQLITE_CLIENT;
|
|
}
|
|
/**
|
|
* # Main DB Handler Function
|
|
* @description Any statement that produces columns (SELECT, WITH, PRAGMA,
|
|
* RETURNING, ...) returns rows. Everything else goes through `run`, which
|
|
* also handles multiple statements.
|
|
*/
|
|
export default function dbHandler({ query, values, config }) {
|
|
try {
|
|
const CLIENT = resolveClient(config);
|
|
const stmt = CLIENT.prepare(query);
|
|
const returnsRows = stmt.columnNames.length > 0;
|
|
try {
|
|
if (returnsRows) {
|
|
const rows = stmt.all(...(values || []));
|
|
return {
|
|
success: true,
|
|
payload: rows,
|
|
singleRes: rows[0],
|
|
};
|
|
}
|
|
}
|
|
finally {
|
|
stmt.finalize();
|
|
}
|
|
const res = CLIENT.run(query, (values || []));
|
|
return {
|
|
success: true,
|
|
postInsertReturn: {
|
|
affectedRows: res.changes,
|
|
insertId: Number(res.lastInsertRowid),
|
|
},
|
|
};
|
|
}
|
|
catch (error) {
|
|
return {
|
|
success: false,
|
|
error: error.message,
|
|
};
|
|
}
|
|
}
|