perf(db): reuse prepared statements on hot paths

- Prepare the user_accounts role lookup once in the auth middleware; it
  runs on nearly every authenticated request
- Prepare session store get/set/destroy/purge statements once in the
  constructor instead of per request
- Prepare the per-check SELECT once per PDF job instead of once per check
This commit is contained in:
2026-06-11 22:03:56 -06:00
parent b4824655dd
commit 2504766be7
3 changed files with 18 additions and 15 deletions
+9 -7
View File
@@ -7,16 +7,20 @@ const { Store } = require('express-session');
class SessionStore extends Store {
constructor(db) {
super();
this.db = db;
// Prepared once — get/set run on every request
this.getStmt = db.prepare('SELECT sess, expired FROM sessions WHERE sid = ?');
this.setStmt = db.prepare('INSERT OR REPLACE INTO sessions (sid, sess, expired) VALUES (?, ?, ?)');
this.delStmt = db.prepare('DELETE FROM sessions WHERE sid = ?');
this.purgeStmt = db.prepare('DELETE FROM sessions WHERE expired < ?');
// Purge expired sessions every 10 minutes
setInterval(() => {
try { db.prepare('DELETE FROM sessions WHERE expired < ?').run(Date.now()); } catch (_) {}
try { this.purgeStmt.run(Date.now()); } catch (_) {}
}, 10 * 60 * 1000).unref();
}
get(sid, cb) {
try {
const row = this.db.prepare('SELECT sess, expired FROM sessions WHERE sid = ?').get(sid);
const row = this.getStmt.get(sid);
if (!row) return cb(null, null);
if (Date.now() > row.expired) {
this.destroy(sid, () => {});
@@ -33,16 +37,14 @@ class SessionStore extends Store {
? sess.cookie.maxAge
: 7 * 24 * 60 * 60 * 1000;
const expired = Date.now() + maxAge;
this.db.prepare(
'INSERT OR REPLACE INTO sessions (sid, sess, expired) VALUES (?, ?, ?)'
).run(sid, JSON.stringify(sess), expired);
this.setStmt.run(sid, JSON.stringify(sess), expired);
cb(null);
} catch (e) { cb(e); }
}
destroy(sid, cb) {
try {
this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
this.delStmt.run(sid);
cb(null);
} catch (e) { cb(e); }
}