Gruber

Postgres

The Postgres module provides an abstraction over a postgres database connection to make it easy to query the database and allow the connection to be swapped out during testing.

Design goals:

  • SQL based — write queries with JavaScript template literals with automatic parameterization.
  • Testable — easily swap out the client during testing and write tests with it
  • Typed — Use the Table abstraction to build queries and type queries
  • Migrations — Safely change the database through ordered queries

There are two main parts of the module

  • PostgresClient — the abstraction over a postgres connection
  • Table — a strongly-typed query builder based on Structures definitions
import postgres from "postgres";
import { PostgresJsClient } from "gruber";

const db = new PostgresJsClient(
  postgres("postgres://user:secret@localhost:5432/database"),
);

// a record type to pass to the query
interface PersonRecord {
  id: number;
  created_at: Date;
  name: string;
}

// Fetch people from the database
const people = await db.execute<PersonRecord>`
  SELECT id, created_at, name
  FROM people
`;

// Fetch a specific record (returns the value or null)
const geoff = await db.execute<PersonRecord>`
  SELECT id, created_at, name
  FROM people
  WHERE id = ${7}
`.first();

// Run multiple queries in a transaction
await db.transaction(async (trx) => {
  await trx.execute` … `;
  await trx.execute` … `;
});

// You could instead use `await using db = new PostgresJsClient(…)`
await db.dispose();

Query building

You can use Table to define your tables using Structures and generate strongly-typed queries based on them.

import { Structure, Table } from "gruber";

// The type here is optional, but recommended for portability in larger code bases
export const Person = Table.define<PersonRecord>("people", {
  id: Structure.number(),
  created_at: Structure.date(),
  name: Structure.string(),
});

// list people created before 2nd feb 2022
const people = await Person.select()
  .where` created_at < ${new Date("2022-02-02")} `.run(db);

// Create Jess
const jess = await Person.insert()
  .values({ name: "Jess Smith" })
  .returning(["id", "created_at", "name"])
  .run(db)
  .first();

// Update Jess
await Person.update().set({ name: "Jessie Smith" }).where` id = ${jess.id} `
  .returning(["id", "created_at", "name"])
  .run(db);

// Delete Jess
await Person.delete().where` id = ${jess.id} `.run(db);

Migrations

Use PostgresMigrator to run database migrations in order against a PostgresClient, it runs the migration in a transaction that rolls-back on failure and stores applied migrations in a "migrations" table.

You have a migration like migrations/001-add-people.ts:

export default defineMigration<PostgresClient>({
  async up(postgres) {
    await postgres.execute`
      CREATE TABLE "people" (
        "id" serial PRIMARY KEY,
        "created_at" timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
        "name" varchar(255) NOT NULL
      )
    `;
  },
  async down(postgres) {
    await postgres.execute`
      DROP TABLE "people"
    `;
  },
});

The you can:

import { loadMigrationDirectory, PostgresMigrator } from "gruber";

const migrations = ;

const migrator = new PostgresMigrator(
  db,
  await loadMigrationDirectory("./migrations/")
);

// Run all pending migrations, or pass a number to run the next n
await migrator.up();

// Revert applied migrations, or pass a number to revert a specific amount
await migrator.down(1);

Migrations are sorted by name, so prefix them with a number like 001-, 002- to control the order. It also ignores file extensions when check whats applied to get around js/ts issues.

PostgresMigrator unstable

Runs migrations against a PostgresClient and records them in a "migrations" table.

Migrations are recorded by their full name, e.g. "001-add-users.js". File extensions are ignored when checking which migrations have been applied, so renaming "001-add-users.js" to "001-add-users.ts" won't run it again.

const migrator = new PostgresMigrator(
  new PostgresClient(…),
  [...definitions]
)

down

Revert n applied migrations

// Revert all migrations
await migrator.down()

// Revert the last 2 applied migrations
await migrator.down(2)

findPending

Filter the existing definitions against ones that have been applied to find ones that need to be applied.

const definitions = await migrator.findPending(
  await migrator.getAppliedRecords()
)

findReversions

Filter the existing definitions against ones that have been applied to find ones to be reverted.

