CodeBlanks Logo Icon CodeBlanks

Transactions

Learn transactions with pg.Client.

Transactions

A transaction runs multiple SQL statements as a single atomic unit. Either all succeed or none do. This is critical for data integrity.

The PostgreSQL transaction pattern: BEGIN → queries → COMMIT (success) or ROLLBACK (error). In the pg module you get a client with pool.connect(), start with client.query("BEGIN"), run the queries, then COMMIT or ROLLBACK, and release the client with client.release().

The pool.connect pattern

For a transaction you get a dedicated client with pool.connect(). This client uses a single connection for the whole transaction; this ensures multiple queries run on the same connection.

The pattern: const client = await pool.connect(); try { await client.query("BEGIN"); await client.query(...); await client.query("COMMIT"); } catch(e) { await client.query("ROLLBACK"); } finally { client.release(); }. The finally block ensures the connection is always returned; this prevents pool exhaustion.

Practice Log the type of pool.connect

Import the Pool class from pg. Create a pool: new Pool({}). Log typeof pool.connect.

Starter code

index.js
// import the module

// create a pool

// log the type of connect

Sample solution

index.js
const { Pool } = require("pg");
const pool = new Pool({});
console.log(typeof pool.connect);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens on error in a transaction?

  • COMMIT
  • ROLLBACK Correct answer
  • BEGIN
  • SELECT

Explanation: On error the transaction is rolled back with ROLLBACK.

2 Match each piece to its role

Term Meaning
BEGIN Starts a transaction
COMMIT Saves changes
ROLLBACK Undoes changes
client.release() Returns the connection

3 Complete the method name

Question
const client = await pool.____()
Answer
const client = await pool.connect()

Explanation: pool.connect() gives a client for a transaction.

All lessons in Advanced