PostgreSQL sequence not rolling back in Node.js application despite transaction rollback

25 views Asked by At

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,
};

 Table Structure

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:

  1. Node.js version: [ 18.19.1 ]
  2. PostgreSQL version: [ PostgreSQL 16.2 ]
  3. pg library version: [ 8.11.3 ]
  4. Operating System: [ macOS Monterey ]

Thank you in advance for your help!

0

There are 0 answers