const definitions = await migrator.findReversions(
  await migrator.getAppliedRecords()
)

getAppliedRecords

Look up records that have been applied in the database

const records = await migrator.getAppliedRecords()

getDefinitions

Get the internal definitions

const defs = migrator.getDefinitions()

up

Run n pending migrations

// Run all pending migrations
await migrator.up()

// Run the next 2 migrations
await migrator.up(2)

PostgresClient type

Something that manages a connection to a postgres database and performs queries & transactions

const pg = {
  execute(strings, ...values) {},
  transaction(block) {},
  dispose() {},
  [Symbol.asyncDispose]() {}
}

getPostgresMigrations

Query the postgres database to find migrations that have already been performed. Returning an array of MigrationRecord, or an empty array if the "migrations" table doesn't exist yet.

const sql // SqlDependency
const records = await getPostgresMigrations(sql)

executePostgresMigration

Perform either the up or down postgres migration and record what happened. This will first start a transaction, so if anything goes wrong the whole operation is aborted. Within the transaction, it attempts the run the action (either up or down) as specified.

After the action is ran, it will follow up with updating the migration records. For an up action, it will create a new PostgresMigrationRecord and insert it into the database. For a down action, it will remove the corresponding PostgresMigrationRecord.

There is an edge case where it will not remove the record if running the postgresBootstrapMigration action, because that migration deletes the migration table itself so would be pointless.

const sql // SqlDependency
const definition = {
  name: "001-add-users.js",
  ...definePostgresMigration(...)
}

await executePostgresMigration(definition, "up", sql)

PostgresMigrationRecord type

A record in a postgres database containing information about a migration that has been run.

const record = {
  name: '001-add-users-table.js',
  created: new Date()
}

postgresBootstrapMigration

This is a MigrationDefinition to bootstrap postgres migrations. It sets up the initial "migrations" table that all other migrations will be recorded in.

definePostgresMigration

A typed version of defineMigration that specializes for a postgres.js sql connection. This is mostly useful to get a strongly typed sql parameter.

import { definePostgresMigration } from "gruber"

export default definePostgresMigration({
  async up(sql) {
    await sql`
      CREATE TABLE users ...
    `
  },
  async down(sql) {
    await sql`
      DROP TABLE users
    `
  }
})

TableColumns type

Turn a type into record of structures to validate it

Table

A declarative definition for a table that you can use to build queries with and query strongly-typed values from the database with.

delete

Build an SQL DELETE query with optional clauses

const query = People.delete()
  .where` id = ${7} `
  .run(postgres)

insert

Build an SQL INSERT query with optional clauses

const query = People.insert()
  .values({ name: "Jess Smith" })
  .returning(['id', 'created_at', 'name'])
  .run(postgres)

properties

Get a subset of the column structures, useful for creating structures for validation

select

Build an SQL SELECT query with optional clauses

const query = People.select([ 'id', 'created_at', 'name' ])
  .where` id = ${7} `
  .orderBy('id', 'DESC')
  .run(postgres)

Table.define

A helper to define a table without using the constructor

const People = Table.define("people", {
  id: Structure.number(),
  created_at: Structure.date(),
  name: Structure.string(),
})

update

Build an SQL UPDATE query with optional clauses

const query = People.update()
  .set({ name: "Geoff Testington" })
  .where` id = ${7} `
  .returning(['id', 'created_at', 'name'])
  .run(postgres)
