Zoltán Matók
Zoltán Matók

Reputation: 4045

sqlite3 + node: when to close db?

I'm using better-sqlite3 on Node, but I suspect my questions are applicable to node-sqlite3 as well.

I basically have 2 simple questions, relating to a server-rendered website:

Thank you

Upvotes: 9

Views: 3673

Answers (1)

Zoltán Matók
Zoltán Matók

Reputation: 4045

Joshua Wise's (better-sqlite3's creator) answer over on GitHub:


Database connections are automatically closed when they are garbage collected, which is non-deterministic. If you want to know that the connection is closed (rather than guessing), you should call .close().

You can just open one database connection for the entire thread (the entire process if you're not using worker threads), and share that connection between every request. Node.js is single-threaded, so you don't have to worry about simultaneous access, even if multiple requests are being handled concurrently. The one caveat is that you should never have a SQLite transaction open across multiple ticks of the event loop (i.e., don't use await between BEGIN and COMMIT), because then other requests could accidentally inject SQL into your transactions. Also, SQLite transactions are serialized (you can't have more than one at a time), so you should open and close them as quickly as possible; keeping them open across ticks of the event loop is bad for performance.

Upvotes: 7

Related Questions