Module 61: Database Integration

Lesson 1 of 5 · 15–25 minutes

Drivers and connection pools

🏠The everyday picture

A taxi stand. Instead of calling a new taxi from across the city for every trip, a few taxis wait at the stand, take a passenger, and come back. Much faster, and the roads don't fill up with taxis.

📘What it really is

import pg from "pg";

export const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: 10,                       // at most 10 connections
});

const { rows } = await pool.query(
  "SELECT id, name FROM customers WHERE city = $1 ORDER BY name LIMIT $2",
  [city, 25],
);
const client = await pool.connect();
try {
  await client.query("BEGIN");
  // ... several queries with client.query(...)
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();              // always return it to the pool
}

🖱️Try it

Install pg and create src/data/pool.ts. Implement the PostgreSQL version of one repository with pool.query and $n placeholders, and one transaction with pool.connect(), BEGIN, COMMIT/ROLLBACK and release(). Run your integration tests against a test database.

✅Quick check

Why use a connection pool?

Show the answer

Opening connections is slow; a pool reuses a few open ones, making requests faster and protecting the database's limit.

What happens if a transaction's client is never released?

Show the answer

The pool gradually runs out of connections, and the app stops responding.

← BackModule 61
ProLearners Assist