debug
{
  "PostgresMigrator": {
    "entrypoint": "postgres/mod.ts",
    "id": "PostgresMigrator",
    "name": "PostgresMigrator",
    "content": "Runs migrations against a [PostgresClient](#postgresclient) and records them in a \"migrations\" table.\n\nMigrations are recorded by their full name, e.g. \"001-add-users.js\".\nFile extensions are ignored when checking which migrations have been applied,\nso renaming \"001-add-users.js\" to \"001-add-users.ts\" won't run it again.\n\n```js\nconst migrator = new PostgresMigrator(\n  new PostgresClient(…),\n  [...definitions]\n)\n```",
    "tags": {
      "unstable": "true",
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator",
    "children": {
      "getDefinitions": {
        "id": "PostgresMigrator#getDefinitions",
        "name": "getDefinitions",
        "content": "Get the internal definitions\n\n```js\nconst defs = migrator.getDefinitions()\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.getDefinitions",
        "children": {}
      },
      "getAppliedRecords": {
        "id": "PostgresMigrator#getAppliedRecords",
        "name": "getAppliedRecords",
        "content": "Look up records that have been applied in the database\n\n```js\nconst records = await migrator.getAppliedRecords()\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.getAppliedRecords",
        "children": {}
      },
      "findPending": {
        "id": "PostgresMigrator#findPending",
        "name": "findPending",
        "content": "Filter the existing definitions against ones that have been applied\nto find ones that need to be applied.\n\n```js\nconst definitions = await migrator.findPending(\n  await migrator.getAppliedRecords()\n)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.findPending",
        "children": {}
      },
      "up": {
        "id": "PostgresMigrator#up",
        "name": "up",
        "content": "Run `n` pending migrations\n\n```js\n// Run all pending migrations\nawait migrator.up()\n\n// Run the next 2 migrations\nawait migrator.up(2)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.up",
        "children": {}
      },
      "findReversions": {
        "id": "PostgresMigrator#findReversions",
        "name": "findReversions",
        "content": "Filter the existing definitions against ones that have been applied\nto find ones to be reverted.\n\n```js\nconst definitions = await migrator.findReversions(\n  await migrator.getAppliedRecords()\n)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.findReversions",
        "children": {}
      },
      "down": {
        "id": "PostgresMigrator#down",
        "name": "down",
        "content": "Revert `n` applied migrations\n\n```js\n// Revert all migrations\nawait migrator.down()\n\n// Revert the last 2 applied migrations\nawait migrator.down(2)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/migrator\".PostgresMigrator.down",
        "children": {}
      }
    }
  },
  "PostgresClient": {
    "entrypoint": "postgres/mod.ts",
    "id": "PostgresClient",
    "name": "PostgresClient",
    "content": "Something that manages a connection to a postgres database and performs queries & transactions\n\n```js\nconst pg = {\n  execute(strings, ...values) {},\n  transaction(block) {},\n  dispose() {},\n  [Symbol.asyncDispose]() {}\n}\n```",
    "tags": {
      "group": "Miscellaneous",
      "type": "true"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-client\".PostgresClient",
    "children": {}
  },
  "getPostgresMigrations": {
    "entrypoint": "postgres/mod.ts",
    "id": "getPostgresMigrations",
    "name": "getPostgresMigrations",
    "content": "Query the postgres database to find migrations that have already been performed.\nReturning an array of `MigrationRecord`, or an empty array if the \"migrations\" table doesn't exist yet.\n\n```js\nconst sql // SqlDependency\nconst records = await getPostgresMigrations(sql)\n```",
    "tags": {
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-migrator\".getPostgresMigrations",
    "children": {}
  },
  "executePostgresMigration": {
    "entrypoint": "postgres/mod.ts",
    "id": "executePostgresMigration",
    "name": "executePostgresMigration",
    "content": "Perform either the **up** or **down** postgres migration and record what happened.\nThis will first start a transaction, so if anything goes wrong the whole operation is aborted.\nWithin the transaction, it attempts the run the action (either **up** or **down**) as specified.\n\nAfter the action is ran, it will follow up with updating the migration records.\nFor an **up** action, it will create a new `PostgresMigrationRecord`\nand insert it into the database.\nFor a **down** action, it will remove the corresponding `PostgresMigrationRecord`.\n\n> There is an edge case where it will not remove the record if running the `postgresBootstrapMigration` action,\n> because that migration deletes the migration table itself so would be pointless.\n\n```js\nconst sql // SqlDependency\nconst definition = {\n  name: \"001-add-users.js\",\n  ...definePostgresMigration(...)\n}\n\nawait executePostgresMigration(definition, \"up\", sql)\n```",
    "tags": {
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-migrator\".executePostgresMigration",
    "children": {}
  },
  "PostgresMigrationRecord": {
    "entrypoint": "postgres/mod.ts",
    "id": "PostgresMigrationRecord",
    "name": "PostgresMigrationRecord",
    "content": "A record in a postgres database containing information about a migration that has been run.\n\n```js\nconst record = {\n  name: '001-add-users-table.js',\n  created: new Date()\n}\n```",
    "tags": {
      "group": "Miscellaneous",
      "type": "true"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-migrator\".PostgresMigrationRecord",
    "children": {}
  },
  "postgresBootstrapMigration": {
    "entrypoint": "postgres/mod.ts",
    "id": "postgresBootstrapMigration",
    "name": "postgresBootstrapMigration",
    "content": "This is a `MigrationDefinition` to bootstrap postgres migrations.\nIt sets up the initial \"migrations\" table that all other\nmigrations will be recorded in.",
    "tags": {
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-migrator\".postgresBootstrapMigration",
    "children": {}
  },
  "definePostgresMigration": {
    "entrypoint": "postgres/mod.ts",
    "id": "definePostgresMigration",
    "name": "definePostgresMigration",
    "content": "A typed version of `defineMigration` that specializes for a [postgres.js](https://github.com/porsager/postgres) `sql` connection.\nThis is mostly useful to get a strongly typed `sql` parameter.\n\n```js\nimport { definePostgresMigration } from \"gruber\"\n\nexport default definePostgresMigration({\n  async up(sql) {\n    await sql`\n      CREATE TABLE users ...\n    `\n  },\n  async down(sql) {\n    await sql`\n      DROP TABLE users\n    `\n  }\n})\n```",
    "tags": {
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/postgres-migrator\".definePostgresMigration",
    "children": {}
  },
  "TableColumns": {
    "entrypoint": "postgres/mod.ts",
    "id": "TableColumns",
    "name": "TableColumns",
    "content": "Turn a type into record of structures to validate it",
    "tags": {
      "group": "Miscellaneous",
      "type": "true"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".TableColumns",
    "children": {}
  },
  "Table": {
    "entrypoint": "postgres/mod.ts",
    "id": "Table",
    "name": "Table",
    "content": "A declarative definition for a table that you can use to build queries with\nand query strongly-typed values from the database with.",
    "tags": {
      "group": "Miscellaneous"
    },
    "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table",
    "children": {
      "select": {
        "id": "Table#select",
        "name": "select",
        "content": "Build an SQL `SELECT` query with optional clauses\n\n```js\nconst query = People.select([ 'id', 'created_at', 'name' ])\n  .where` id = ${7} `\n  .orderBy('id', 'DESC')\n  .run(postgres)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.select",
        "children": {}
      },
      "update": {
        "id": "Table#update",
        "name": "update",
        "content": "Build an SQL `UPDATE` query with optional clauses\n\n```js\nconst query = People.update()\n  .set({ name: \"Geoff Testington\" })\n  .where` id = ${7} `\n  .returning(['id', 'created_at', 'name'])\n  .run(postgres)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.update",
        "children": {}
      },
      "insert": {
        "id": "Table#insert",
        "name": "insert",
        "content": "Build an SQL `INSERT` query with optional clauses\n\n```js\nconst query = People.insert()\n  .values({ name: \"Jess Smith\" })\n  .returning(['id', 'created_at', 'name'])\n  .run(postgres)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.insert",
        "children": {}
      },
      "delete": {
        "id": "Table#delete",
        "name": "delete",
        "content": "Build an SQL `DELETE` query with optional clauses\n\n```js\nconst query = People.delete()\n  .where` id = ${7} `\n  .run(postgres)\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.delete",
        "children": {}
      },
      "properties": {
        "id": "Table#properties",
        "name": "properties",
        "content": "Get a subset of the column structures, useful for creating structures for validation",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.properties",
        "children": {}
      },
      "Table.define": {
        "id": "Table.define",
        "name": "define",
        "content": "A helper to define a table without using the constructor\n\n```js\nconst People = Table.define(\"people\", {\n  id: Structure.number(),\n  created_at: Structure.date(),\n  name: Structure.string(),\n})\n```",
        "tags": {
          "group": "Miscellaneous"
        },
        "fullName": "\"/home/runner/work/gruber/gruber/postgres/tables\".Table.define",
        "children": {}
      }
    }
  }
}