I'm encountering an issue in my Node.js application where the PostgreSQL sequence (nextval) continues to increment even if there is an error during validation or insertion, and I have explicitly rolled back the transaction. The application uses Node.js with the pg library and the pool connection. Below is a simplified version of the relevant code:
// userController.js
const pool = require('../db/pool');
const userSchema = require('../schemas/userSchema');
const addUser = async (full_name, phone_number, password) => {
const client = await pool.connect();
try {
// Start a transaction
await client.query('BEGIN');
// Validate input data using Zod
const userData = userSchema.parse({ full_name, phone_number, password });
// Insert data into the users table
const query = `
INSERT INTO users (full_name, phone_number, password)
VALUES ($1, $2, $3)
RETURNING *;
`;
const values = [userData.full_name, userData.phone_number, userData.password];
const result = await client.query(query, values);
// Commit the transaction
await client.query('COMMIT');
// Return the newly created user
return result.rows[0];
} catch (error) {
// Roll back the transaction in case of an error
await client.query('ROLLBACK');
console.error('Error adding user:', error);
throw error; // Rethrow the error to be caught by the calling code
} finally {
client.release(); // Release the client back to the pool
}
};
module.exports = {
addUser,
};
Despite the rollback in the catch block, the sequence continues to increment if there is an error during insertion. I suspect it might be a PostgreSQL-specific behavior. Any insights into why this might be happening or suggestions for an alternative approach would be greatly appreciated.
Additional Information:
- Node.js version: [ 18.19.1 ]
- PostgreSQL version: [ PostgreSQL 16.2 ]
- pg library version: [ 8.11.3 ]
- Operating System: [ macOS Monterey ]
Thank you in advance for your help!
