Skip to main content
jg-packages

Search

    PostgreSQL

    jg-postgres

    node-postgres helpers: transactions that report an unknown commit, advisory locks, SQLSTATE checks, cursor pages, and ordered lists.

    v0.7.0Node.jsESMMIT

    npm

    npm install jg-postgres

    pnpm

    pnpm add jg-postgres

    Usage

    Create one pool per database, with timeouts, and close it at shutdown:

    ts
    import { createPostgres } from 'jg-postgres';
    
    const postgres = createPostgres({
      host: 'db.internal',
      database: 'app',
      user: 'app',
      password: 'secret',
      max: 10,
      connectionTimeoutMillis: 30_000, // waiting for a connection
      statement_timeout: 60_000, // one statement, on the server
      lock_timeout: 30_000, // waiting for a row or table lock
      idle_in_transaction_session_timeout: 300_000, // a transaction left open
      onError: (error) => console.error('PostgreSQL', error),
    });
    
    const users = await postgres.query<{ id: string }>('SELECT id FROM user_account LIMIT $1;', [10]);
    await postgres.close();

    The pool reads NUMERIC as a number and TIMESTAMPTZ as an ISO 8601 UTC string, such as '2026-10-17T08:30:00.000Z', and keeps BIGINT as a string, so no digit of a large amount is lost. The parsers are set on the pool, not node-postgres’s global registry, so other pools in the program keep theirs. Errors no caller awaits, such as an idle connection the server closed, go to onError, console.error by default, instead of crashing the process.

    Creating the database and its schema

    At startup, ensureDatabase creates the database when the server doesn’t have it yet, connecting to the maintenance database, postgres, with the same configuration, and initializeSchemaOnce creates its schema the first time:

    ts
    import {
      createPostgres,
      ensureDatabase,
      initializeSchemaOnce,
      type IPostgresConfig,
    } from 'jg-postgres';
    
    const config: IPostgresConfig = {
      host: 'db.internal',
      database: 'app',
      user: 'app',
      password: 'secret',
    };
    
    await ensureDatabase(config);
    const postgres = createPostgres(config);
    await initializeSchemaOnce(postgres, {
      statements: schemaStatements, // such as each table's DDL, in order
      markerTable: 'schema_migration', // a table the statements create last
    });

    Every replica can run both at once. Another process creating the database first counts as success. initializeSchemaOnce runs in one transaction under an advisory lock: it skips when the public schema has the marker table, refuses with SCHEMA_NOT_EMPTY a public schema that holds anything else, such as a half-applied schema from before, and otherwise runs the statements and checks they created the marker table, rolling everything back with SCHEMA_MARKER_MISSING when they didn’t. It resolves to true when it created the schema. The statements run in a transaction, so none may be one that can’t, such as CREATE INDEX CONCURRENTLY.

    Test databases

    jg-postgres/testing names a database for one test process, test_<pid>_<name>, and drops it afterwards, ending its connections first. The drop refuses any name without this process’s prefix, with INVALID_TEST_DATABASE_NAME, so a configuration that points at a real database can’t lose it:

    ts
    import { ensureDatabase, type IPostgresConfig } from 'jg-postgres';
    import { createTestDatabaseName, dropTestDatabase } from 'jg-postgres/testing';
    
    const config: IPostgresConfig = { ...connection, database: createTestDatabaseName('primary') };
    await ensureDatabase(config);
    // ... the tests
    await dropTestDatabase(config);

    A name holds lowercase letters, digits, and underscores, and the whole name at most 63 bytes. The helpers aren’t exported from the root entry.

    Transactions

    ts
    import { createPostgres } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const orderId = await postgres.transaction(async (client) => {
      const { rows } = await client.query<{ id: string }>(
        'INSERT INTO purchase_order (user_account_id) VALUES ($1) RETURNING id;',
        ['42'],
      );
      await client.query('UPDATE user_account SET order_count = order_count + 1 WHERE id = $1;', [
        '42',
      ]);
      return rows[0]?.id;
    });

    transaction commits when the operation resolves, rolls back when it throws, and rejects with the operation’s own error. It always returns its client to the pool, or destroys it when its state is unknown. When the connection breaks during COMMIT, nobody can tell whether the transaction committed, so it rejects with TRANSACTION_OUTCOME_UNKNOWN: check the data before retrying anything that isn’t idempotent. Run work inside a transaction on its client, and never start a transaction inside another.

    Transactions on a client you already hold

    runTransaction runs the same kind of transaction on a client you checked out yourself, so several transactions can run one after another on one connection. It never releases the client: release it with client.release(isInTransaction(client)), which destroys a client whose transaction ended in an unknown state instead of returning it to the pool:

    ts
    import { createPostgres, isInTransaction, runTransaction } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const client = await postgres.pool.connect();
    try {
      await runTransaction(client, async (transactionClient) => {
        await transactionClient.query('DELETE FROM user_session WHERE user_account_id = $1;', ['42']);
      });
      await runTransaction(client, async (transactionClient) => {
        await transactionClient.query('DELETE FROM user_account WHERE id = $1;', ['42']);
      });
    } finally {
      client.release(isInTransaction(client));
    }

    isInTransaction is true while a transaction runTransaction began is open, and stays true when its end is unknown: a COMMIT the server never answered, which rejects with TRANSACTION_OUTCOME_UNKNOWN, or a ROLLBACK that failed, which goes to onError, console.error by default. A client already in a transaction, whether runTransaction’s or one the caller began with its own BEGIN, is refused with TRANSACTION_ALREADY_ACTIVE before any query, so a transaction is never nested inside another. runTransaction takes the same timeouts as transaction. It tracks only the clients of the copy of jg-postgres that ran it, and a postgres.transaction() started inside its operation runs on another client.

    Timeouts

    A profile says how long a kind of work may run: a statement on the server, a wait for a lock, and the client’s wait for the answer, which adds a grace, 15 seconds by default, so the server’s own error arrives first. Give the pool the profile of everyday work, and a slow transaction one of its own:

    ts
    import {
      createPostgres,
      defineTimeoutProfile,
      toPoolTimeouts,
      withQueryTimeout,
    } from 'jg-postgres';
    
    const STANDARD = defineTimeoutProfile({ statementTimeoutSeconds: 15, lockTimeoutSeconds: 5 });
    const REPORT = defineTimeoutProfile({ statementTimeoutSeconds: 300, lockTimeoutSeconds: 30 });
    
    const postgres = createPostgres({ connectionString, ...toPoolTimeouts(STANDARD) });
    
    await postgres.transaction(
      (client) =>
        client.query(withQueryTimeout({ text: 'SELECT build_report($1);', values: [month] }, REPORT)),
      { timeouts: REPORT },
    );

    timeouts sets the statement and lock timeouts for that transaction only, so the client goes back to the pool with the pool’s. The pool’s query_timeout still applies to each query that doesn’t set its own, so pass the transaction’s queries through withQueryTimeout with the same profile. A query the client stops waiting for is rolled back: the client goes back to the pool once ROLLBACK, which has the pool’s query_timeout too, confirms the connection, and is destroyed otherwise.

    Optional reads

    createOptionalReader runs reads that are nice to have, such as a counter in a page’s header, without ever delaying or crowding out essential work. A read is skipped, giving null at once, when the reader already runs maxActiveReads reads, a request waits for a client, or the pool can’t give more clients than reservedIdleClients, counting idle ones and the room left to open new ones. It runs in a read-only transaction with short timeouts, gives null after admissionSeconds, and never throws:

    ts
    import { createOptionalReader } from 'jg-postgres';
    
    const counters = createOptionalReader({ postgres }); // 2 reads at most, 2 clients left free, 1 second
    
    const unread = counters.read(
      `unread:${accountId}`, // callers of the same key share one read
      {
        text: 'SELECT count(*)::int AS count FROM notification WHERE account_id = $1;',
        values: [accountId],
      },
      (row) => (row as { count: number }).count,
    );
    const count = await unread.completion; // a number, or null

    Deleting expired rows

    deleteExpiredInBatches deletes a table’s rows older than a cutoff, such as audit events past their retention, a batch at a time, so no statement holds many locks or runs long:

    ts
    import { deleteExpiredInBatches } from 'jg-postgres';
    
    const { deletedCount, cutoff } = await deleteExpiredInBatches(postgres, {
      table: 'audit_event',
      timestampColumn: 'created_at', // the default
      keyColumn: 'id', // the default
      olderThan: { months: 6 }, // or cutoff: a Date or an ISO string
      batchSize: 1_024, // the default, at most 8,192
      filters: [{ column: 'tenant_id', value: tenantId }], // optional
    });

    olderThan takes months and days, subtracted on the UTC calendar, so six months before August 31 is the last day of February, and then seconds. It’s counted once from the database’s clock, and a row exactly at the cutoff is kept. Each batch is one statement that locks the oldest expired rows, skipping rows another transaction holds, which the next run deletes, and deletes them by keyColumn; batches repeat until one deletes nothing, so concurrent runs share the work without deleting a row twice. With timeouts, a profile from defineTimeoutProfile, each batch runs as a transaction of its own with them. Every name is quoted.

    A signal stops the deletion between batches, such as when the app shuts down: once it aborts, no further statement starts, and the call rejects with its reason after the batch in flight settles. The rows it didn’t reach stay for a later call, so a drain of a large backlog can run in small batches without delaying shutdown.

    keyColumn must be unique and not null, such as the primary key: a key shared by an expired and an unexpired row would delete both. Index the timestamp and the key together, such as CREATE INDEX idx_ae__created_at_id ON audit_event (created_at, id);, so each batch reads only the rows it deletes.

    Usage limits

    admitUsage decides, atomically, whether an actor may do a rate-limited action now, such as sending an invitation, and records it when they may. It refuses with cooldown while the same action on the same scope was accepted less than cooldownSeconds ago, by any actor, and with limit once the actor did the action limit times within windowSeconds:

    ts
    import { admitUsage } from 'jg-postgres';
    
    const admission = await admitUsage(postgres, {
      actorId: userId,
      actionId: 'send-invitation',
      scopeKey: inviteeEmailHash, // the cooldown applies per invitee
      limit: 20,
      windowSeconds: 86_400,
      cooldownSeconds: 60,
    });
    // { outcome: 'accepted' | 'cooldown' | 'limit', retryAt: an ISO timestamp, or null }

    Concurrent calls queue on transaction advisory locks, the scope’s then the actor’s, so two can never both pass, and every comparison uses the database’s clock. Like transaction, it rejects with TRANSACTION_OUTCOME_UNKNOWN when the connection breaks during COMMIT, and the action may or may not have been recorded. The accepted actions go in a usage_event table:

    sql
    CREATE TABLE usage_event (
      id bigint GENERATED ALWAYS AS IDENTITY,
      actor_id varchar(256) NOT NULL,
      action_id varchar(128) NOT NULL,
      scope_key varchar(256) NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT pk_ue__id PRIMARY KEY (id),
      CONSTRAINT chk_ue__actor_id_non_empty CHECK (actor_id <> ''),
      CONSTRAINT chk_ue__action_id_non_empty CHECK (action_id <> ''),
      CONSTRAINT chk_ue__scope_key_non_empty CHECK (scope_key <> '')
    );
    CREATE INDEX idx_ue__actor_id_action_id_created_at ON usage_event (actor_id, action_id, created_at);
    CREATE INDEX idx_ue__action_id_scope_key_created_at_scoped
      ON usage_event (action_id, scope_key, created_at)
      WHERE scope_key IS NOT NULL;
    CREATE INDEX idx_ue__created_at ON usage_event (created_at);

    The table grows with every accepted action. Prune it on a schedule with deleteExpiredInBatches, deleting the rows older than the longest window or cooldown of any action:

    ts
    import { deleteExpiredInBatches } from 'jg-postgres';
    
    await deleteExpiredInBatches(postgres, { table: 'usage_event', olderThan: { seconds: 86_400 } });

    Verification challenges

    createVerificationChallenges issues and checks short codes bound to an actor, an action, and a target, such as the code that confirms a new email address. Each action has a policy: how long a code is valid, how many wrong codes it takes, how many codes an actor may be issued within a window, over every target, and how often a challenge’s code may be resent:

    ts
    import { createVerificationChallenges } from 'jg-postgres';
    
    const challenges = createVerificationChallenges(postgres, {
      policies: {
        'verify-email': {
          validitySeconds: 600,
          maxFailedAttempts: 5,
          issueLimit: 5,
          issueWindowSeconds: 3_600,
          resendLimit: 3, // optional: without it, resend refuses the action
          resendCooldownSeconds: 60, // optional
        },
      },
      codeLength: 6, // the default
    });
    
    const binding = { actorId: userId, actionId: 'verify-email', targetId: newEmail };
    const issued = await challenges.issue(binding, ({ code, deliveryId }) =>
      mailer.send(newEmail, code, { idempotencyKey: deliveryId }),
    );
    // { outcome: 'issued', challengeToken, expiresAt } or { outcome: 'limit', retryAt }
    
    // when the user asks for another code, with the token the client kept
    const resent = await challenges.resend(
      { ...binding, challengeToken: savedToken },
      ({ code, deliveryId, remainingSeconds }) =>
        mailer.send(newEmail, code, { idempotencyKey: deliveryId, remainingSeconds }),
    );
    // { outcome: 'resent', expiresAt }, { outcome: 'cooldown', retryAt }, { outcome: 'limit' },
    // or { outcome: 'invalid' }
    
    // later, with the token the client kept and the code the user typed
    const isVerified = await challenges.consume({
      ...binding,
      challengeToken: savedToken,
      code: typedCode,
    });

    issue refuses with limit once the actor was issued issueLimit codes within the window, with retryAt, when the oldest of them leaves it. Otherwise it supersedes the binding’s active challenge and commits the new one, then calls deliver with the code, the only time it’s available. A delivery that throws makes issue throw VERIFICATION_DELIVERY_FAILED, with the code and the token redacted from it and its cause; the challenge still counts toward the limit. Concurrent issues for an actor and an action queue on a transaction advisory lock, and every comparison uses the database’s clock.

    resend sends the binding’s active challenge a new code, under the same token and the same expiry, so the earlier code stops working. Wrong codes keep counting toward maxFailedAttempts, and resends never count toward issueLimit. It refuses with limit once the challenge was resent resendLimit times, and with cooldown and a retryAt until resendCooldownSeconds passed since its issue or its last resend; a policy without resendLimit makes resend throw INVALID_VERIFICATION_INPUT. A challenge that’s used, superseded, expired, or out of attempts, another binding’s token, or a token of the wrong shape resolves to invalid. Concurrent resends of one challenge queue on its row, so they can’t exceed the limit, and a resend judges expiry and the cooldown after any wait for that row, so one that waited past the expiry resolves to invalid. The new code is delivered once it’s committed; a delivery that throws makes resend throw VERIFICATION_DELIVERY_FAILED, redacted as for issue, and the resend still counts, with the earlier code already stopped. A resend can go out with little time left, so remainingSeconds lets the message say how long the code works.

    Every delivery has a deliveryId, ${challengeId}:0 for the issue and ${challengeId}:1 and up for each resend. Use it, not challengeId, as the email’s idempotency key: it’s the same for every attempt to send one code, and different for each new code.

    consume resolves to true once, for the right code. A wrong code counts a failed attempt, and a challenge stops accepting codes after maxFailedAttempts of them, so the policy’s current value applies. A used, superseded, or expired challenge, another binding’s token, or a token or code of the wrong shape resolves to false without counting, and every false looks the same to the caller. Expiry is judged after any wait for another call’s lock on the challenge, so an attempt that waited past it resolves to false without counting. Like issue and resend, consume rejects with TRANSACTION_OUTCOME_UNKNOWN when the connection breaks during COMMIT, and the code may or may not have been used.

    Only the SHA-256 hashes of the token and of the code, combined with its token, are stored, in a verification_challenge table:

    sql
    CREATE TABLE verification_challenge (
      id bigint GENERATED ALWAYS AS IDENTITY,
      actor_id varchar(256) NOT NULL,
      action_id varchar(128) NOT NULL,
      target_id varchar(256) NOT NULL,
      token_hash text NOT NULL,
      code_hash text NOT NULL,
      failed_attempt_count smallint NOT NULL DEFAULT 0,
      resend_count smallint NOT NULL DEFAULT 0,
      expires_at timestamptz NOT NULL,
      used_at timestamptz NULL,
      superseded_at timestamptz NULL,
      resent_at timestamptz NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT pk_vc__id PRIMARY KEY (id),
      CONSTRAINT uq_vc__token_hash UNIQUE (token_hash),
      CONSTRAINT chk_vc__actor_id_non_empty CHECK (actor_id <> ''),
      CONSTRAINT chk_vc__action_id_non_empty CHECK (action_id <> ''),
      CONSTRAINT chk_vc__target_id_non_empty CHECK (target_id <> ''),
      CONSTRAINT chk_vc__token_hash_sha256 CHECK (token_hash ~ '^[0-9a-f]{64}$'),
      CONSTRAINT chk_vc__code_hash_sha256 CHECK (code_hash ~ '^[0-9a-f]{64}$'),
      CONSTRAINT chk_vc__failed_attempt_count_non_negative CHECK (failed_attempt_count >= 0),
      CONSTRAINT chk_vc__resend_count_non_negative CHECK (resend_count >= 0),
      CONSTRAINT chk_vc__expires_at_chronological CHECK (expires_at > created_at),
      CONSTRAINT chk_vc__resent_at_chronological CHECK (resent_at IS NULL OR resent_at >= created_at),
      CONSTRAINT chk_vc__used_at_superseded_at_mutually_exclusive
        CHECK (used_at IS NULL OR superseded_at IS NULL)
    );
    CREATE UNIQUE INDEX uidx_vc__actor_id_action_id_target_id_active
      ON verification_challenge (actor_id, action_id, target_id)
      WHERE used_at IS NULL AND superseded_at IS NULL;
    CREATE INDEX idx_vc__actor_id_action_id_created_at
      ON verification_challenge (actor_id, action_id, created_at);
    CREATE INDEX idx_vc__created_at ON verification_challenge (created_at);

    Prune it on a schedule with deleteExpiredInBatches, deleting the rows older than the longest validitySeconds or issueWindowSeconds of any policy. A younger row may still be consumed, or count toward a limit:

    ts
    import { deleteExpiredInBatches } from 'jg-postgres';
    
    await deleteExpiredInBatches(postgres, {
      table: 'verification_challenge',
      olderThan: { seconds: 3_600 },
    });

    A table created from jg-postgres 0.3.0’s README lacks the two columns resend uses. issue and consume keep working without them, but add them before deploying code that calls resend. Both are filled for every existing row, 0 and NULL, so the checks hold:

    sql
    ALTER TABLE verification_challenge
      ADD COLUMN resend_count smallint NOT NULL DEFAULT 0,
      ADD COLUMN resent_at timestamptz NULL,
      ADD CONSTRAINT chk_vc__resend_count_non_negative CHECK (resend_count >= 0),
      ADD CONSTRAINT chk_vc__resent_at_chronological
        CHECK (resent_at IS NULL OR resent_at >= created_at);

    Error log

    jg-postgres/error-log’s createErrorLog records errors in a table, such as the ones an API’s exception filter catches, for an admin page to list. It never rejects, so recording an error can’t fail the request that hit it:

    ts
    import { createErrorLog } from 'jg-postgres/error-log';
    
    const errorLog = createErrorLog(postgres, {
      origin: 'api', // what reports the errors: 1 to 256 characters
      table: 'error_log', // the default
      redactKeys: ['password', 'token'], // replaced in an Exception's data, at any depth, any case
      maxMessageLength: 8_192, // the default, the column's size
      maxPayloadBytes: 1_024, // the default
      maxBatchSize: 256, // the default: the rows each INSERT writes
      onRecorded: ({ count }) => unreadErrors.increment(count), // optional, not awaited
    });
    
    await errorLog.record({ error, userInfo: { userId } }); // true when a row was inserted
    
    // one row per origin and key, however often the failure repeats
    await errorLog.recordMany(
      failures.map((failure) => ({ error: failure.error, deduplicationKey: failure.jobId })),
    );

    A row’s error is the error’s message, prefixed with its code, such as NOT_FOUND: The user doesn't exist., without null characters, and cut to maxMessageLength characters, ending in [truncated]. An Exception’s data, when it’s an object, is its payload, with redactKeys replaced, cycles left out, and null characters removed; data larger than maxPayloadBytes as JSON, or nested more than 256 levels deep, is left out of that row alone. userInfo is stored as given, without its undefined fields, and left out the same way when it’s nested more than 256 levels deep. An entry’s own origin overrides the log’s, and an origin that isn’t 1 to 256 characters falls back to it.

    A deduplicationKey is stored as its SHA-256 digest in lowercase hex, the same digest as Node.js’s createHash('sha256').update(key).digest('hex'), and the table keeps one row per origin and digest: a repeat inserts nothing and resolves to false, or counts 0. An app moving digests it computed itself onto the log passes the strings it hashed, not the digests, so its stored rows keep their identity. Without a key, every record inserts a row.

    A write runs in one transaction with timeouts, 5 seconds per statement and 1 second for a lock by default, so a table another transaction locks stops it quickly. A write that fails, for a lock, a constraint, or a missing table, inserts nothing and goes to the database’s onError as ERROR_LOG_WRITE_FAILED, with its SQLSTATE and its entry count but without the rows or the database’s message, which can quote them; record then resolves to false and recordMany to 0. onRecorded runs after a write that inserted rows commits; what it throws or rejects with goes to onError too.

    The app creates the table, under any name it passes as table:

    sql
    CREATE TABLE error_log (
      id bigint GENERATED ALWAYS AS IDENTITY,
      origin varchar(256) NOT NULL,
      error varchar(8192) NOT NULL,
      user_info jsonb NULL,
      payload jsonb NULL,
      deduplication_hash char(64) NULL,
      event_time timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT pk_el__id PRIMARY KEY (id),
      CONSTRAINT chk_el__origin_non_empty CHECK (origin <> ''),
      CONSTRAINT chk_el__error_non_empty CHECK (error <> ''),
      CONSTRAINT chk_el__user_info_object
        CHECK (user_info IS NULL OR jsonb_typeof(user_info) = 'object'),
      CONSTRAINT chk_el__payload_object CHECK (payload IS NULL OR jsonb_typeof(payload) = 'object'),
      CONSTRAINT chk_el__deduplication_hash_sha256
        CHECK (deduplication_hash IS NULL OR deduplication_hash ~ '^[0-9a-f]{64}$'),
      CONSTRAINT uq_el__origin_deduplication_hash UNIQUE (origin, deduplication_hash)
    );
    CREATE INDEX idx_el__origin_id_desc ON error_log (origin, id DESC);
    CREATE INDEX idx_el__event_time ON error_log (event_time);

    List it for an admin page with listByCursor, newest first, and prune it with deleteExpiredInBatches:

    ts
    import { deleteExpiredInBatches, listByCursor } from 'jg-postgres';
    
    const rows = await listByCursor(postgres.pool, {
      table: 'error_log',
      columns: ['id', 'origin', 'error', 'event_time'],
      filters: [{ column: 'origin', value: 'api' }],
      after: cursor,
      limit: 51,
    });
    
    await deleteExpiredInBatches(postgres, {
      table: 'error_log',
      timestampColumn: 'event_time',
      olderThan: { days: 90 },
    });

    Database summaries

    readDatabaseSummary and listTableSizes read what an admin dashboard or a health check shows about the database, and diffTables compares the tables with the ones a migration should have created:

    ts
    import { diffTables, listTableSizes, readDatabaseSummary } from 'jg-postgres';
    
    const summary = await readDatabaseSummary(postgres.pool); // the public schema, or { schema }
    // { name, serverVersion, serverVersionNumber, sizeBytes, activeConnections, maxConnections, tableCount }
    
    const tables = await listTableSizes(postgres.pool); // [{ name, totalBytes }], sorted by name
    const { missing, unexpected } = diffTables(
      tables.map(({ name }) => name),
      ['app_user', 'session'],
    );

    Sizes and counts are numbers, and sizes include indexes and TOAST data. activeConnections counts the connections to this database running a query. Without the pg_read_all_stats role, PostgreSQL shows a role only its own connections, so the count is lower than the server’s.

    Counter tables

    defineCounterTable builds the queries that change counter rows, such as an account’s daily usage or a balance, quoting every name once and sending every value as a parameter. applyCounterQueries runs them in the caller’s transaction, sorted by row, so two transactions that change the same rows lock them in the same order and never deadlock:

    ts
    import { applyCounterQueries, defineCounterTable } from 'jg-postgres';
    
    const dailyUsage = defineCounterTable({
      table: 'daily_usage',
      keyColumns: ['account_id', 'day'],
      counters: ['request_count', 'token_count'],
    });
    
    await postgres.transaction((client) =>
      applyCounterQueries(client, [
        // inserts the row, or adds to it
        dailyUsage.buildIncrement(
          { account_id: accountId, day },
          { request_count: 1, token_count: tokens },
        ),
        // adds to a row that must exist, or throws COUNTER_ROW_NOT_FOUND
        dailyUsage.buildAdjustment({ account_id: accountId, day }, { token_count: -refunded }),
      ]),
    );

    An increment is an INSERT … ON CONFLICT (key columns) DO UPDATE, so the table needs a unique constraint on exactly the key columns, and a default, such as 0, for every counter. Amounts are whole numbers or bigints within BIGINT: positive to increment, and non-zero to adjust. A counter that would leave BIGINT’s range fails with SQLSTATE 22003, which isNumericValueOutOfRangeError checks, and the transaction rolls back.

    Constraint errors

    ts
    import { isUniqueViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    
    if (isUniqueViolationError(error, 'uq_user_account__email')) {
      // the email is already registered
    }

    isDatabaseError and the checks for unique, foreign key, not-null, check, and restrict violations, string truncation, numeric overflow, invalid text, serialization failures, deadlocks, and canceled queries read the SQLSTATE code. The constraint checks take an optional constraint name.

    Advisory locks

    createAdvisoryLockKey turns a name into the 64-bit key PostgreSQL’s advisory locks take. lockTransaction holds one until the transaction ends, waiting while another holds it. withSessionLock holds one on a connection across several transactions, or skips the work when another session holds it:

    ts
    import { createAdvisoryLockKey, createPostgres, withSessionLock } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const outcome = await withSessionLock(
      postgres,
      createAdvisoryLockKey('user-account-deletion:42'),
      async (lock) => {
        await lock.transaction(async (client) => {
          await client.query('DELETE FROM user_session WHERE user_account_id = $1;', ['42']);
        });
        lock.assertActive(); // throws SESSION_LOCK_LOST once the lock's connection is gone
        await lock.transaction(async (client) => {
          await client.query('DELETE FROM user_account WHERE id = $1;', ['42']);
        });
        return 'deleted';
      },
    );
    // { acquired: false } when another request holds the lock

    lock.transaction runs a transaction on the lock’s client with runTransaction, after checking the lock is still held, and takes the same timeouts. Once the operation ends, the lock is released and its client returned to the pool, unless a transaction on it is still open, such as one the operation began with its own BEGIN, or ended in an unknown state: then the client is destroyed, which closes its connection and releases the lock with it.

    Cursor pages and ordered lists

    listByCursor lists a page of rows after a cursor, and buildCursorPage turns a page listed with one extra row into { items, nextCursor }. moveUp and moveDown swap a row’s sort order with its neighbor’s, in their own transaction under the list’s lock, and lockOrderedList takes the same lock for an append. Every table and column name is quoted.

    A record store

    jg-postgres/record-store keeps small JSON records, such as counters or a feature’s settings, one row each in a record_store table, which the app creates:

    sql
    CREATE TABLE IF NOT EXISTS record_store (
      id    varchar(512),
      value jsonb        NOT NULL,
    
      CONSTRAINT pk_rs__id PRIMARY KEY (id),
      CONSTRAINT chk_rs__id_non_empty CHECK (id <> ''),
      CONSTRAINT chk_rs__value_object CHECK (jsonb_typeof(value) = 'object')
    );
    ts
    import { createPostgres } from 'jg-postgres';
    import { createRecordStore } from 'jg-postgres/record-store';
    import { z } from 'zod';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const counters = createRecordStore({
      postgres,
      id: 'admin:unread-counts',
      defaults: { notifications: 0, reports: 0 },
      schema: z.object({ notifications: z.number(), reports: z.number() }),
    });
    
    await counters.incrementNumber('notifications', 1); // atomic, so concurrent increments all count
    await counters.setNumber('reports', 0); // leaves the other fields as they are
    await counters.get(); // { notifications: 1, reports: 0 }, checked with the schema

    The defaults fill every missing or null field when the record is read, and are the only keys a write keeps. Every method takes an optional transaction’s client, to run in that transaction without committing it.

    A delivery inbox

    jg-postgres/delivery-inbox stores deliveries an app must process exactly once, such as webhook events, before acknowledging them, recognizes replays, and hands each due delivery to one worker at a time under a lease. The app creates the table, under any name:

    sql
    CREATE TABLE IF NOT EXISTS webhook_delivery (
      delivery_key     varchar(512) NOT NULL,
      digest           char(64)     NOT NULL,
      payload          jsonb        NOT NULL,
      created_at       timestamptz  NOT NULL DEFAULT statement_timestamp(),
      due_at           timestamptz  NOT NULL,
      expires_at       timestamptz  NOT NULL,
      lease_id         uuid         NULL,
      lease_expires_at timestamptz  NULL,
      processed_at     timestamptz  NULL,
    
      CONSTRAINT pk_wd__delivery_key PRIMARY KEY (delivery_key),
      CONSTRAINT chk_wd__delivery_key_non_empty CHECK (delivery_key <> ''),
      CONSTRAINT chk_wd__digest_sha256 CHECK (digest ~ '^[0-9a-f]{64}$'),
      CONSTRAINT chk_wd__expires_at_chronological CHECK (expires_at > created_at),
      CONSTRAINT chk_wd__processed_at_chronological
        CHECK (processed_at IS NULL OR processed_at >= created_at),
      CONSTRAINT chk_wd__lease_complete CHECK ((lease_id IS NULL) = (lease_expires_at IS NULL)),
      CONSTRAINT chk_wd__processed_without_lease CHECK (processed_at IS NULL OR lease_id IS NULL)
    );
    CREATE INDEX IF NOT EXISTS idx_wd__due_at_delivery_key_pending
      ON webhook_delivery (due_at, delivery_key)
      WHERE processed_at IS NULL;
    CREATE INDEX IF NOT EXISTS idx_wd__processed_at_delivery_key_processed
      ON webhook_delivery (processed_at, delivery_key)
      WHERE processed_at IS NOT NULL;
    ts
    import { createPostgres } from 'jg-postgres';
    import { createDeliveryInbox } from 'jg-postgres/delivery-inbox';
    import { z } from 'zod';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const inbox = createDeliveryInbox(postgres, {
      table: 'webhook_delivery',
      schema: z.object({ eventId: z.string() }), // checks the payload on receive and on claim
      leaseSeconds: 600, // how long a claim holds a delivery
      retrySeconds: 60, // how long a deferred delivery waits
      expirySeconds: 86_400, // how long after receipt it may still be claimed
    });
    
    // in the webhook route, before answering 2xx
    await inbox.receive({ key: webhookId, digest: bodySha256, payload: { eventId } });
    
    // in a worker
    for (const key of await inbox.listDue(32)) {
      const claim = await inbox.claim(key);
      // null when another worker has it, or it's done or expired
      if (claim === null) {
        continue;
      }
      try {
        await handleEvent(claim.payload);
        await inbox.finish(claim.key, claim.leaseId);
      } catch {
        await inbox.defer(claim.key, claim.leaseId);
      }
    }

    receive resolves to true for a new delivery and false for a replay with the same digest and payload, and throws DELIVERY_REPLAY_MISMATCH for a key received before with another. listDue returns the due keys, oldest first. claim takes a lease, pushing the delivery’s due time to the lease’s end, so a worker that dies without finishing leaves it due again then; it resolves to null when the delivery isn’t due, is leased, was processed, or is past its expiry, which closes it. finish marks it processed and defer makes it due after retrySeconds, never later than its expiry; both resolve to false when the lease ended, so a worker whose lease ran out can’t touch a delivery another worker claimed. Delete processed deliveries with deleteExpiredInBatches, on processed_at, which never matches a pending delivery:

    ts
    await deleteExpiredInBatches(postgres, {
      table: 'webhook_delivery',
      timestampColumn: 'processed_at',
      keyColumn: 'delivery_key',
      olderThan: { days: 7 },
      signal, // the maintenance task's, so shutdown stops it between batches
    });

    Errors

    Code When
    TRANSACTION_OUTCOME_UNKNOWN The connection was lost during COMMIT
    TRANSACTION_ALREADY_ACTIVE runTransaction or a lock’s transaction was given a client that’s already in a transaction
    SESSION_LOCK_LOST The connection that held a session lock was lost
    INVALID_IDENTIFIER A name is empty, holds a null character, or is longer than 63 bytes
    ROW_NOT_FOUND The row to move doesn’t exist in the ordered list
    ROW_ALREADY_FIRST The row to move up is already first
    ROW_ALREADY_LAST The row to move down is already last
    MOVE_FAILED The move didn’t update exactly two rows
    INVALID_EXPIRED_DELETION deleteExpiredInBatches was given both olderThan and cutoff or neither, an age or a date that isn’t valid, a batch size outside 1 to 8,192, or a filter without a column
    INVALID_TIMEOUT_PROFILE A timeout profile’s seconds aren’t positive and finite, or its lock timeout is longer than its statement timeout
    INVALID_OPTIONAL_READ_OPTIONS An optional reader’s database, limits, or timeouts aren’t valid
    INVALID_USAGE_ADMISSION A usage admission’s ids, limit, or seconds aren’t valid, or it has a cooldown without a scope
    INVALID_VERIFICATION_POLICY The verification policies or the code length aren’t valid
    INVALID_VERIFICATION_INPUT A verification binding’s ids aren’t valid, its action has no policy, issue or resend has no delivery function, or resend’s policy has no resend limit
    VERIFICATION_DELIVERY_FAILED The delivery function threw, after the challenge or its resend was committed
    INVALID_COUNTER_TABLE A counter table has no key column or no counter, or repeats a name
    INVALID_COUNTER_CHANGE A counter row’s key doesn’t have exactly the key columns, or an amount isn’t a whole, non-zero amount within BIGINT
    COUNTER_ROW_NOT_FOUND A counter query changed no row, because the row to adjust doesn’t exist
    INVALID_ERROR_LOG_OPTIONS An error log’s origin, redact keys, limits, or onRecorded aren’t valid
    ERROR_LOG_WRITE_FAILED An error log’s write failed, so nothing was inserted; it’s reported to onError, never thrown
    SCHEMA_NOT_EMPTY initializeSchemaOnce found objects in the public schema but not the marker table
    SCHEMA_MARKER_MISSING initializeSchemaOnce’s statements didn’t create the marker table, so they were rolled back
    INVALID_TEST_DATABASE_NAME A test database’s name isn’t lowercase letters, digits, and underscores within 63 bytes, or, to drop, doesn’t start with this process’s test_<pid>_ prefix
    INVALID_DELIVERY_INBOX_OPTIONS A delivery inbox’s table, schema, or seconds, or a listDue limit, aren’t valid
    INVALID_DELIVERY A delivery’s key, digest, or payload, or a lease id, isn’t valid
    DELIVERY_REPLAY_MISMATCH A delivery’s key was received before with another digest or payload

    A query’s own error, such as a constraint violation, is node-postgres’s DatabaseError, unchanged.

    Generated from TSDoc

    API reference

    Every export of [email protected], 101 in all, with its signature, its errors, and an example.

    jg-postgres

    Functionsjg-postgres

    admitUsage
    function

    Decides, atomically, whether an actor may do a rate-limited action now, such as sending an invitation, and records it when they may. It refuses with cooldown while the same action on the same scope was accepted less than cooldownSeconds ago, by any actor, and with limit once the actor did the action limit times within windowSeconds. Concurrent calls queue on transaction advisory locks, the scope's then the actor's, so they never both pass, and every comparison uses the database's clock. It needs the usage_event table the README defines.

    Signature
    admitUsage(
      postgres: IPostgres,
      input: IUsageAdmissionInput,
    ): Promise<IUsageAdmission>

    Parameters

    postgresIPostgres

    The database.

    inputIUsageAdmissionInput

    The actor, the action, the optional scope, the limit and its window, and the optional cooldown.

    Returns

    Promise<IUsageAdmission>

    A promise that resolves to the outcome, with retryAt, an ISO 8601 UTC timestamp: when the scope's cooldown ends, or null without one.

    Throws

    • INVALID_USAGE_ADMISSIONThe usage admission needs an actor id of 1 to 256 characters, an action id of 1 to 128, a scope key of 1 to 256 when given, a whole positive limit, and positive seconds, with a cooldown only for a scope.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { admitUsage, createPostgres } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const admission = await admitUsage(postgres, {
      actorId: '42',
      actionId: 'send-invitation',
      scopeKey: '[email protected]',
      limit: 20,
      windowSeconds: 86_400,
      cooldownSeconds: 60,
    });
    if (admission.outcome !== 'accepted') {
      // tell the user when to try again: admission.retryAt, or tomorrow for 'limit'
    }
    applyCounterQueries
    function

    Runs counter queries one after another on a transaction's client, sorted by their lock keys, so two transactions changing the same rows lock them in the same order and never deadlock each other. Queries for the same row keep their order. Each must change exactly one row, so an adjustment of a row that doesn't exist throws, and the caller's transaction rolls back. A counter that would leave BIGINT's range fails with SQLSTATE 22003, as isNumericValueOutOfRangeError checks.

    Signature
    applyCounterQueries(
      client: PoolClient,
      queries: readonly ICounterQuery[],
    ): Promise<void>

    Parameters

    clientPoolClient

    The client of the transaction to run them in.

    queriesreadonly ICounterQuery[]

    The queries, from defineCounterTable's builders. The list isn't changed.

    Returns

    Promise<void>

    A promise that resolves once every query ran.

    Throws

    • COUNTER_ROW_NOT_FOUNDThe counter query changed no row, because the row to adjust doesn't exist.
    Example
    import { applyCounterQueries, createPostgres, defineCounterTable } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const balances = defineCounterTable({
      table: 'account_balance',
      keyColumns: ['account_id'],
      counters: ['credit_count'],
    });
    await postgres.transaction((client) =>
      applyCounterQueries(client, [
        balances.buildAdjustment({ account_id: '42' }, { credit_count: -10 }),
        balances.buildIncrement({ account_id: '7' }, { credit_count: 10 }),
      ]),
    );
    buildCursorPage
    function

    Builds a page from rows listed with one more than the page's size, so the extra row tells whether another page follows without counting the table.

    Signature
    buildCursorPage<T>(
      rows: readonly T[],
      limit: number,
      toCursor: (row: T) => string,
    ): ICursorPage<T>

    Parameters

    rowsreadonly T[]

    The rows, listed with a limit of the page size plus one.

    limitnumber

    The page size.

    toCursor(row: T) => string

    Reads the cursor from a row, such as its ID.

    Returns

    ICursorPage<T>

    The page's rows, and the last one's cursor when more follow, otherwise null.

    Example
    import { buildCursorPage } from 'jg-postgres';
    
    buildCursorPage([{ id: '3' }, { id: '2' }, { id: '1' }], 2, ({ id }) => id);
    // => { items: [{ id: '3' }, { id: '2' }], nextCursor: '2' }
    createAdvisoryLockKey
    function

    Turns a lock's name into the signed 64-bit key PostgreSQL's advisory locks take: the first 8 bytes of the name's SHA-256 hash. The same name always gives the same key, in every process.

    Signature
    createAdvisoryLockKey(name: string): string

    Parameters

    namestring

    The lock's name, such as user-account-deletion:42.

    Returns

    string

    The key, as a string, such as '7480330268761432310'.

    Example
    import { createAdvisoryLockKey } from 'jg-postgres';
    
    createAdvisoryLockKey('moldea'); // => '7480330268761432310'
    createOptionalReader
    function

    Creates a reader for optional data, such as counters in a page's header, that must never delay or crowd out essential work. A read is skipped, giving null at once, when the reader already runs maxActiveReads reads, a request waits for a client, or the pool can't give more clients than reservedIdleClients, counting idle ones and the room left to open new ones. A running read gives null once admissionSeconds pass, and is shared by every caller of the same key until it ends. Each read runs in a read-only transaction with short timeouts of its own, and never throws.

    Signature
    createOptionalReader(options: IOptionalReaderOptions): IOptionalReader

    Parameters

    optionsIOptionalReaderOptions

    The database, and optionally the limits and the reads' timeouts.

    Returns

    IOptionalReader

    The reader.

    Throws

    • INVALID_OPTIONAL_READ_OPTIONSThe optional reader needs a database, whole positive maxActiveReads, whole reservedIdleClients from 0, positive admissionSeconds, and a valid timeout profile.
    Example
    import { createOptionalReader, createPostgres } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    declare const accountId: string;
    
    const counters = createOptionalReader({ postgres });
    
    const unread = counters.read(
      `unread:${accountId}`,
      { text: 'SELECT count(*)::int AS count FROM notification WHERE account_id = $1 AND read_at IS NULL;', values: [accountId] },
      (row) => (row as { count: number }).count,
    );
    const count = await unread.completion; // a number, or null when the database is busy
    createPostgres
    function

    Creates a PostgreSQL pool with the helpers every query, transaction, and lock uses. The pool parses NUMERIC as a number and TIMESTAMPTZ as an ISO 8601 UTC string, keeps BIGINT as a string, and sends errors no caller awaits, such as an idle connection the server closed, to onError instead of crashing the process.

    Signature
    createPostgres(config: IPostgresConfig): IPostgres

    Parameters

    configIPostgresConfig

    node-postgres's pool configuration, plus onError.

    Returns

    IPostgres

    The pool and its helpers.

    Example
    import { createPostgres } from 'jg-postgres';
    
    const postgres = createPostgres({
      host: 'localhost',
      database: 'app',
      user: 'app',
      password: 'secret',
      max: 10,
      connectionTimeoutMillis: 30_000,
      statement_timeout: 60_000,
      lock_timeout: 30_000,
      idle_in_transaction_session_timeout: 300_000,
    });
    
    const users = await postgres.query<{ id: string }>('SELECT id FROM user_account LIMIT $1;', [10]);
    await postgres.close();
    createVerificationChallenges
    function

    Creates the functions that issue and consume verification challenges, such as the code that confirms a new email address. A challenge is bound to an actor, an action, and a target; only the SHA-256 hashes of its token and code are stored, in a verification_challenge table the README defines, and every comparison uses the database's clock.

    issue refuses with limit once the actor was issued the action's issueLimit challenges within issueWindowSeconds, over every target, so concurrent issues queue on a transaction advisory lock. Otherwise it supersedes the binding's active challenge, commits the new one, and calls deliver with the code. resend sends the active challenge a new code under the same token and expiry, which stops the earlier code from working, up to the policy's resendLimit and at most once per resendCooldownSeconds. consume uses the challenge when the code matches, or counts a failed attempt, and every failure resolves to false alike.

    Signature
    createVerificationChallenges(
      postgres: IPostgres,
      options: IVerificationChallengesOptions,
    ): IVerificationChallenges

    Parameters

    postgresIPostgres

    The database.

    optionsIVerificationChallengesOptions

    Each action's policy, keyed by its action id, and the code's digits.

    Returns

    IVerificationChallenges

    The functions.

    Throws

    • INVALID_VERIFICATION_POLICYThe verification challenges need at least one policy, each for an action id of 1 to 128 characters, with whole validity and window seconds of at least 1, a whole issue limit of at least 1, a whole failed-attempt limit from 1 to 32767, and, when given, a whole resend limit from 1 to 32767 and whole resend cooldown seconds of at least 1, and a whole code length from 4 to 10.
    Example
    import { createPostgres, createVerificationChallenges } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    declare const sendEmail: (to: string, text: string) => Promise<void>;
    
    const challenges = createVerificationChallenges(postgres, {
      policies: {
        'verify-email': {
          validitySeconds: 600,
          maxFailedAttempts: 5,
          issueLimit: 5,
          issueWindowSeconds: 3_600,
          resendLimit: 3,
          resendCooldownSeconds: 60,
        },
      },
    });
    const binding = { actorId: '42', actionId: 'verify-email', targetId: '[email protected]' };
    const issued = await challenges.issue(binding, ({ code, targetId }) =>
      sendEmail(targetId, `Your code is ${code}`),
    );
    if (issued.outcome === 'issued') {
      // when the user asks for another code
      await challenges.resend({ ...binding, challengeToken: issued.challengeToken }, ({ code }) =>
        sendEmail(binding.targetId, `Your new code is ${code}`),
      );
      // later, with the code the user typed
      const isVerified = await challenges.consume({
        ...binding,
        challengeToken: issued.challengeToken,
        code: '123456',
      });
    }
    defineCounterTable
    function

    Defines a table of counters, such as an account's daily usage, and gives the functions that build the queries changing its rows. Every name is quoted once, and every value is a parameter. The table needs a unique constraint on exactly the key columns, for the increments' ON CONFLICT, and a default for every counter. Run the queries with applyCounterQueries, which orders them so concurrent transactions lock rows in the same order.

    Signature
    defineCounterTable<K extends string, C extends string>(
      definition: ICounterTableDefinition<K, C>,
    ): ICounterTable<K, C>

    Parameters

    definitionICounterTableDefinition<K, C>

    The table, its key columns, and its counters.

    Returns

    ICounterTable<K, C>

    The query builders.

    Throws

    • INVALID_COUNTER_TABLEThe counter table needs at least one key column and one counter, every name distinct.
    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    Example
    import { defineCounterTable } from 'jg-postgres';
    
    const dailyUsage = defineCounterTable({
      table: 'daily_usage',
      keyColumns: ['account_id', 'day'],
      counters: ['request_count', 'token_count'],
    });
    const increment = dailyUsage.buildIncrement(
      { account_id: '42', day: '2026-10-19' },
      { request_count: 1, token_count: 1_250n },
    );
    // increment.text: INSERT INTO "daily_usage" ("account_id", "day", "request_count", "token_count")
    //   VALUES ($1, $2, $3, $4) ON CONFLICT ("account_id", "day") DO UPDATE SET ...
    // increment.values: ['42', '2026-10-19', '1', '1250']
    defineTimeoutProfile
    function

    Defines how long a kind of work may run: a statement on the server, a wait for a lock, and the client's wait for the server's answer, which is the statement timeout plus a grace, so the server's own timeout error arrives first. A slow report and an interactive request each get one.

    Signature
    defineTimeoutProfile(
      options: { statementTimeoutSeconds: number; lockTimeoutSeconds: number; queryGraceSeconds?: number },
    ): ITimeoutProfile

    Parameters

    options{ statementTimeoutSeconds: number; lockTimeoutSeconds: number; queryGraceSeconds?: number }

    The statement and lock timeouts, and the client's grace, 15 seconds by default, all in seconds.

    Returns

    ITimeoutProfile

    The profile, frozen.

    Throws

    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    Example
    import { defineTimeoutProfile } from 'jg-postgres';
    
    const REPORT_TIMEOUTS = defineTimeoutProfile({ statementTimeoutSeconds: 120, lockTimeoutSeconds: 10 });
    REPORT_TIMEOUTS.queryTimeoutSeconds; // 135
    deleteExpiredInBatches
    function

    Deletes a table's rows older than a cutoff, a batch at a time, until a batch deletes nothing. The cutoff is computed once, from olderThan on the database's clock or from cutoff, and a row exactly at it is kept. Each batch is one statement that locks the oldest expired rows, skipping rows another transaction holds, and deletes them by keyColumn, which must be unique and not null: a key that repeats would delete rows that haven't expired. With timeouts, each batch runs as a transaction of its own with them. A signal stops the deletion between batches: once it aborts, no further statement starts, and the call rejects with its reason after the batch in flight settles, leaving the remaining rows for a later call.

    Signature
    deleteExpiredInBatches(
      postgres: IPostgres,
      options: IExpiredRowDeletionOptions,
    ): Promise<IExpiredRowDeletion>

    Parameters

    postgresIPostgres

    The database.

    optionsIExpiredRowDeletionOptions

    The table, its timestamp and key columns, how old a row must be, and the batches.

    Returns

    Promise<IExpiredRowDeletion>

    A promise that resolves to the rows deleted and the cutoff.

    Throws

    • INVALID_EXPIRED_DELETIONThe expired-row deletion needs exactly one of olderThan, with whole months, days, and seconds of at least 0 that are not all 0, and cutoff, a valid date, a whole batch size from 1 to 8192, and filters that each name a column.
    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    • ErrorThe signal's reason when the signal aborts.
    Example
    import { createPostgres, deleteExpiredInBatches } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const { deletedCount } = await deleteExpiredInBatches(postgres, {
      table: 'audit_event',
      olderThan: { months: 6 },
    });
    diffTables
    function

    Compares the tables a schema has with the ones an app expects, such as in a health check after a migration. Names compare exactly, as PostgreSQL stores them.

    Signature
    diffTables(actual: readonly string[], expected: readonly string[]): ITableDiff

    Parameters

    actualreadonly string[]

    The tables that exist, such as listTableSizes' names.

    expectedreadonly string[]

    The tables the app expects.

    Returns

    ITableDiff

    The expected tables that are missing, and the tables that aren't expected, each sorted and without duplicates.

    Example
    import { diffTables } from 'jg-postgres';
    
    diffTables(['app_user', 'session'], ['app_user', 'invitation']);
    // => { missing: ['invitation'], unexpected: ['session'] }
    ensureDatabase
    function

    Creates a database when the server doesn't have it yet, connecting to the maintenance database, postgres, with the rest of the configuration. Another process creating it at the same time counts as success, so every replica of an app can call it at startup.

    Signature
    ensureDatabase(config: IPostgresConfig): Promise<void>

    Parameters

    configIPostgresConfig

    The configuration of the database to create, as createPostgres takes it.

    Returns

    Promise<void>

    A promise that resolves once the database exists.

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    Example
    import { createPostgres, ensureDatabase, type IPostgresConfig } from 'jg-postgres';
    
    const config: IPostgresConfig = { host: 'localhost', database: 'app', user: 'app', password: 'secret' };
    await ensureDatabase(config);
    const postgres = createPostgres(config);
    initializeSchemaOnce
    function

    Creates an app's schema once: in one transaction, under an advisory lock, it skips when the public schema already has the marker table, refuses a public schema that holds anything else, and otherwise runs the statements and checks they created the marker table. Every replica of an app can call it at startup: one creates the schema, and the others wait for it and skip. A statement that fails, or a marker the statements didn't create, rolls everything back.

    Signature
    initializeSchemaOnce(
      postgres: IPostgres,
      options: IInitializeSchemaOptions,
    ): Promise<boolean>

    Parameters

    postgresIPostgres

    The database.

    optionsIInitializeSchemaOptions

    The statements, the marker table they create, and the transaction's timeouts.

    Returns

    Promise<boolean>

    A promise that resolves to true when it created the schema, and false when the marker table was already there.

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    • SCHEMA_NOT_EMPTYThe public schema holds objects but not the marker table, so its initialization never finished.
    • SCHEMA_MARKER_MISSINGThe schema statements didn't create the marker table.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { createPostgres, initializeSchemaOnce } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    await initializeSchemaOnce(postgres, {
      statements: [
        'CREATE TABLE note (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text NOT NULL);',
        'CREATE TABLE schema_migration (version integer PRIMARY KEY);',
      ],
      markerTable: 'schema_migration',
    });
    isCheckViolationError
    function

    Checks whether an error is a check violation (SQLSTATE 23514), optionally on one constraint.

    Signature
    isCheckViolationError(
      error: unknown,
      constraint?: string,
    ): error is DatabaseError

    Parameters

    errorunknown

    The error.

    constraint?string

    The check constraint's name, when it must match.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isCheckViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    isCheckViolationError(error, 'ck_order__quantity');
    isDatabaseError
    function

    Checks whether an error is one PostgreSQL returned, with its SQLSTATE code, as node-postgres reports it.

    Signature
    isDatabaseError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether it's a node-postgres DatabaseError.

    Example
    import { isDatabaseError } from 'jg-postgres';
    
    isDatabaseError(new Error('Connection terminated')); // => false
    isDeadlockDetectedError
    function

    Checks whether an error is a detected deadlock (SQLSTATE 40P01), which a retry of the whole transaction may fix.

    Signature
    isDeadlockDetectedError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isDeadlockDetectedError } from 'jg-postgres';
    
    declare const error: unknown;
    isDeadlockDetectedError(error);
    isForeignKeyViolationError
    function

    Checks whether an error is a foreign key violation (SQLSTATE 23503), optionally on one constraint.

    Signature
    isForeignKeyViolationError(
      error: unknown,
      constraint?: string,
    ): error is DatabaseError

    Parameters

    errorunknown

    The error.

    constraint?string

    The foreign key's name, when it must match.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isForeignKeyViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    isForeignKeyViolationError(error, 'fk_order__user_account_id');
    isInTransaction
    function

    Checks whether a client is inside a transaction runTransaction began, including one whose end is unknown, such as a COMMIT the server never answered or a ROLLBACK that failed. Release such a client with client.release(isInTransaction(client)), which destroys it.

    Signature
    isInTransaction(client: PoolClient): boolean

    Parameters

    clientPoolClient

    The client.

    Returns

    boolean

    Whether the client is inside such a transaction.

    Example
    import { createPostgres, isInTransaction, runTransaction } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const client = await postgres.pool.connect();
    try {
      await runTransaction(client, async (transactionClient) => {
        isInTransaction(transactionClient); // true
      });
    } finally {
      client.release(isInTransaction(client));
    }
    isInvalidTextRepresentationError
    function

    Checks whether an error is an invalid text representation (SQLSTATE 22P02), such as text where a UUID belongs.

    Signature
    isInvalidTextRepresentationError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isInvalidTextRepresentationError } from 'jg-postgres';
    
    declare const error: unknown;
    isInvalidTextRepresentationError(error);
    isNotNullViolationError
    function

    Checks whether an error is a not-null violation (SQLSTATE 23502).

    Signature
    isNotNullViolationError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isNotNullViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    isNotNullViolationError(error);
    isNumericValueOutOfRangeError
    function

    Checks whether an error is a numeric value out of range (SQLSTATE 22003).

    Signature
    isNumericValueOutOfRangeError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isNumericValueOutOfRangeError } from 'jg-postgres';
    
    declare const error: unknown;
    isNumericValueOutOfRangeError(error);
    isQueryCanceledError
    function

    Checks whether an error is a canceled query (SQLSTATE 57014), such as one that ran past statement_timeout.

    Signature
    isQueryCanceledError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isQueryCanceledError } from 'jg-postgres';
    
    declare const error: unknown;
    isQueryCanceledError(error);
    isRestrictViolationError
    function

    Checks whether an error is a restrict violation (SQLSTATE 23001), optionally on one constraint.

    Signature
    isRestrictViolationError(
      error: unknown,
      constraint?: string,
    ): error is DatabaseError

    Parameters

    errorunknown

    The error.

    constraint?string

    The foreign key's name, when it must match.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isRestrictViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    isRestrictViolationError(error);
    isSerializationFailureError
    function

    Checks whether an error is a serialization failure (SQLSTATE 40001), which a retry of the whole transaction may fix.

    Signature
    isSerializationFailureError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isSerializationFailureError } from 'jg-postgres';
    
    declare const error: unknown;
    isSerializationFailureError(error);
    isStringDataRightTruncationError
    function

    Checks whether an error is a string data right truncation (SQLSTATE 22001): a value longer than its column allows.

    Signature
    isStringDataRightTruncationError(error: unknown): error is DatabaseError

    Parameters

    errorunknown

    The error.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isStringDataRightTruncationError } from 'jg-postgres';
    
    declare const error: unknown;
    isStringDataRightTruncationError(error);
    isUniqueViolationError
    function

    Checks whether an error is a unique violation (SQLSTATE 23505), optionally on one constraint.

    Signature
    isUniqueViolationError(
      error: unknown,
      constraint?: string,
    ): error is DatabaseError

    Parameters

    errorunknown

    The error.

    constraint?string

    The unique constraint's or index's name, when it must match.

    Returns

    error is DatabaseError

    Whether the error matches.

    Example
    import { isUniqueViolationError } from 'jg-postgres';
    
    declare const error: unknown;
    if (isUniqueViolationError(error, 'uq_user_account__email')) {
      // the email is taken
    }
    listByCursor
    function

    Lists a page of a table's rows after a cursor, ordered by the cursor column. Every name is quoted, and the order and the cursor comparison use the table's own column, so a selected column can't change them.

    Signature
    listByCursor<T extends QueryResultRow = QueryResultRow>(
      executor: IQueryExecutor,
      options: ICursorListingOptions,
    ): Promise<T[]>

    Parameters

    executorIQueryExecutor

    The pool, or a transaction's client.

    optionsICursorListingOptions

    The table, its columns, the cursor column and direction, filters, the previous page's last cursor, and the limit.

    Returns

    Promise<T[]>

    A promise that resolves to the rows.

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    Example
    import { createPostgres, listByCursor } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const errors = await listByCursor<{ id: string; origin: string }>(postgres.pool, {
      table: 'api_error',
      columns: ['id', 'origin'],
      filters: [{ column: 'origin', value: 'api-admin' }],
      after: '120',
      limit: 20,
    });
    listTableSizes
    function

    Lists the ordinary tables in a schema with their total size on disk, indexes and TOAST data included, sorted by name.

    Signature
    listTableSizes(
      executor: IQueryExecutor,
      options?: IIntrospectionOptions,
    ): Promise<ITableSize[]>

    Parameters

    executorIQueryExecutor

    The pool, or a client.

    options?IIntrospectionOptions

    The schema.

    Defaults to {}.

    Returns

    Promise<ITableSize[]>

    A promise that resolves to the tables.

    Example
    import { createPostgres, listTableSizes } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const tables = await listTableSizes(postgres.pool);
    // [{ name: 'app_user', totalBytes: 65_536 }, { name: 'session', totalBytes: 16_384 }]
    lockOrderedList
    function

    Locks an ordered list for the rest of a transaction, so no move or append changes it meanwhile, such as before appending a row after the list's last sort order. moveUp and moveDown take the same lock.

    Signature
    lockOrderedList(client: PoolClient, list: IOrderedList): Promise<void>

    Parameters

    clientPoolClient

    The transaction's client.

    listIOrderedList

    The table, its sort order column, and the scope that picks one list.

    Returns

    Promise<void>

    A promise that resolves once the lock is held.

    Example
    import { createPostgres, lockOrderedList } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    await postgres.transaction(async (client) => {
      await lockOrderedList(client, { table: 'category', scope: [{ column: 'group_id', value: 1 }] });
      await client.query(
        `INSERT INTO category (group_id, sort_order)
           SELECT 1, COALESCE(MAX(sort_order), 0) + 10 FROM category WHERE group_id = 1;`,
      );
    });
    lockTransaction
    function

    Takes an advisory lock for the rest of a transaction, waiting while another transaction holds it. PostgreSQL releases it when the transaction commits or rolls back.

    Signature
    lockTransaction(client: PoolClient, key: string): Promise<void>

    Parameters

    clientPoolClient

    The transaction's client.

    keystring

    The lock's key, from createAdvisoryLockKey.

    Returns

    Promise<void>

    A promise that resolves once the lock is held.

    Example
    import { createAdvisoryLockKey, createPostgres, lockTransaction } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    await postgres.transaction(async (client) => {
      await lockTransaction(client, createAdvisoryLockKey('invoice-numbers'));
      // only one transaction at a time gets here
    });
    moveDown
    function

    Moves a row one place down an ordered list, by swapping its sort order with the closest larger one, in its own transaction under the list's lock.

    Signature
    moveDown(
      postgres: IPostgres,
      rowId: IRowId,
      options: IMoveOptions,
    ): Promise<void>

    Parameters

    postgresIPostgres

    The database, from createPostgres.

    rowIdIRowId

    The row's identifier.

    optionsIMoveOptions

    The table, its sort order constraint, and, when they differ from the defaults, its ID and sort order columns, and the scope that picks one list.

    Returns

    Promise<void>

    A promise that resolves once the move commits.

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    • MOVE_FAILEDThe move did not update exactly two rows.
    • ROW_NOT_FOUNDThe row does not exist in the ordered list.
    • ROW_ALREADY_LASTThe row is already last in the ordered list.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { createPostgres, moveDown } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    await moveDown(postgres, 42, { table: 'category', sortOrderConstraint: 'uq_category__sort_order' });
    moveUp
    function

    Moves a row one place up an ordered list, by swapping its sort order with the closest smaller one, in its own transaction under the list's lock.

    Signature
    moveUp(postgres: IPostgres, rowId: IRowId, options: IMoveOptions): Promise<void>

    Parameters

    postgresIPostgres

    The database, from createPostgres.

    rowIdIRowId

    The row's identifier.

    optionsIMoveOptions

    The table, its sort order constraint, and, when they differ from the defaults, its ID and sort order columns, and the scope that picks one list.

    Returns

    Promise<void>

    A promise that resolves once the move commits.

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    • MOVE_FAILEDThe move did not update exactly two rows.
    • ROW_NOT_FOUNDThe row does not exist in the ordered list.
    • ROW_ALREADY_FIRSTThe row is already first in the ordered list.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { createPostgres, moveUp } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    await moveUp(postgres, 42, { table: 'category', sortOrderConstraint: 'uq_category__sort_order' });
    quoteIdentifier
    function

    Quotes a table, column, or constraint name for SQL that can't take it as a parameter. A name PostgreSQL would cut short, an empty one, or one with a null character throws instead.

    Signature
    quoteIdentifier(name: string): string

    Parameters

    namestring

    The name, such as order or sort_order.

    Returns

    string

    The quoted name, such as "order".

    Throws

    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    Example
    import { quoteIdentifier } from 'jg-postgres';
    
    quoteIdentifier('order'); // => '"order"'
    quoteIdentifier('say "hi"'); // => '"say ""hi"""'
    readDatabaseSummary
    function

    Reads a summary of the database the executor is connected to, such as for an admin dashboard: its name, the server's version, its size, its active connections out of the server's maximum, and the ordinary tables in a schema. Without the pg_read_all_stats role, PostgreSQL shows only the role's own connections, so activeConnections undercounts.

    Signature
    readDatabaseSummary(
      executor: IQueryExecutor,
      options?: IIntrospectionOptions,
    ): Promise<IDatabaseSummary>

    Parameters

    executorIQueryExecutor

    The pool, or a client.

    options?IIntrospectionOptions

    The schema whose tables are counted.

    Defaults to {}.

    Returns

    Promise<IDatabaseSummary>

    A promise that resolves to the summary.

    Example
    import { createPostgres, readDatabaseSummary } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const summary = await readDatabaseSummary(postgres.pool);
    // { name: 'app', serverVersion: '18.1', serverVersionNumber: 180001, sizeBytes: 8_000_000,
    //   activeConnections: 3, maxConnections: 100, tableCount: 12 }
    runTransaction
    function

    Runs an operation in a transaction on a client the caller already holds, such as a session lock's, committing when it resolves and rolling back when it throws. It refuses a client that's already in a transaction, and never releases the client: release it with client.release(isInTransaction(client)), which destroys a client whose transaction ended in an unknown state.

    Signature
    runTransaction<T>(
      client: PoolClient,
      operation: (client: PoolClient) => Promise<T>,
      options?: IRunTransactionOptions,
    ): Promise<T>

    Parameters

    clientPoolClient

    The client, checked out of the pool by the caller.

    operation(client: PoolClient) => Promise<T>

    The work, given the same client.

    options?IRunTransactionOptions

    The transaction's timeouts, and where a failed ROLLBACK goes.

    Defaults to {}.

    Returns

    Promise<T>

    A promise that resolves to what the operation resolves to, once committed.

    Throws

    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    • TRANSACTION_ALREADY_ACTIVEThe client is already in a transaction, so another can't begin on it.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { createPostgres, isInTransaction, runTransaction } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const client = await postgres.pool.connect();
    try {
      await runTransaction(client, async (transactionClient) => {
        await transactionClient.query('DELETE FROM user_session WHERE user_account_id = $1;', ['42']);
      });
      await runTransaction(client, async (transactionClient) => {
        await transactionClient.query('DELETE FROM user_account WHERE id = $1;', ['42']);
      });
    } finally {
      client.release(isInTransaction(client));
    }
    toPoolTimeouts
    function

    Gives a profile's timeouts as createPostgres takes them, in milliseconds, for a pool whose every query follows the profile.

    Signature
    toPoolTimeouts(
      profile: ITimeoutProfile,
    ): { statement_timeout: number; lock_timeout: number; query_timeout: number }

    Parameters

    profileITimeoutProfile

    The profile.

    Returns

    { statement_timeout: number; lock_timeout: number; query_timeout: number }

    The pool's statement_timeout, lock_timeout, and query_timeout.

    Throws

    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    Example
    import { createPostgres, defineTimeoutProfile, toPoolTimeouts } from 'jg-postgres';
    
    const STANDARD = defineTimeoutProfile({ statementTimeoutSeconds: 30, lockTimeoutSeconds: 5 });
    const postgres = createPostgres({ connectionString: process.env['DATABASE_URL'], ...toPoolTimeouts(STANDARD) });
    withQueryTimeout
    function

    Gives a query the client timeout of a profile, which node-postgres's pool otherwise sets for every query, so a query in a transaction with longer timeouts isn't cut off by the pool's.

    Signature
    withQueryTimeout(
      query: { text: string; values?: unknown[] },
      profile: ITimeoutProfile,
    ): QueryConfig<any[]> & { query_timeout: number }

    Parameters

    query{ text: string; values?: unknown[] }

    The query's text and values.

    profileITimeoutProfile

    The profile.

    Returns

    QueryConfig<any[]> & { query_timeout: number }

    The query, as node-postgres's query methods take it.

    Throws

    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    Example
    import { createPostgres, defineTimeoutProfile, withQueryTimeout } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const REPORT_TIMEOUTS = defineTimeoutProfile({ statementTimeoutSeconds: 120, lockTimeoutSeconds: 10 });
    await postgres.transaction(
      (client) =>
        client.query(withQueryTimeout({ text: 'SELECT build_report($1);', values: [2026] }, REPORT_TIMEOUTS)),
      { timeouts: REPORT_TIMEOUTS },
    );
    withSessionLock
    function

    Runs an operation while holding an advisory lock on one connection, across as many transactions as it needs, run with the lock's transaction, or skips it when another session holds the lock. The lock lasts as long as its connection, so the operation can check it's still held. Afterwards the lock is released, and the client is destroyed instead of reused when the release fails, the connection was lost, or a transaction on it is still open or ended in an unknown state, which releases the lock too.

    Signature
    withSessionLock<T>(
      postgres: IPostgres,
      key: string,
      operation: (lock: ISessionLock) => Promise<T>,
    ): Promise<ISessionLockResult<T>>

    Parameters

    postgresIPostgres

    The database, from createPostgres.

    keystring

    The lock's key, from createAdvisoryLockKey.

    operation(lock: ISessionLock) => Promise<T>

    The work, given the lock.

    Returns

    Promise<ISessionLockResult<T>>

    A promise that resolves to { acquired: false } when another session holds the lock, or { acquired: true, result } with what the operation resolved to.

    Throws

    • SESSION_LOCK_LOSTThe connection that held the session lock was lost.
    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    • TRANSACTION_ALREADY_ACTIVEThe client is already in a transaction, so another can't begin on it.
    • TRANSACTION_OUTCOME_UNKNOWNThe connection was lost during COMMIT, so the transaction may or may not have committed.
    Example
    import { createAdvisoryLockKey, createPostgres, withSessionLock } from 'jg-postgres';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const outcome = await withSessionLock(
      postgres,
      createAdvisoryLockKey('user-account-deletion:42'),
      async (lock) => {
        await lock.transaction(async (client) => {
          await client.query('DELETE FROM user_session WHERE user_account_id = $1;', ['42']);
        });
        lock.assertActive();
        return 'deleted';
      },
    );
    if (!outcome.acquired) {
      // another request is already deleting the account
    }

    Constantsjg-postgres

    ERRORS
    const

    the codes for every error thrown by the package

    Declaration
    const ERRORS: { INVALID_IDENTIFIER: "INVALID_IDENTIFIER"; TRANSACTION_OUTCOME_UNKNOWN: "TRANSACTION_OUTCOME_UNKNOWN"; TRANSACTION_ALREADY_ACTIVE: "TRANSACTION_ALREADY_ACTIVE"; SESSION_LOCK_LOST: "SESSION_LOCK_LOST"; ROW_NOT_FOUND: "ROW_NOT_FOUND"; ROW_ALREADY_FIRST: "ROW_ALREADY_FIRST"; ROW_ALREADY_LAST: "ROW_ALREADY_LAST"; MOVE_FAILED: "MOVE_FAILED"; INVALID_TIMEOUT_PROFILE: "INVALID_TIMEOUT_PROFILE"; INVALID_EXPIRED_DELETION: "INVALID_EXPIRED_DELETION"; INVALID_OPTIONAL_READ_OPTIONS: "INVALID_OPTIONAL_READ_OPTIONS"; INVALID_USAGE_ADMISSION: "INVALID_USAGE_ADMISSION"; INVALID_VERIFICATION_POLICY: "INVALID_VERIFICATION_POLICY"; INVALID_VERIFICATION_INPUT: "INVALID_VERIFICATION_INPUT"; VERIFICATION_DELIVERY_FAILED: "VERIFICATION_DELIVERY_FAILED"; INVALID_COUNTER_TABLE: "INVALID_COUNTER_TABLE"; INVALID_COUNTER_CHANGE: "INVALID_COUNTER_CHANGE"; COUNTER_ROW_NOT_FOUND: "COUNTER_ROW_NOT_FOUND"; INVALID_ERROR_LOG_OPTIONS: "INVALID_ERROR_LOG_OPTIONS"; ERROR_LOG_WRITE_FAILED: "ERROR_LOG_WRITE_FAILED"; SCHEMA_NOT_EMPTY: "SCHEMA_NOT_EMPTY"; SCHEMA_MARKER_MISSING: "SCHEMA_MARKER_MISSING"; INVALID_TEST_DATABASE_NAME: "INVALID_TEST_DATABASE_NAME"; INVALID_DELIVERY_INBOX_OPTIONS: "INVALID_DELIVERY_INBOX_OPTIONS"; INVALID_DELIVERY: "INVALID_DELIVERY"; DELIVERY_REPLAY_MISMATCH: "DELIVERY_REPLAY_MISMATCH" }
    POSTGRES_BIGINT_MAX
    const

    the largest value a PostgreSQL BIGINT column holds

    Declaration
    const POSTGRES_BIGINT_MAX: 9223372036854775807n
    POSTGRES_BIGINT_MIN
    const

    the smallest value a PostgreSQL BIGINT column holds

    Declaration
    const POSTGRES_BIGINT_MIN: -9223372036854775808n

    Typesjg-postgres

    IColumnFilter
    type

    an equality condition on one column, such as { column: 'group_id', value: 1 }

    Declaration
    type IColumnFilter = {
        column: string;
        value: unknown;
    };

    Members

    • columnproperty
      string

      the column's name, quoted in the SQL

    • valueproperty
      unknown

      the value it must equal, sent as a query parameter

    ICounterChanges
    type

    the whole amounts to add to some of the counters

    Declaration
    type ICounterChanges<C extends string> = Partial<Record<C, number | bigint>>;
    ICounterKey
    type

    a row's key: a value for every key column, none of them empty

    Declaration
    type ICounterKey<K extends string> = Record<K, string | number | bigint>;
    ICounterQuery
    type

    a query a counter table builds, with the key that orders it among a transaction's other queries

    Declaration
    type ICounterQuery = {
        text: string;
        values: unknown[];
        lockKey: string;
    };

    Members

    • textproperty
      string

      the SQL, with every value as a parameter

    • valuesproperty
      unknown[]

      the parameters, with bigints as strings

    • lockKeyproperty
      string

      the table and the row's key, so queries for the same rows run in the same order everywhere

    ICounterTable
    type

    builds the queries that change a counter table's rows

    Declaration
    type ICounterTable<K extends string, C extends string> = {
        buildIncrement: (key: ICounterKey<K>, increments: ICounterChanges<C>) => ICounterQuery;
        buildAdjustment: (key: ICounterKey<K>, changes: ICounterChanges<C>) => ICounterQuery;
    };

    Members

    • buildIncrementproperty
      (key: ICounterKey<K>, increments: ICounterChanges<C>) => ICounterQuery

      inserts the row with the increments, or adds them to the row that exists

    • buildAdjustmentproperty
      (key: ICounterKey<K>, changes: ICounterChanges<C>) => ICounterQuery

      adds the changes, which may be negative, to a row that must exist

    ICounterTableDefinition
    type

    a counter table's layout: its name, the columns that identify a row, and the counter columns

    Declaration
    type ICounterTableDefinition<K extends string, C extends string> = {
        table: string;
        keyColumns: readonly K[];
        counters: readonly C[];
    };

    Members

    • tableproperty
      string

      the table's name, quoted in the SQL

    • keyColumnsproperty
      readonly K[]

      the columns that identify a row, which a unique constraint must cover exactly

    • countersproperty
      readonly C[]

      the BIGINT counter columns, each with a default, such as 0

    ICursorListingOptions
    type

    what listByCursor lists

    Declaration
    type ICursorListingOptions = {
        table: string;
        columns: readonly string[];
        cursorColumn?: string;
        sortDirection?: 'ASC' | 'DESC';
        filters?: readonly IColumnFilter[];
        after?: IRowId | undefined;
        limit: number;
    };

    Members

    • tableproperty
      string

      the table's name, quoted in the SQL

    • columnsproperty
      readonly string[]

      the columns to select, each quoted in the SQL

    • cursorColumnproperty
      string

      the unique column the pages follow, such as an ascending ID. Defaults to 'id'

    • sortDirectionproperty
      "ASC" | "DESC"

      the order rows come in. Defaults to 'DESC', newest first for ascending IDs

    • filtersproperty
      readonly IColumnFilter[]

      equality conditions every listed row meets

    • afterproperty
      IRowId

      the cursor column's value on the last row of the previous page, or undefined for the first

    • limitproperty
      number

      the most rows to return

    ICursorPage
    type

    a page of rows, and the cursor of the next page, or null when this is the last

    Declaration
    type ICursorPage<T> = {
        items: T[];
        nextCursor: string | null;
    };

    Members

    • itemsproperty
      T[]
    • nextCursorproperty
      string | null
    IDatabaseSummary
    type

    the database a connection is on: its name, server, size, connections, and tables

    Declaration
    type IDatabaseSummary = {
        name: string;
        serverVersion: string;
        serverVersionNumber: number;
        sizeBytes: number;
        activeConnections: number;
        maxConnections: number;
        tableCount: number;
    };

    Members

    • nameproperty
      string

      the database's name

    • serverVersionproperty
      string

      the server's version, such as '18.1'

    • serverVersionNumberproperty
      number

      the server's version as a number, such as 180001, to compare versions

    • sizeBytesproperty
      number

      the database's size on disk, in bytes

    • activeConnectionsproperty
      number

      the connections to this database running a query now. Without pg_read_all_stats, only the role's own connections are counted

    • maxConnectionsproperty
      number

      the most connections the server accepts, over every database

    • tableCountproperty
      number

      the ordinary tables in the schema

    IExpiredRowDeletion
    type

    what deleteExpiredInBatches resolves to: the rows it deleted, and the cutoff it deleted them by, as an ISO 8601 UTC timestamp

    Declaration
    type IExpiredRowDeletion = {
        deletedCount: number;
        cutoff: string;
    };

    Members

    • deletedCountproperty
      number
    • cutoffproperty
      string
    IExpiredRowDeletionOptions
    type

    which rows deleteExpiredInBatches deletes, and how

    Declaration
    type IExpiredRowDeletionOptions = {
        table: string;
        timestampColumn?: string | undefined;
        keyColumn?: string | undefined;
        olderThan?: IRetentionAge | undefined;
        cutoff?: string | Date | undefined;
        batchSize?: number | undefined;
        filters?: readonly IColumnFilter[] | undefined;
        timeouts?: ITimeoutProfile | undefined;
        signal?: AbortSignal | undefined;
    };

    Members

    • tableproperty
      string

      the table, quoted in the SQL

    • timestampColumnproperty
      string

      the column whose time a row expires by. Defaults to created_at

    • keyColumnproperty
      string

      a unique, non-null column the batches delete by, such as the primary key. Defaults to id

    • olderThanproperty
      IRetentionAge

      how old a row must be, from the database's clock. Give this or cutoff

    • cutoffproperty
      string | Date

      the time rows older than which are deleted. Give this or olderThan

    • batchSizeproperty
      number

      the rows each statement deletes: 1 to 8,192. Defaults to 1,024

    • filtersproperty
      readonly IColumnFilter[]

      equality conditions a row must also meet, such as one tenant's rows

    • timeoutsproperty
      ITimeoutProfile

      the statement and lock timeouts of each batch, which then runs as a transaction of its own

    • signalproperty
      AbortSignal

      stops the deletion between batches, such as on shutdown: no batch starts after it aborts, and the call rejects with its reason once the batch in flight settles. The rows left stay for a later call

    IInitializeSchemaOptions
    type

    what initializeSchemaOnce takes

    Declaration
    type IInitializeSchemaOptions = {
        statements: readonly string[];
        markerTable: string;
        timeouts?: ITimeoutProfile | undefined;
    };

    Members

    • statementsproperty
      readonly string[]

      the statements that create the schema, run in order in one transaction, so none may be one that can't run in a transaction, such as CREATE INDEX CONCURRENTLY

    • markerTableproperty
      string

      a table in the public schema the statements create, whose presence marks the schema as initialized, such as schema_migration

    • timeoutsproperty
      ITimeoutProfile

      the statement and lock timeouts of the transaction

    IIntrospectionOptions
    type

    which schema readDatabaseSummary and listTableSizes read the tables of

    Declaration
    type IIntrospectionOptions = {
        schema?: string | undefined;
    };

    Members

    • schemaproperty
      string

      the schema. Defaults to 'public'

    IMoveOptions
    type

    what moveUp and moveDown move within

    Declaration
    type IMoveOptions = IOrderedList & {
        sortOrderConstraint: string;
        idColumn?: string;
    };
    IOptionalRead
    type

    a read that may not run: its value once known, and a promise of it; null when it was skipped, ran out of time, or failed

    Declaration
    type IOptionalRead<T> = {
        getSnapshot: () => T | null;
        completion: Promise<T | null>;
    };

    Members

    • getSnapshotproperty
      () => T | null

      the value, or null until the read finishes, and when it gives none

    • completionproperty
      Promise<T | null>

      resolves to the value, or null; it never rejects

    IOptionalReader
    type

    runs optional reads, such as a counter in a page's header, that never delay or crowd out essential work

    Declaration
    type IOptionalReader = {
        read: <T>(key: string, query: {
            text: string;
            values?: unknown[] | undefined;
        }, parse: (row: unknown) => T) => IOptionalRead<T>;
    };

    Members

    • readproperty
      (key: string, query: { text: string; values?: unknown[] }, parse: (row: unknown) => T) => IOptionalRead<T>

      starts a read of the query's first row, or joins the one running for the same key

    IOptionalReaderOptions
    type

    how createOptionalReader admits and bounds reads

    Declaration
    type IOptionalReaderOptions = {
        postgres: IPostgres;
        maxActiveReads?: number | undefined;
        reservedIdleClients?: number | undefined;
        admissionSeconds?: number | undefined;
        timeouts?: ITimeoutProfile | undefined;
    };

    Members

    • postgresproperty
      IPostgres

      the database the reads run on

    • maxActiveReadsproperty
      number

      the most reads running at once. Defaults to 2

    • reservedIdleClientsproperty
      number

      the clients a read leaves free for essential work: it's skipped unless the pool can give more than this many. Defaults to 2

    • admissionSecondsproperty
      number

      the seconds a read may take, waiting for a client included, before it gives null. Defaults to 1

    • timeoutsproperty
      ITimeoutProfile

      each read's timeouts. Defaults to a 0.5-second statement timeout, a 0.1-second lock timeout, and a 0.75-second client timeout

    IOrderedList
    type

    an ordered list: the rows of a table, or of one group in it, ordered by a column

    Declaration
    type IOrderedList = {
        table: string;
        sortOrderColumn?: string;
        scope?: readonly IColumnFilter[];
    };

    Members

    • tableproperty
      string

      the table's name

    • sortOrderColumnproperty
      string

      the column the rows are ordered by. Defaults to 'sort_order'

    • scopeproperty
      readonly IColumnFilter[]

      equality conditions that pick one ordered list when a table holds several, such as [{ column: 'group_id', value: 1 }]

    IPostgres
    type

    a database: its pool, and the helpers that use it

    Declaration
    type IPostgres = {
        readonly pool: Pool;
        query: <T extends QueryResultRow = QueryResultRow>(text: string, params?: readonly unknown[]) => Promise<T[]>;
        transaction: <T>(operation: (client: PoolClient) => Promise<T>, options?: ITransactionOptions) => Promise<T>;
        close: () => Promise<void>;
    };

    Members

    • poolproperty
      Pool

      the node-postgres pool, for what the helpers don't cover

    • queryproperty
      (text: string, params?: readonly unknown[]) => Promise<T[]>

      runs a query on the pool and returns its rows

    • transactionproperty
      (operation: (client: PoolClient) => Promise<T>, options?: ITransactionOptions) => Promise<T>

      runs an operation in a transaction on one client, committing when it resolves and rolling back when it throws, optionally with timeouts of its own. Never start a transaction inside another: run the inner work on the client instead

    • closeproperty
      () => Promise<void>

      ends every connection, once queries in flight finish

    IPostgresConfig
    type

    what createPostgres takes: node-postgres's pool configuration, such as the host, the pool size, and connectionTimeoutMillis, statement_timeout, lock_timeout, and idle_in_transaction_session_timeout, plus where errors outside any query go

    Declaration
    type IPostgresConfig = Omit<PoolConfig, 'types'> & {
        onError?: ((error: unknown) => void) | undefined;
    };
    IQueryExecutor
    type

    what runs a query: the pool, or a client checked out from it, such as a transaction's

    Declaration
    type IQueryExecutor = Pool | PoolClient;
    IRetentionAge
    type

    how old a row must be to be deleted: calendar months and days, then seconds, each a whole number of at least 0, not all 0, counted back from the database's clock on the UTC calendar

    Declaration
    type IRetentionAge = {
        months?: number | undefined;
        days?: number | undefined;
        seconds?: number | undefined;
    };

    Members

    • monthsproperty
      number
    • daysproperty
      number
    • secondsproperty
      number
    IRowId
    type

    a row's identifier, as a cursor or a row to move

    Declaration
    type IRowId = string | number | bigint;
    IRunTransactionOptions
    type

    how runTransaction runs a transaction on a client the caller holds: its timeouts, and where a failed ROLLBACK goes

    Declaration
    type IRunTransactionOptions = ITransactionOptions & {
        onError?: ((error: unknown) => void) | undefined;
    };
    ISessionLock
    type

    what withSessionLock gives the operation while it holds the lock

    Declaration
    type ISessionLock = {
        readonly client: PoolClient;
        isActive: () => boolean;
        assertActive: () => void;
        transaction: <T>(operation: (client: PoolClient) => Promise<T>, options?: ITransactionOptions) => Promise<T>;
        destroyClient: () => void;
    };

    Members

    • clientproperty
      PoolClient

      the client that holds the lock, for work that must stop when the lock does

    • isActiveproperty
      () => boolean

      whether the lock's connection is still alive, so the lock is still held

    • assertActiveproperty
      () => void

      throws SESSION_LOCK_LOST when the lock's connection was lost

    • transactionproperty
      (operation: (client: PoolClient) => Promise<T>, options?: ITransactionOptions) => Promise<T>

      runs an operation in a transaction on the lock's client, after checking the lock is still held, as runTransaction does. Run as many as the work needs, one after another: one still open, or one whose end is unknown, makes the lock destroy its client instead of reusing it

    • destroyClientproperty
      () => void

      marks the client as unsafe to reuse, such as after work on it ended in an unknown state, so it's destroyed instead of returned to the pool

    ISessionLockResult
    type

    what withSessionLock resolves to: whether it got the lock, and the operation's result when it did

    Declaration
    type ISessionLockResult<T> = {
        acquired: false;
    } | {
        acquired: true;
        result: T;
    };
    ITableDiff
    type

    how a schema's tables differ from the ones expected

    Declaration
    type ITableDiff = {
        missing: string[];
        unexpected: string[];
    };

    Members

    • missingproperty
      string[]

      the expected tables that don't exist

    • unexpectedproperty
      string[]

      the tables that exist but aren't expected

    ITableSize
    type

    a table and its size on disk, with its indexes and TOAST data

    Declaration
    type ITableSize = {
        name: string;
        totalBytes: number;
    };

    Members

    • nameproperty
      string

      the table's name

    • totalBytesproperty
      number

      its total size, in bytes

    ITimeoutProfile
    type

    how long a query may run, in seconds: on the server, waiting for a lock, and on the client, which stops waiting for the server's answer. defineTimeoutProfile builds it

    Declaration
    type ITimeoutProfile = Readonly<{
        statementTimeoutSeconds: number;
        lockTimeoutSeconds: number;
        queryTimeoutSeconds: number;
    }>;
    ITransactionOptions
    type

    how a transaction runs

    Declaration
    type ITransactionOptions = {
        timeouts?: ITimeoutProfile | undefined;
    };

    Members

    • timeoutsproperty
      ITimeoutProfile

      the statement and lock timeouts for this transaction only, from defineTimeoutProfile. The pool's query_timeout still applies to each query that doesn't set its own, so pass the operation's queries through withQueryTimeout with the same profile. A query the client stops waiting for is rolled back: the client goes back to the pool once ROLLBACK, which waits for the server and has the pool's query_timeout too, confirms the connection, and is destroyed otherwise

    IUsageAdmission
    type

    what admitUsage decides, with when to try again: accepted, refused by the scope's cooldown, or refused because the actor reached the limit within the window

    Declaration
    type IUsageAdmission = {
        outcome: 'accepted';
        retryAt: string | null;
    } | {
        outcome: 'cooldown';
        retryAt: string;
    } | {
        outcome: 'limit';
        retryAt: null;
    };
    IUsageAdmissionInput
    type

    what admitUsage counts and limits

    Declaration
    type IUsageAdmissionInput = {
        actorId: string;
        actionId: string;
        scopeKey?: string | undefined;
        limit: number;
        windowSeconds: number;
        cooldownSeconds?: number | undefined;
    };

    Members

    • actorIdproperty
      string

      who acts, such as a user's id: 1 to 256 characters

    • actionIdproperty
      string

      what they do, such as send-invitation: 1 to 128 characters

    • scopeKeyproperty
      string

      what they act on, such as the invited email's hash, which the cooldown applies to: 1 to 256 characters

    • limitproperty
      number

      the most times the actor may do the action within the window

    • windowSecondsproperty
      number

      the seconds the limit counts back from now

    • cooldownSecondsproperty
      number

      the seconds after an accepted action before the same action on the same scope is accepted again, by any actor. Only with a scopeKey

    IVerificationAttempt
    type

    what consume checks: the binding the challenge was issued for, its token, and the code

    Declaration
    type IVerificationAttempt = IVerificationBinding & {
        challengeToken: string;
        code: string;
    };
    IVerificationBinding
    type

    who a challenge is for, what it verifies, and what on

    Declaration
    type IVerificationBinding = {
        actorId: string;
        actionId: string;
        targetId: string;
    };

    Members

    • actorIdproperty
      string

      who verifies, such as a user's id: 1 to 256 characters

    • actionIdproperty
      string

      what they verify, such as verify-email, which must have a policy: 1 to 128 characters

    • targetIdproperty
      string

      what they verify it on, such as the new email address: 1 to 256 characters

    IVerificationChallenges
    type

    issues and consumes verification challenges with the policies they were created with

    Declaration
    type IVerificationChallenges = {
        issue: (binding: IVerificationBinding, deliver: IVerificationDeliver) => Promise<IVerificationIssue>;
        resend: (request: IVerificationResendRequest, deliver: IVerificationDeliver) => Promise<IVerificationResend>;
        consume: (attempt: IVerificationAttempt) => Promise<boolean>;
    };

    Members

    • issueproperty
      (binding: IVerificationBinding, deliver: IVerificationDeliver) => Promise<IVerificationIssue>

      issues a challenge for a binding, superseding its active one, and delivers its code once it's committed, unless the actor reached the issue limit

    • resendproperty
      (request: IVerificationResendRequest, deliver: IVerificationDeliver) => Promise<IVerificationResend>

      sends a new code for a binding's active challenge, keeping its token and expiry, which stops the earlier code from working, unless the challenge is cooling down or reached its resend limit

    • consumeproperty
      (attempt: IVerificationAttempt) => Promise<boolean>

      uses a challenge when its code matches, or counts a failed attempt, and resolves to whether it matched

    IVerificationChallengesOptions
    type

    what createVerificationChallenges takes

    Declaration
    type IVerificationChallengesOptions = {
        policies: Record<string, IVerificationPolicy>;
        codeLength?: number | undefined;
    };

    Members

    • policiesproperty
      Record<string, IVerificationPolicy>

      each action's policy, keyed by its action id, such as verify-email

    • codeLengthproperty
      number

      the code's digits: 4 to 10. Defaults to 6

    IVerificationDeliver
    type

    sends a challenge's code to its actor, such as by email

    Declaration
    type IVerificationDeliver = (delivery: IVerificationDelivery) => Promise<void> | void;
    IVerificationDelivery
    type

    what deliver receives once the challenge is committed, to send the code to the actor

    Declaration
    type IVerificationDelivery = IVerificationBinding & {
        code: string;
        challengeId: string;
        deliveryId: string;
        expiresAt: string;
        validitySeconds: number;
        remainingSeconds: number;
    };
    IVerificationIssue
    type

    What issue resolves to: the challenge's token, which the client keeps and sends back with the code, and when it expires; or, when the actor reached the policy's issue limit, when they may be issued one again.

    Declaration
    type IVerificationIssue = {
        outcome: 'issued';
        challengeToken: string;
        expiresAt: string;
    } | {
        outcome: 'limit';
        retryAt: string;
    };
    IVerificationPolicy
    type

    how one action's challenges behave: how long they last, how many wrong codes they take, and how many an actor may be issued within a window

    Declaration
    type IVerificationPolicy = {
        validitySeconds: number;
        maxFailedAttempts: number;
        issueLimit: number;
        issueWindowSeconds: number;
        resendLimit?: number | undefined;
        resendCooldownSeconds?: number | undefined;
    };

    Members

    • validitySecondsproperty
      number

      the whole seconds a challenge stays valid after it's issued, at least 1

    • maxFailedAttemptsproperty
      number

      the wrong codes a challenge takes before it stops accepting any: 1 to 32,767

    • issueLimitproperty
      number

      the most challenges an actor may be issued for the action within the window, over every target

    • issueWindowSecondsproperty
      number

      the whole seconds the issue limit counts back from now, at least 1

    • resendLimitproperty
      number

      the times one challenge's code may be resent, each time as a new code: 1 to 32,767. Without it, resend refuses the action

    • resendCooldownSecondsproperty
      number

      the whole seconds that must pass between two sends of one challenge, counted from its issue or its last resend, at least 1. Without it, a challenge may be resent at once

    IVerificationResend
    type

    What resend resolves to: a new code was sent, under the challenge's original expiry; the challenge is cooling down until retryAt; it was resent as often as the policy allows; or there's no active challenge for the binding and token, because it was used, superseded, expired, or ran out of attempts.

    Declaration
    type IVerificationResend = {
        outcome: 'resent';
        expiresAt: string;
    } | {
        outcome: 'cooldown';
        retryAt: string;
    } | {
        outcome: 'limit';
    } | {
        outcome: 'invalid';
    };
    IVerificationResendRequest
    type

    what resend takes: the binding the challenge was issued for, and its token

    Declaration
    type IVerificationResendRequest = IVerificationBinding & {
        challengeToken: string;
    };

    jg-postgres/error-log

    Functionsjg-postgres/error-log

    createErrorLog
    function

    Creates an error log that records errors in a table the README defines, such as the errors an API's exception filter catches. A record's message is the error's message, prefixed with its code, without null characters and cut to maxMessageLength; an Exception's object data is its payload, with redactKeys replaced at any depth, left out when it's larger than maxPayloadBytes or nested more than 256 levels deep, like user info nested that deep; and a deduplicationKey stores one row per origin and key, by the key's SHA-256 digest in lowercase hex. A write runs in one transaction with timeouts, in INSERTs of at most maxBatchSize rows, and never rejects: a failure goes to the database's onError as ERROR_LOG_WRITE_FAILED, with the SQLSTATE and without the rows, and the write resolves to 0.

    Signature
    createErrorLog(postgres: IPostgres, options: IErrorLogOptions): IErrorLog

    Parameters

    postgresIPostgres

    The database.

    optionsIErrorLogOptions

    The log's origin and table, and its redaction, limits, and timeouts.

    Returns

    IErrorLog

    The functions that record errors.

    Throws

    • INVALID_ERROR_LOG_OPTIONSThe error log needs an origin of 1 to 256 characters, redact keys that are strings, a whole message length of at least 16, a whole payload size of at least 16 bytes, a whole batch size from 1 to 8192, and an onRecorded that's a function when it's given.
    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    • INVALID_TIMEOUT_PROFILEThe timeout profile needs positive, finite seconds, with the lock timeout no longer than the statement timeout.
    Example
    import { createPostgres } from 'jg-postgres';
    import { createErrorLog } from 'jg-postgres/error-log';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const errorLog = createErrorLog(postgres, { origin: 'api', redactKeys: ['password', 'token'] });
    await errorLog.record({ error: new Error('The upload failed.'), userInfo: { userId: '42' } });

    Typesjg-postgres/error-log

    IErrorLog
    type

    records errors in a table, never rejecting

    Declaration
    type IErrorLog = {
        record: (entry: IErrorLogEntry) => Promise<boolean>;
        recordMany: (entries: readonly IErrorLogEntry[]) => Promise<number>;
    };

    Members

    • recordproperty
      (entry: IErrorLogEntry) => Promise<boolean>

      records one error, resolving to whether a row was inserted

    • recordManyproperty
      (entries: readonly IErrorLogEntry[]) => Promise<number>

      records several errors in one transaction, resolving to the rows inserted

    IErrorLogEntry
    type

    one error to record

    Declaration
    type IErrorLogEntry = {
        error: unknown;
        origin?: string | undefined;
        userInfo?: Record<string, IJsonValue | undefined> | null | undefined;
        deduplicationKey?: string | undefined;
    };

    Members

    • errorproperty
      unknown

      the error, of any shape: its message is stored, prefixed with its code when it has one, and an Exception's object data is stored as its payload

    • originproperty
      string

      what reported it, when it isn't the log's origin: 1 to 256 characters

    • userInfoproperty
      Record<string, IJsonValue | undefined> | null

      who was affected, such as the user's id; undefined fields are left out

    • deduplicationKeyproperty
      string

      what identifies a repeat of the same failure: one row is stored per origin and key, by the key's SHA-256 digest. Without it, every record is stored

    IErrorLogOptions
    type

    what createErrorLog takes

    Declaration
    type IErrorLogOptions = {
        origin: string;
        table?: string | undefined;
        redactKeys?: readonly string[] | undefined;
        maxMessageLength?: number | undefined;
        maxPayloadBytes?: number | undefined;
        maxBatchSize?: number | undefined;
        timeouts?: ITimeoutProfile | undefined;
        onRecorded?: ((event: IErrorLogRecordedEvent) => void | Promise<void>) | undefined;
    };

    Members

    • originproperty
      string

      what reports the errors, such as api or worker: 1 to 256 characters

    • tableproperty
      string

      the table the README defines, under any name. Defaults to error_log

    • redactKeysproperty
      readonly string[]

      the keys whose values are replaced in an Exception's data before it's stored, at any depth and whatever their case, such as password or token

    • maxMessageLengthproperty
      number

      the most characters a stored message has, with [truncated] at its end once it's cut: at least 16. Defaults to 8,192, the README column's size

    • maxPayloadBytesproperty
      number

      the most bytes an Exception's data takes as JSON; larger data is left out of its row: at least 16. Defaults to 1,024

    • maxBatchSizeproperty
      number

      the most rows one INSERT writes; a longer list is written in chunks, in one transaction: 1 to 8,192. Defaults to 256

    • timeoutsproperty
      ITimeoutProfile

      the statement and lock timeouts of each write. Defaults to 5 seconds and 1 second

    • onRecordedproperty
      (event: IErrorLogRecordedEvent) => void | Promise<void>

      runs after a write that inserted rows commits, such as to count unread errors. It isn't awaited, and what it throws or rejects with goes to the database's onError

    IErrorLogRecordedEvent
    type

    what onRecorded receives: how many rows the write inserted

    Declaration
    type IErrorLogRecordedEvent = {
        count: number;
    };

    Members

    • countproperty
      number

    jg-postgres/record-store

    Functionsjg-postgres/record-store

    createRecordStore
    function

    Creates a store for one JSON record, such as a set of counters or a feature's settings, kept in the record_store table the package's README describes, which the app creates. The defaults fill every missing field when it's read, and are the only keys a write keeps. Every read is checked with the schema. A method given a transaction's client runs in it, and never commits it.

    Signature
    createRecordStore<T extends Record<string, unknown>>(
      options: IRecordStoreOptions<T>,
    ): IRecordStore<T>

    Parameters

    optionsIRecordStoreOptions<T>

    The database, the record's id, its defaults, and its schema.

    Returns

    IRecordStore<T>

    The record's store.

    Example
    import { createPostgres } from 'jg-postgres';
    import { createRecordStore } from 'jg-postgres/record-store';
    import { z } from 'zod';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const counters = createRecordStore({
      postgres,
      id: 'admin:unread-counts',
      defaults: { notifications: 0, reports: 0 },
      schema: z.object({ notifications: z.number(), reports: z.number() }),
    });
    
    await counters.incrementNumber('notifications', 1);
    await counters.get(); // => { notifications: 1, reports: 0 }

    Typesjg-postgres/record-store

    IRecordNumberKey
    type

    the keys of a record whose values are numbers

    Declaration
    type IRecordNumberKey<T extends Record<string, unknown>> = {
        [Key in keyof T]: T[Key] extends number ? Key : never;
    }[keyof T] & string;
    IRecordStore
    type

    one record in the record_store table. Each method takes a transaction's client, to run in it without committing it, or runs on the pool

    Declaration
    type IRecordStore<T extends Record<string, unknown>> = {
        get: (client?: PoolClient) => Promise<T>;
        set: (value: T, client?: PoolClient) => Promise<void>;
        incrementNumber: (field: IRecordNumberKey<T>, delta: number, client?: PoolClient) => Promise<void>;
        setNumber: (field: IRecordNumberKey<T>, value: number, client?: PoolClient) => Promise<void>;
    };

    Members

    • getproperty
      (client?: PoolClient) => Promise<T>

      reads the record, with the defaults filling every missing or null field

    • setproperty
      (value: T, client?: PoolClient) => Promise<void>

      replaces the record, with the defaults filling every undefined or null field

    • incrementNumberproperty
      (field: IRecordNumberKey<T>, delta: number, client?: PoolClient) => Promise<void>

      adds to one numeric field atomically, so concurrent increments all count

    • setNumberproperty
      (field: IRecordNumberKey<T>, value: number, client?: PoolClient) => Promise<void>

      replaces one numeric field, leaving the record's other fields as they are

    IRecordStoreOptions
    type

    what createRecordStore keeps

    Declaration
    type IRecordStoreOptions<T extends Record<string, unknown>> = {
        postgres: IPostgres;
        id: string;
        defaults: T;
        schema: ISchema<T>;
    };

    Members

    • postgresproperty
      IPostgres

      the database whose record_store table holds the record

    • idproperty
      string

      the record's id in the table, such as 'notifications:unread-counts'

    • defaultsproperty
      T

      the complete record: what get returns for a missing field, and the only keys a write keeps

    • schemaproperty
      ISchema<T>

      checks the record get returns, defaults applied, such as a Zod schema. Its error propagates

    ISchema
    type

    validates data and returns it typed, which a Zod schema does

    Declaration
    type ISchema<T> = {
        parse(value: unknown): T;
    };

    Members

    • parsemethod
      parse(value: unknown): T

    jg-postgres/delivery-inbox

    Functionsjg-postgres/delivery-inbox

    createDeliveryInbox
    function

    Creates an inbox for deliveries an app must process exactly once, such as webhook events: it stores each one before the app acknowledges it, recognizes a replay, and hands each due delivery to one worker at a time under a lease. The table, whose DDL the package's README gives, is the app's to create, under any name. A worker lists the due keys, claims one, processes it, and then finishes it, or defers it to retry after retrySeconds. A lease that ends without either makes the delivery due again, and a delivery still unprocessed expirySeconds after it was received closes at its next claim. Delete processed deliveries with deleteExpiredInBatches on processed_at, which never touches pending ones.

    Signature
    createDeliveryInbox<TPayload>(
      postgres: IPostgres,
      options: IDeliveryInboxOptions<TPayload>,
    ): IDeliveryInbox<TPayload>

    Parameters

    postgresIPostgres

    The database.

    optionsIDeliveryInboxOptions<TPayload>

    The table, the payload's schema, and the lease, retry, and expiry seconds.

    Returns

    IDeliveryInbox<TPayload>

    The inbox.

    Throws

    • INVALID_DELIVERY_INBOX_OPTIONSThe delivery inbox needs a table name, a schema, whole lease, retry, and expiry seconds from 1 to 2147483647, and a due-list limit from 1 to 8192.
    • INVALID_IDENTIFIERThe identifier is empty, holds a null character, or is longer than 63 bytes.
    Example
    import { createPostgres } from 'jg-postgres';
    import { createDeliveryInbox } from 'jg-postgres/delivery-inbox';
    import { z } from 'zod';
    
    declare const postgres: ReturnType<typeof createPostgres>;
    
    const inbox = createDeliveryInbox(postgres, {
      table: 'webhook_delivery',
      schema: z.object({ eventId: z.string() }),
      leaseSeconds: 600,
      retrySeconds: 60,
      expirySeconds: 86_400,
    });
    
    await inbox.receive({ key: 'wh_1', digest: 'a'.repeat(64), payload: { eventId: 'evt_1' } }); // => true
    for (const key of await inbox.listDue(32)) {
      const claim = await inbox.claim(key);
      if (claim !== null) {
        await inbox.finish(claim.key, claim.leaseId);
      }
    }

    Typesjg-postgres/delivery-inbox

    IDelivery
    type

    a delivery as received: its key, a SHA-256 of its body, and what processing it needs

    Declaration
    type IDelivery<TPayload> = {
        key: string;
        digest: string;
        payload: TPayload;
    };

    Members

    • keyproperty
      string

      the provider's identifier for the delivery, such as a webhook id, 1 to 512 characters

    • digestproperty
      string

      the lowercase hex SHA-256 of the delivery's body, which tells a replay from a different delivery under the same key

    • payloadproperty
      TPayload

      what processing the delivery needs, such as the ids the event names, stored as JSON

    IDeliveryClaim
    type

    a delivery claimed for processing, with the lease that finishes or defers it

    Declaration
    type IDeliveryClaim<TPayload> = IDelivery<TPayload> & {
        leaseId: string;
        leaseExpiresAt: string;
    };
    IDeliveryInbox
    type

    a table of received deliveries, each processed once, by whoever holds its lease

    Declaration
    type IDeliveryInbox<TPayload> = {
        receive: (delivery: IDelivery<TPayload>) => Promise<boolean>;
        listDue: (limit: number) => Promise<string[]>;
        claim: (key: string) => Promise<IDeliveryClaim<TPayload> | null>;
        finish: (key: string, leaseId: string) => Promise<boolean>;
        defer: (key: string, leaseId: string) => Promise<boolean>;
    };

    Members

    • receiveproperty
      (delivery: IDelivery<TPayload>) => Promise<boolean>

      stores a delivery, resolving to true when it's new and false for a replay of one received before with the same digest and payload

    • listDueproperty
      (limit: number) => Promise<string[]>

      the keys of the deliveries due for processing, oldest due first, at most limit, from 1 to 8,192

    • claimproperty
      (key: string) => Promise<IDeliveryClaim<TPayload> | null>

      Takes a lease on a due delivery, resolving to it, or to null when it isn't due, is leased, was processed, or has expired, which closes it. Its payload goes through the schema again, and a stored payload the schema now refuses throws the schema's error.

    • finishproperty
      (key: string, leaseId: string) => Promise<boolean>

      marks a delivery processed, resolving to whether the lease still held it

    • deferproperty
      (key: string, leaseId: string) => Promise<boolean>

      gives a delivery back to be retried after retrySeconds, never later than its expiry, resolving to whether the lease still held it

    IDeliveryInboxOptions
    type

    what createDeliveryInbox takes

    Declaration
    type IDeliveryInboxOptions<TPayload> = {
        table: string;
        schema: ISchema<TPayload>;
        leaseSeconds: number;
        retrySeconds: number;
        expirySeconds: number;
    };

    Members

    • tableproperty
      string

      the table the README's DDL defines, under any name

    • schemaproperty
      ISchema<TPayload>

      checks a delivery's payload when it's received and when it's claimed, such as a Zod schema

    • leaseSecondsproperty
      number

      how long a claim holds a delivery, in seconds, before another claim can take it

    • retrySecondsproperty
      number

      how long a deferred delivery waits before it's due again, in seconds

    • expirySecondsproperty
      number

      how long after it's received a delivery may still be claimed, in seconds. A claim after that closes it instead

    ISchema
    type

    validates data and returns it typed, which a Zod schema does

    Declaration
    type ISchema<T> = {
        parse(value: unknown): T;
    };

    Members

    • parsemethod
      parse(value: unknown): T

    jg-postgres/testing

    Functionsjg-postgres/testing

    createTestDatabaseName
    function

    Names a database for this process's tests, test_<pid>_<name>, so test runs in parallel each get their own and dropTestDatabase drops only this process's.

    Signature
    createTestDatabaseName(name: string): string

    Parameters

    namestring

    What the database is for, in lowercase letters, digits, and underscores, such as primary.

    Returns

    string

    The database's name, such as test_4242_primary.

    Throws

    • INVALID_TEST_DATABASE_NAMEThe test database name must hold only lowercase letters, digits, and underscores, start with this process's test_<pid>_ prefix, and be at most 63 bytes.
    Example
    import { createTestDatabaseName } from 'jg-postgres/testing';
    
    createTestDatabaseName('primary'); // => 'test_4242_primary', with this process's id
    dropTestDatabase
    function

    Drops a test database, ending its connections first, after checking its name is one createTestDatabaseName gave this process, so a configuration that points at a real database can never drop it. A database that doesn't exist is no error.

    Signature
    dropTestDatabase(config: IPostgresConfig): Promise<void>

    Parameters

    configIPostgresConfig

    The test database's configuration, as createPostgres takes it.

    Returns

    Promise<void>

    A promise that resolves once the database is gone.

    Throws

    • INVALID_TEST_DATABASE_NAMEThe test database name must hold only lowercase letters, digits, and underscores, start with this process's test_<pid>_ prefix, and be at most 63 bytes.
    Example
    import { createTestDatabaseName, dropTestDatabase } from 'jg-postgres/testing';
    
    await dropTestDatabase({ host: 'localhost', user: 'postgres', database: createTestDatabaseName('primary') });