迁移至Knex.js后是否仍需手动释放PostgreSQL数据库客户端连接?
Good news - you don't need to manually release client connections with Knex.js! It handles connection pooling automatically under the hood, which will solve the pain points you're facing with tracking connection status and passing client instances around.
Here's why this works differently from your current pg setup:
- When you use Knex to run queries (either standalone, in transactions, or via query builders), it automatically borrows a connection from the pool, executes your operation, and returns the connection back to the pool once the operation completes (successfully or with an error). No need for explicit
client.release()calls anywhere in your code. - The
.destroy()method you mentioned is indeed only for scenarios where you want to shut down the entire connection pool permanently (like when your server is gracefully shutting down). For your daily API calls that run frequently, you'll never need to call this—Knex keeps the pool alive and reuses connections efficiently.
Example rewrite of your API endpoint with Knex:
Instead of managing clients manually, your code becomes much cleaner:
app.post("/deleteCognitoUserBasedOnEmail", async function (req, res) { const { email } = req.body; try { const isUserAdminRes = await knex('end_user') .select('is_admin') .where('email', email); // Your logic to handle admin check and send response goes here const status = /* determine appropriate status */; const responseMessage = /* your response message */; return res.status(status).send({ responseMessage }); } catch (e) { console.error("Error occurred : " + e); return res.status(500).send({ errorMessage: "Internal Server Error. " + e.message }); } });
Notice there's no manual connection handling at all—Knex takes care of that for you.
Matching your existing pool configuration in Knex:
You can replicate your current pg pool settings (max connections, idle timeout) when initializing Knex, so you get the same pooling behavior you're used to:
const knex = require('knex')({ client: 'pg', connection: { user: dbUser, host: dbHost, database: database, password: dbHmac, port: dbPort, }, pool: { max: 10, // Same as your pg max setting idleTimeoutMillis: 30000 // Same idle timeout } }); module.exports = knex;
This setup will eliminate the need to track client instances and remember to release connections, making your codebase less error-prone and easier to maintain.
内容的提问来源于stack exchange,提问作者era s'q

