Lab 10: Database Patterns

Time: 30 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Master database patterns with Node.js: Knex.js query builder, ORM patterns (Sequelize/Prisma concepts), connection pooling, transactions, migrations, seeds, and the Repository pattern.


Step 1: Setup Knex with SQLite

cd /tmp && npm init -y --quiet
npm install knex better-sqlite3
const knex = require('knex')({
  client: 'better-sqlite3',
  connection: { filename: ':memory:' }, // In-memory for testing
  useNullAsDefault: true,
  pool: {
    min: 1,
    max: 5,
    afterCreate: (conn, done) => {
      // Enable WAL mode for better concurrent reads
      conn.pragma('journal_mode = WAL');
      conn.pragma('foreign_keys = ON');
      done(null, conn);
    }
  },
  debug: false
});

module.exports = knex;

Step 2: Migrations


Step 3: Seeds


Step 4: Query Builder Patterns


Step 5: Transactions


Step 6: Repository Pattern


Step 7: Connection Pooling


Step 8: Capstone — Full Demo

📸 Verified Output:


Summary

Pattern
Knex API
Use Case

Schema migration

knex.schema.createTable()

Database versioning

Seeds

knex('table').insert()

Test data setup

Query builder

knex('t').select().where().join()

Type-safe queries

Transactions

knex.transaction(async trx => {})

Atomic operations

Raw queries

knex.raw('SQL', [params])

Complex queries

Connection pool

pool: { min, max }

Production config

Repository

Class wrapping DB calls

Testable data layer

Eager loading

.join() or separate queries + map

N+1 prevention

Last updated