I am using javascript and node express with async/await. So there is only one thread/process running, but the way it executes is not straightforward.
Asynchronous methods may request rows from an sqllite database. I am using this npm package.
https://www.npmjs.com/package/sqlite
If simply opening and closing the database inside the async methods, like this
async function request() {
var db = await sqlite.open({
filename: "filename.db",
mode: sqlite3.OPEN_READONLY,
driver: sqlite3.Database
})
//-- do something, like this
const stmt = await db.prepare("SELECT 1");
const rows = await stmt.all();
await stmt.finalize();
//-- then close
await actualDb.close();
}
This throws “SQLITE_BUSY” errors. So I made functions like this to open/close the database:
var inUse = false;
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function openDb() {
while (inUse) {
await timeout(50)
}
inUse = true;
return await sqlite.open({
filename: "filename.db",
mode: sqlite3.OPEN_READONLY,
driver: sqlite3.Database
})
}
async function closeDb(db) {
await db.close();
inUse = false;
}
And then call these functions to open/close the database. But this only allows one async method to use the database at a time, while other requests need to wait. I think it might be possible to allow several “threads” to share the database with reference counting somehow, but don’t know exactly how to do it.