@n8io/baseline-postgres 5.3.1 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,15 +24,37 @@ pnpm add @n8io/baseline-postgres
24
24
 
25
25
  ## Example
26
26
 
27
+ The table and the error its insert can return:
28
+
27
29
  ```ts
30
+ import { postgresIdColumnCreate } from "@n8io/baseline-postgres";
31
+ import { pgTable, text } from "drizzle-orm/pg-core";
32
+
28
33
  export const fooTable = pgTable("foo", {
29
34
  id: postgresIdColumnCreate("foo")().primaryKey(),
30
35
  name: text().notNull(),
31
36
  });
37
+
38
+ class FooNotCreatedError extends Error {
39
+ readonly type = "FooNotCreated";
40
+ }
32
41
  ```
33
42
 
43
+ One pool per process:
44
+
34
45
  ```ts
46
+ import { postgresPoolCreate } from "@n8io/baseline-postgres";
47
+
35
48
  const pgPool = postgresPoolCreate({ databaseUrl: ENV.DATABASE_URL });
49
+ ```
50
+
51
+ A transaction that commits on `ok` and rolls back on `err`:
52
+
53
+ ```ts
54
+ import { idCreate } from "@n8io/baseline-id";
55
+ import { postgresTransactionRun } from "@n8io/baseline-postgres";
56
+ import { err, ok } from "@n8io/baseline-result";
57
+ import { drizzle } from "drizzle-orm/node-postgres";
36
58
 
37
59
  const result = await postgresTransactionRun({
38
60
  pgPool,
@@ -41,30 +63,40 @@ const result = await postgresTransactionRun({
41
63
  .insert(fooTable)
42
64
  .values({ id: idCreate("foo"), name })
43
65
  .returning();
44
- return foo ? ok(foo) : err({ type: "FooNotCreated" as const });
66
+ return foo ? ok(foo) : err(new FooNotCreatedError());
45
67
  },
46
68
  });
47
69
  ```
48
70
 
49
- Test a race with `postgresTestInterleave` from `@n8io/baseline-postgres/testing` (see Race tests below). The Package's own tests need Docker: `pnpm test` starts a Postgres container and, for the migrate tests, a connection pooler.
71
+ Test a race with `postgresTestInterleave` from `@n8io/baseline-postgres/testing` (see Race tests below).
50
72
 
51
73
  ## Reference
52
74
 
53
75
  <details><summary><b>Exports</b></summary>
54
76
 
55
- - `postgresPoolCreate({ databaseUrl, max?, connectTimeoutMs?, queryTimeoutMs?, vendor? })`: the process's one pool (10 connections, 3 s connect timeout). A query that takes longer than `queryTimeoutMs` (default 15 s, `null` for no limit) rejects with `Query read timeout`, so a server that stops answering cannot hold a request or a pool slot forever. The pool closes that connection; inside `postgresTransactionRun` it is closed once the rollback has been tried, which can take one more `queryTimeoutMs`. The timer runs in this process and sends no cancel: a server that is slow, not gone, may still finish the query, a write included, so treat the rejection as "unknown", not "did not happen". The limit is per query, inside a transaction too. An idle connection is probed after 10 s (TCP keep-alive). `vendor` takes pg's own pool settings, such as `ssl` or `idleTimeoutMillis`, and passes them through. The named options win: `vendor` throws on the keys they set, on `host`, `port`, `database`, `user` and `password` (pg lets the URL win, so put them in `databaseUrl`), and on `ssl` when the URL carries an `ssl*` parameter. It is outside the contract: nothing in it is tested here, and moving off pg deletes it.
56
- - `PostgresPool`, `PostgresClient`: the pool and a checked-out connection. `await using` calls the pool's `end()` when its block ends. Name these in your own signatures, not `pg`'s types. They are pg's own pool and client, because Drizzle's `drizzle({ client })` needs the real ones.
57
- - `postgresTransactionRun({ pgPool, work, timeoutMs? })`: runs `work(pgClient)` in one transaction; COMMIT on `ok`, ROLLBACK on `err` or a throw. It ends after `timeoutMs` (default 5 s).
58
- - `postgresMigrate({ databaseUrl, migrationsFolder, lockWaitMs?, vendor? })`: applies pending Drizzle migrations under an advisory lock, so concurrent starts apply each one once. A run waits up to `lockWaitMs` (default 60 s) for the lock, then fails with an error that names it. The lock belongs to the session, so `databaseUrl` must reach Postgres itself: through a connection pooler such as PgBouncer the run refuses before it changes anything. Queries here have no time limit. `vendor` takes pg's settings for its one connection, under the same rules as the pool's.
59
- - Types for the options and results above: `PostgresPoolOptions`, `PostgresPoolVendorOptions`, `PostgresMigrateVendorOptions`, `PostgresKeysetKind`, `PostgresKeysetOptions`, `PostgresUniqueViolation`, `PostgresExecutor`; from `/testing`, `PostgresTestInterleaveOptions` and `PostgresTestInterleavePool`.
60
- - `@n8io/baseline-postgres/testing`: `postgresTestInterleave` for race tests (below). Import it from tests only.
61
- - `postgresIdColumnCreate(prefix)`: a Drizzle `uuid` column that reads and writes `Id<prefix>`.
62
- - `postgresUniqueViolationIs(error, constraint)`: true when a unique violation on that constraint is anywhere in the `cause` chain.
63
- - `postgresUniqueViolationRead(error)`: the first unique violation in the `cause` chain as `{ constraint, columns, values }`, or `undefined`. `columns` and `values` come from Postgres's detail (`Key (league_id, name)=(7, Eagles)`), so a value is text as Postgres printed it. Postgres quotes nothing there, so when a key of two or more columns holds a value with `", "` in it, both lists are empty rather than misaligned; an expression key such as `lower(name)` comes back as Postgres printed it, and one with `", "` inside may not split cleanly. Read `constraint` when you need certainty.
64
- - `postgresKeysetCreate({ after?, descending, idColumn, kind, sortColumn })`: keyset paging on `(sortColumn, idColumn)`. Returns `{ where, orderBy }` for a Drizzle `select`; `where` is `undefined` on the first page. `after` is the last row of the previous page, `{ id, value }`, with `id` written through `idColumn` (a prefixed id works). `kind` says how the sort compares: `text` by byte order (`COLLATE "C"`, the same in every locale, so give the column a `COLLATE "C"` index); `number` as the column's own type, so its index is used (for `integer`, `real` and `double precision` columns; a `numeric` or `bigint` column reads as a string or a bigint and is not supported); `integer` the same, for an `integer` or `serial` column only (any other column throws), taking only a whole number from -2147483648 to 2147483647; `date` as an instant, with `value` an ISO string with an offset (`toISOString()`). The sort column must be `NOT NULL`, because a NULL never compares, and a `date` column must hold no more than milliseconds (`timestamp({ precision: 3, withTimezone: true })`, or written only from a JS `Date`): a cursor made from a `Date` drops the microseconds a `now()` default stores, and pages would repeat or skip rows. A `value` of the wrong type for `kind`, a date that is not an ISO instant, or a number an `integer` or `smallint` sort column cannot hold (a fraction, or past its range), throws a `TypeError`: decode and check a cursor before you pass it.
65
- - `postgresAdvisoryLockTake(db, key)`: waits for and takes a transaction-scoped advisory lock on the string `key`; Postgres drops it at COMMIT or ROLLBACK. Use it to serialize work that has no row to lock, such as counting a League's Teams before inserting one. `db` is anything with Drizzle's `execute` (`PostgresExecutor`). Call it inside `postgresTransactionRun`: outside a transaction the lock ends with the statement.
66
-
67
- The example above imports `postgresIdColumnCreate`, `postgresPoolCreate` and `postgresTransactionRun` from this Package, `idCreate` from `@n8io/baseline-id`, `err` and `ok` from `@n8io/baseline-result`, `drizzle` from `drizzle-orm/node-postgres`, and `pgTable` and `text` from `drizzle-orm/pg-core`.
77
+ | Export | Does |
78
+ | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
79
+ | `postgresPoolCreate({ databaseUrl, max?, connectTimeoutMs?, queryTimeoutMs?, vendor? })` | The process's one pool (10 connections, 3 s connect timeout). A query that takes longer than `queryTimeoutMs` (default 15 s, `null` for no limit) rejects with `Query read timeout`, so a server that stops answering cannot hold a request or a pool slot forever. The pool closes that connection; inside `postgresTransactionRun` it is closed once the rollback has been tried, which can take one more `queryTimeoutMs`. The timer runs in this process and sends no cancel: a server that is slow, not gone, may still finish the query, a write included, so treat the rejection as "unknown", not "did not happen". The limit is per query, inside a transaction too. An idle connection is probed after 10 s (TCP keep-alive). `vendor` takes pg's own pool settings, such as `ssl` or `idleTimeoutMillis`, and passes them through. The named options win: `vendor` throws on the keys they set, on `host`, `port`, `database`, `user` and `password` (pg lets the URL win, so put them in `databaseUrl`), and on `ssl` when the URL carries an `ssl*` parameter. It is outside the contract: nothing in it is tested here, and moving off pg deletes it. |
80
+ | `PostgresPool`, `PostgresClient` | The pool and a checked-out connection. `await using` calls the pool's `end()` when its block ends. Name these in your own signatures, not `pg`'s types. They are pg's own pool and client, because Drizzle's `drizzle({ client })` needs the real ones. |
81
+ | `postgresTransactionRun({ pgPool, work, timeoutMs? })` | Runs `work(pgClient)` in one transaction; COMMIT on `ok`, ROLLBACK on `err` or a throw. It ends after `timeoutMs` (default 5 s). |
82
+ | `postgresMigrate({ databaseUrl, migrationsFolder, lockWaitMs?, vendor? })` | Applies pending Drizzle migrations under an advisory lock, so concurrent starts apply each one once. A run waits up to `lockWaitMs` (default 60 s) for the lock, then fails with an error that names it. The lock belongs to the session, so `databaseUrl` must reach Postgres itself: through a connection pooler such as PgBouncer the run refuses before it changes anything. Queries here have no time limit. `vendor` takes pg's settings for its one connection, under the same rules as the pool's. |
83
+ | `PostgresPoolOptions` | What `postgresPoolCreate` takes. |
84
+ | `PostgresPoolVendorOptions` | The `vendor` option of `postgresPoolCreate`: pg's own pool settings, outside the contract. |
85
+ | `PostgresMigrateOptions` | What `postgresMigrate` takes. |
86
+ | `PostgresMigrateVendorOptions` | The `vendor` option of `postgresMigrate`: pg's settings for its one connection, outside the contract. |
87
+ | `PostgresTransactionRunOptions` | What `postgresTransactionRun` takes. |
88
+ | `PostgresKeysetKind` | How the sort column compares: `"text"`, `"date"`, `"integer"` or `"number"`. |
89
+ | `PostgresKeysetOptions` | What `postgresKeysetCreate` takes. |
90
+ | `PostgresUniqueViolation` | What `postgresUniqueViolationRead` returns: `{ constraint, columns, values }`. |
91
+ | `PostgresExecutor` | Anything with Drizzle's `execute`, which `postgresAdvisoryLockTake` takes as `db`. |
92
+ | `@n8io/baseline-postgres/testing`: `postgresTestInterleave({ first, second, pgPool, timeoutMs? })` | Forces the interleaving a race test needs (see Race tests below). Import it from tests only. |
93
+ | `@n8io/baseline-postgres/testing`: `PostgresTestInterleaveOptions` | What `postgresTestInterleave` takes. |
94
+ | `@n8io/baseline-postgres/testing`: `PostgresTestInterleavePool` | The pool the helper watches `pg_stat_activity` through; a `PostgresPool` fits. |
95
+ | `postgresIdColumnCreate(prefix)` | A Drizzle `uuid` column that reads and writes `Id<prefix>`. |
96
+ | `postgresUniqueViolationIs(error, constraint)` | True when a unique violation on that constraint is anywhere in the `cause` chain. |
97
+ | `postgresUniqueViolationRead(error)` | The first unique violation in the `cause` chain as `{ constraint, columns, values }`, or `undefined`. `columns` and `values` come from Postgres's detail (`Key (league_id, name)=(7, Eagles)`), so a value is text as Postgres printed it. Postgres quotes nothing there, so when a key of two or more columns holds a value with `", "` in it, both lists are empty rather than misaligned; an expression key such as `lower(name)` comes back as Postgres printed it, and one with `", "` inside may not split cleanly. Read `constraint` when you need certainty. |
98
+ | `postgresKeysetCreate({ after?, descending, idColumn, kind, sortColumn })` | Keyset paging on `(sortColumn, idColumn)`. Returns `{ where, orderBy }` for a Drizzle `select`; `where` is `undefined` on the first page. `after` is the last row of the previous page, `{ id, value }`, with `id` written through `idColumn` (a prefixed id works). `kind` says how the sort compares: `text` by byte order (`COLLATE "C"`, the same in every locale, so give the column a `COLLATE "C"` index); `number` as the column's own type, so its index is used (for `integer`, `real` and `double precision` columns; a `numeric` or `bigint` column reads as a string or a bigint and is not supported); `integer` the same, for an `integer` or `serial` column only (any other column throws), taking only a whole number from -2147483648 to 2147483647; `date` as an instant, with `value` an ISO string with an offset (`toISOString()`). The sort column must be `NOT NULL`, because a NULL never compares, and a `date` column must hold no more than milliseconds (`timestamp({ precision: 3, withTimezone: true })`, or written only from a JS `Date`): a cursor made from a `Date` drops the microseconds a `now()` default stores, and pages would repeat or skip rows. A `value` of the wrong type for `kind`, a date that is not an ISO instant, or a number an `integer` or `smallint` sort column cannot hold (a fraction, or past its range), throws a `TypeError`: decode and check a cursor before you pass it. |
99
+ | `postgresAdvisoryLockTake(db, key)` | Waits for and takes a transaction-scoped advisory lock on the string `key`; Postgres drops it at COMMIT or ROLLBACK. Use it to serialize work that has no row to lock, such as counting a League's Teams before inserting one. `db` is anything with Drizzle's `execute` (`PostgresExecutor`). Call it inside `postgresTransactionRun`: outside a transaction the lock ends with the statement. |
68
100
 
69
101
  </details>
70
102
 
@@ -156,7 +188,13 @@ Every process opens up to `max` connections, and Postgres refuses new ones past
156
188
 
157
189
  </details>
158
190
 
159
- <details><summary><b>Env</b></summary>
191
+ <details><summary><b>This Package's own tests</b></summary>
192
+
193
+ They need Docker: `pnpm test` starts a Postgres container and, for the migrate tests, a connection pooler. `pnpm test:unit` runs the option checks without it.
194
+
195
+ </details>
196
+
197
+ <details><summary><b>Environment</b></summary>
160
198
 
161
199
  By the Template's convention: `DATABASE_URL` (`postgres://` or `postgresql://`), `DATABASE_POOL_MAX` for `max`, and `DATABASE_MIGRATE_URL` for `postgresMigrate` where `DATABASE_URL` goes through a pooler. Transactions use `transaction_timeout`, so Postgres 17 or newer.
162
200
 
package/dist/index.d.ts CHANGED
@@ -7,18 +7,25 @@ import { Result } from "@n8io/baseline-result";
7
7
  type PostgresExecutor = {
8
8
  execute(query: SQL): Promise<unknown>;
9
9
  };
10
+ /**
11
+ * Takes a transaction-scoped advisory lock on `key`, waiting while another transaction holds it.
12
+ * Postgres releases it at COMMIT or ROLLBACK. Outside a transaction it is released as soon as
13
+ * this statement ends, so call it inside postgresTransactionRun.
14
+ */
10
15
  export declare const postgresAdvisoryLockTake: (db: PostgresExecutor, key: string) => Promise<void>;
11
16
  type PostgresIdColumnBuilder<P extends string> = PgCustomColumnBuilder<{
12
17
  data: Id<P>;
13
18
  dataType: "custom";
14
19
  driverParam: string;
15
20
  }>;
21
+ /** A `uuid` column in the database that reads and writes prefixed ids (`foo_…`) in code. */
16
22
  export declare const postgresIdColumnCreate: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
17
23
  /**
18
24
  * How the sort column compares: `text` by byte order (`COLLATE "C"`), `date` as an instant,
19
25
  * `integer` and `number` as numbers (`integer` takes only a whole number).
20
26
  */
21
27
  type PostgresKeysetKind = "date" | "integer" | "number" | "text";
28
+ /** What `postgresKeysetCreate` takes. */
22
29
  type PostgresKeysetOptions = {
23
30
  /** The last row of the previous page; none for the first page. */
24
31
  after?: {
@@ -31,6 +38,15 @@ type PostgresKeysetOptions = {
31
38
  kind: PostgresKeysetKind;
32
39
  sortColumn: AnyColumn;
33
40
  };
41
+ /**
42
+ * Keyset ("seek") paging on (sort, id): the rows after `after` in the order of `orderBy`. The sort
43
+ * column must be NOT NULL (a NULL never compares), and a `date` column must hold no more than
44
+ * milliseconds, the precision of the JS Date a cursor is written from. Decode and check the
45
+ * cursor before calling; a value of the wrong type for `kind`, a number an integer or smallint
46
+ * sort column cannot hold, or kind `integer` on another column type, throws a TypeError.
47
+ * A number is bound untyped so Postgres reads it as the column's own type: a `::numeric` cast
48
+ * would turn an integer column's index condition into a filter over the whole index.
49
+ */
34
50
  export declare const postgresKeysetCreate: ({ after, descending, idColumn, kind, sortColumn }: PostgresKeysetOptions) => {
35
51
  orderBy: SQL[];
36
52
  where: SQL | undefined;
@@ -44,20 +60,28 @@ declare const postgresVendorOwnedKeys: {
44
60
  readonly port: "databaseUrl";
45
61
  readonly user: "databaseUrl";
46
62
  };
63
+ /** The pg settings no `vendor` option may carry. */
47
64
  type PostgresVendorOwnedKey = keyof typeof postgresVendorOwnedKeys;
48
65
  /**
49
66
  * pg's own client settings for the migration's one connection, passed through as they are.
50
67
  * Outside this Package's contract, like `PostgresPoolVendorOptions`.
51
68
  */
52
69
  type PostgresMigrateVendorOptions = Omit<pg.ClientConfig, PostgresVendorOwnedKey>;
53
- export declare const postgresMigrate: (options: {
70
+ /** What `postgresMigrate` takes. */
71
+ type PostgresMigrateOptions = {
54
72
  databaseUrl: string;
55
73
  /** How long to wait for another run to release the lock. Default 60 s. */
56
74
  lockWaitMs?: number | null;
57
75
  migrationsFolder: string;
58
76
  /** Settings only pg has, such as `ssl`: the same ones the pool takes. */
59
- vendor?: PostgresMigrateVendorOptions;
60
- }) => Promise<void>;
77
+ vendor?: PostgresMigrateVendorOptions | null;
78
+ };
79
+ /**
80
+ * Applies pending Drizzle migrations under an advisory lock, so concurrent runs (several
81
+ * containers starting at once) apply each migration once: a second run waits, then finds nothing.
82
+ * The lock belongs to the session, so the connection must reach Postgres itself, not a pooler.
83
+ */
84
+ export declare const postgresMigrate: (options: PostgresMigrateOptions) => Promise<void>;
61
85
  /**
62
86
  * The process's Postgres connection pool. Close it with `end()`; `await using` calls `end()` when
63
87
  * its block ends.
@@ -71,26 +95,40 @@ type PostgresClient = pg.PoolClient;
71
95
  * refused.
72
96
  */
73
97
  type PostgresPoolVendorOptions = Omit<pg.PoolConfig, PostgresVendorOwnedKey | "max" | "query_timeout">;
98
+ /** What `postgresPoolCreate` takes. */
74
99
  type PostgresPoolOptions = {
75
100
  databaseUrl: string;
76
101
  /** How long a connect may take. Default 3 s. */
77
- connectTimeoutMs?: number;
102
+ connectTimeoutMs?: number | null;
78
103
  /** The most connections the pool opens. Default 10. */
79
- max?: number;
104
+ max?: number | null;
80
105
  /**
81
- * How long the caller waits for one query before it rejects. Default 15 s; `null` turns it off.
82
- * The pool closes that connection; the server may still finish the query.
106
+ * How long the caller waits for one query before it rejects. Default 15 s. Unlike every other
107
+ * option, `null` does not mean the default: it turns the limit off. The pool closes that
108
+ * connection; the server may still finish the query.
83
109
  */
84
110
  queryTimeoutMs?: number | null;
85
111
  /** Settings only pg has, such as `ssl` or `idleTimeoutMillis`. */
86
- vendor?: PostgresPoolVendorOptions;
112
+ vendor?: PostgresPoolVendorOptions | null;
87
113
  };
88
- export declare const postgresPoolCreate: ({ connectTimeoutMs, databaseUrl, max, queryTimeoutMs, vendor }: PostgresPoolOptions) => PostgresPool;
89
- export declare const postgresTransactionRun: <T, E>({ pgPool, timeoutMs: timeoutMsGiven, work }: {
114
+ /**
115
+ * The process's one Postgres pool. pg 8.23 ignores `?connect_timeout=` in the URL, so the
116
+ * settings live here.
117
+ */
118
+ export declare const postgresPoolCreate: (options: PostgresPoolOptions) => PostgresPool;
119
+ /** What `postgresTransactionRun` takes. */
120
+ type PostgresTransactionRunOptions<T, E> = {
90
121
  pgPool: PostgresPool;
122
+ /** How long the transaction may run before Postgres ends it. Default 5 s. */
91
123
  timeoutMs?: number | null;
92
124
  work: (pgClient: PostgresClient) => Promise<Result<T, E>>;
93
- }) => Promise<Result<T, E>>;
125
+ };
126
+ /**
127
+ * Runs `work` in one transaction on one checked-out client: COMMIT on ok, ROLLBACK on err or a
128
+ * throw. transaction_timeout (Postgres 17+) ends a transaction that runs longer than timeoutMs.
129
+ */
130
+ export declare const postgresTransactionRun: <T, E>({ pgPool, timeoutMs: timeoutMsGiven, work }: PostgresTransactionRunOptions<T, E>) => Promise<Result<T, E>>;
131
+ /** A unique violation as data: the constraint, and the key's columns and values as Postgres printed them. */
94
132
  type PostgresUniqueViolation = {
95
133
  /** The key's columns, or expressions for an expression index. Empty when Postgres sent no detail. */
96
134
  columns: string[];
@@ -98,6 +136,12 @@ type PostgresUniqueViolation = {
98
136
  /** The clashing values as Postgres printed them, in column order. Empty when unreadable. */
99
137
  values: string[];
100
138
  };
139
+ /** True when `error` or any error in its `.cause` chain is a unique violation on `constraint`. */
101
140
  export declare const postgresUniqueViolationIs: (error: unknown, constraint: string) => boolean;
141
+ /**
142
+ * Postgres words the detail `Key (a, b)=(1, x) already exists.` and quotes nothing, so a value
143
+ * that holds ", " in a key of two or more columns cannot be split: then both lists are empty
144
+ * rather than misaligned.
145
+ */
102
146
  export declare const postgresUniqueViolationRead: (error: unknown) => PostgresUniqueViolation | undefined;
103
- export type { PostgresClient, PostgresExecutor, PostgresKeysetKind, PostgresKeysetOptions, PostgresMigrateVendorOptions, PostgresPool, PostgresPoolOptions, PostgresPoolVendorOptions, PostgresUniqueViolation };
147
+ export type { PostgresClient, PostgresExecutor, PostgresKeysetKind, PostgresKeysetOptions, PostgresMigrateOptions, PostgresMigrateVendorOptions, PostgresPool, PostgresPoolOptions, PostgresPoolVendorOptions, PostgresTransactionRunOptions, PostgresUniqueViolation };
package/dist/index.js CHANGED
@@ -7,10 +7,16 @@ import { migrate } from "drizzle-orm/node-postgres/migrator";
7
7
  import pg from "pg";
8
8
  import { logger } from "@n8io/baseline-logger";
9
9
  // src/postgres-advisory-lock-take.ts
10
+ /**
11
+ * Takes a transaction-scoped advisory lock on `key`, waiting while another transaction holds it.
12
+ * Postgres releases it at COMMIT or ROLLBACK. Outside a transaction it is released as soon as
13
+ * this statement ends, so call it inside postgresTransactionRun.
14
+ */
10
15
  const postgresAdvisoryLockTake = async (db, key) => {
11
16
  await db.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))`);
12
17
  };
13
18
  // src/postgres-id-column.ts
19
+ /** A `uuid` column in the database that reads and writes prefixed ids (`foo_…`) in code. */
14
20
  const postgresIdColumnCreate = (prefix) => {
15
21
  const column = customType({
16
22
  dataType: () => "uuid",
@@ -29,23 +35,32 @@ const isoInstantIs = (value) => {
29
35
  const [year = 0, month = 0, day = 0] = value.slice(0, 10).split("-").map(Number);
30
36
  return new Date(Date.UTC(year, month - 1, day)).getUTCDate() === day;
31
37
  };
32
- const INT4 = [-(2 ** 31), 2 ** 31 - 1];
33
- const INT2 = [-(2 ** 15), 2 ** 15 - 1];
38
+ const int4Range = [-(2 ** 31), 2 ** 31 - 1];
39
+ const int2Range = [-(2 ** 15), 2 ** 15 - 1];
34
40
  const integerRanges = {
35
- integer: INT4,
36
- serial: INT4,
37
- smallint: INT2,
38
- smallserial: INT2
41
+ integer: int4Range,
42
+ serial: int4Range,
43
+ smallint: int2Range,
44
+ smallserial: int2Range
39
45
  };
40
46
  const integerKindAssert = (sortColumn) => {
41
47
  const type = sortColumn.getSQLType();
42
- if (integerRanges[type] !== INT4) throw new TypeError(`An integer keyset needs an integer or serial column, got ${type}`);
48
+ if (integerRanges[type] !== int4Range) throw new TypeError(`postgresKeysetCreate: sortColumn: an integer keyset needs an integer or serial column, got ${type}`);
43
49
  };
44
50
  const afterValueAssert = ({ kind, sortColumn, value }) => {
45
51
  const numeric = kind === "integer" || kind === "number";
46
52
  const range = numeric ? integerRanges[sortColumn.getSQLType()] : void 0;
47
- if (!(numeric ? typeof value === "number" && (range ? Number.isInteger(value) && value >= range[0] && value <= range[1] : Number.isFinite(value)) : typeof value === "string" && (kind === "text" || isoInstantIs(value)))) throw new TypeError(`${kind === "integer" ? "An" : "A"} ${kind} keyset needs ${range ? `an integer from ${range[0]} to ${range[1]}` : kind === "number" ? "a finite number" : kind === "date" ? "an ISO instant such as 2026-01-01T00:00:00.000Z" : "a string"}, got ${JSON.stringify(value)}`);
53
+ if (!(numeric ? typeof value === "number" && (range ? Number.isInteger(value) && value >= range[0] && value <= range[1] : Number.isFinite(value)) : typeof value === "string" && (kind === "text" || isoInstantIs(value)))) throw new TypeError(`postgresKeysetCreate: after.value: ${kind === "integer" ? "an" : "a"} ${kind} keyset needs ${range ? `an integer from ${range[0]} to ${range[1]}` : kind === "number" ? "a finite number" : kind === "date" ? "an ISO instant such as 2026-01-01T00:00:00.000Z" : "a string"}, got ${JSON.stringify(value)}`);
48
54
  };
55
+ /**
56
+ * Keyset ("seek") paging on (sort, id): the rows after `after` in the order of `orderBy`. The sort
57
+ * column must be NOT NULL (a NULL never compares), and a `date` column must hold no more than
58
+ * milliseconds, the precision of the JS Date a cursor is written from. Decode and check the
59
+ * cursor before calling; a value of the wrong type for `kind`, a number an integer or smallint
60
+ * sort column cannot hold, or kind `integer` on another column type, throws a TypeError.
61
+ * A number is bound untyped so Postgres reads it as the column's own type: a `::numeric` cast
62
+ * would turn an integer column's index condition into a filter over the whole index.
63
+ */
49
64
  const postgresKeysetCreate = ({ after, descending, idColumn, kind, sortColumn }) => {
50
65
  if (kind === "integer") integerKindAssert(sortColumn);
51
66
  const sortBy = kind === "text" ? sql`${sortColumn} COLLATE "C"` : sql`${sortColumn}`;
@@ -67,11 +82,16 @@ const postgresKeysetCreate = ({ after, descending, idColumn, kind, sortColumn })
67
82
  };
68
83
  };
69
84
  // src/postgres-url-assert.ts
70
- const postgresUrlAssert = (databaseUrl) => {
85
+ /**
86
+ * Pool and migrate accept only Postgres URLs; the composition root handles memory:// first.
87
+ * The message names the scheme but never the URL, which may hold a password. `caller` is the
88
+ * public function that was handed the URL, which the message starts with.
89
+ */
90
+ const postgresUrlAssert = (databaseUrl, caller) => {
71
91
  if (/^postgres(ql)?:\/\//.test(databaseUrl)) return;
72
92
  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(databaseUrl)?.[1];
73
93
  const found = scheme ? `"${scheme}://"` : "no scheme";
74
- throw new TypeError(`Invalid database URL: found ${found}; use postgres:// or postgresql://`);
94
+ throw new TypeError(`${caller}: databaseUrl must start with postgres:// or postgresql://, found ${found}`);
75
95
  };
76
96
  // src/postgres-vendor-assert.ts
77
97
  const postgresVendorOwnedKeys = {
@@ -90,26 +110,44 @@ const postgresUrlSslParams = [
90
110
  "sslmode",
91
111
  "sslrootcert"
92
112
  ];
93
- const postgresVendorAssert = ({ databaseUrl, owned = {}, vendor }) => {
113
+ const postgresUrlParamsRead = (databaseUrl, caller) => {
114
+ try {
115
+ return new URL(databaseUrl).searchParams;
116
+ } catch {
117
+ throw new TypeError(`${caller}: databaseUrl is not a valid URL`);
118
+ }
119
+ };
120
+ /**
121
+ * Throws on a vendor setting that a named option or the URL already decides. `caller` is the
122
+ * public function that was handed `vendor`, which the message starts with.
123
+ */
124
+ const postgresVendorAssert = ({ caller, databaseUrl, owned, vendor }) => {
94
125
  for (const [key, option] of Object.entries({
95
126
  ...postgresVendorOwnedKeys,
96
127
  ...owned
97
- })) if (key in vendor) throw new TypeError(`vendor.${key} is not allowed: set it with ${option} instead`);
98
- const urlParams = new URL(databaseUrl).searchParams;
128
+ })) if (key in vendor) throw new TypeError(`${caller}: vendor.${key} is not allowed: set it with ${option} instead`);
129
+ const urlParams = postgresUrlParamsRead(databaseUrl, caller);
99
130
  const sslParam = postgresUrlSslParams.find((name) => urlParams.has(name));
100
- if ("ssl" in vendor && sslParam !== void 0) throw new TypeError(`vendor.ssl is not allowed with ${sslParam} in databaseUrl: pg lets the URL win; set TLS in one place`);
131
+ if ("ssl" in vendor && sslParam !== void 0) throw new TypeError(`${caller}: vendor.ssl is not allowed with ${sslParam} in databaseUrl: pg lets the URL win; set TLS in one place`);
101
132
  };
102
133
  // src/postgres-migrate.ts
134
+ /** A fixed 64-bit advisory lock key: the first 8 bytes of SHA-256("baseline:migrate"). */
103
135
  const postgresMigrateLockKey = createHash("sha256").update("baseline:migrate").digest().readBigInt64BE(0).toString();
104
136
  const lockNotAvailable = "55P03";
137
+ /**
138
+ * Applies pending Drizzle migrations under an advisory lock, so concurrent runs (several
139
+ * containers starting at once) apply each migration once: a second run waits, then finds nothing.
140
+ * The lock belongs to the session, so the connection must reach Postgres itself, not a pooler.
141
+ */
105
142
  const postgresMigrate = async (options) => {
106
- postgresUrlAssert(options.databaseUrl);
143
+ postgresUrlAssert(options.databaseUrl, "postgresMigrate");
107
144
  postgresVendorAssert({
108
- vendor: options.vendor ?? {},
109
- databaseUrl: options.databaseUrl
145
+ caller: "postgresMigrate",
146
+ databaseUrl: options.databaseUrl,
147
+ vendor: options.vendor ?? {}
110
148
  });
111
149
  const lockWaitMs = options.lockWaitMs ?? 6e4;
112
- if (!Number.isSafeInteger(lockWaitMs) || lockWaitMs <= 0) throw new TypeError("lockWaitMs must be a positive integer");
150
+ if (!Number.isSafeInteger(lockWaitMs) || lockWaitMs <= 0) throw new TypeError("postgresMigrate: lockWaitMs must be a positive integer");
113
151
  const pgClient = new pg.Client({
114
152
  ...options.vendor,
115
153
  connectionString: options.databaseUrl,
@@ -134,17 +172,29 @@ const postgresMigrate = async (options) => {
134
172
  }
135
173
  };
136
174
  // src/postgres-pool.ts
137
- const postgresPoolCreate = ({ connectTimeoutMs = 3e3, databaseUrl, max = 10, queryTimeoutMs = 15e3, vendor = {} }) => {
138
- postgresUrlAssert(databaseUrl);
175
+ const postgresPositiveIntegerIs = (value) => Number.isSafeInteger(value) && value > 0;
176
+ /**
177
+ * The process's one Postgres pool. pg 8.23 ignores `?connect_timeout=` in the URL, so the
178
+ * settings live here.
179
+ */
180
+ const postgresPoolCreate = (options) => {
181
+ const { databaseUrl, queryTimeoutMs = 15e3 } = options;
182
+ const connectTimeoutMs = options.connectTimeoutMs ?? 3e3;
183
+ const max = options.max ?? 10;
184
+ const vendor = options.vendor ?? {};
185
+ postgresUrlAssert(databaseUrl, "postgresPoolCreate");
139
186
  postgresVendorAssert({
140
- vendor,
187
+ caller: "postgresPoolCreate",
141
188
  databaseUrl,
142
189
  owned: {
143
190
  max: "max",
144
191
  query_timeout: "queryTimeoutMs"
145
- }
192
+ },
193
+ vendor
146
194
  });
147
- if (queryTimeoutMs !== null && (!Number.isSafeInteger(queryTimeoutMs) || queryTimeoutMs <= 0)) throw new TypeError("queryTimeoutMs must be a positive integer or null");
195
+ if (!postgresPositiveIntegerIs(connectTimeoutMs)) throw new TypeError("postgresPoolCreate: connectTimeoutMs must be a positive integer");
196
+ if (!postgresPositiveIntegerIs(max)) throw new TypeError("postgresPoolCreate: max must be a positive integer");
197
+ if (queryTimeoutMs !== null && !postgresPositiveIntegerIs(queryTimeoutMs)) throw new TypeError("postgresPoolCreate: queryTimeoutMs must be a positive integer or null");
148
198
  const pgPool = new pg.Pool({
149
199
  keepAlive: true,
150
200
  keepAliveInitialDelayMillis: 1e4,
@@ -165,9 +215,13 @@ const clientGuard = (pgClient, isOpen) => new Proxy(pgClient, { get(target, prop
165
215
  const value = Reflect.get(target, property, target);
166
216
  return typeof value === "function" ? value.bind(target) : value;
167
217
  } });
218
+ /**
219
+ * Runs `work` in one transaction on one checked-out client: COMMIT on ok, ROLLBACK on err or a
220
+ * throw. transaction_timeout (Postgres 17+) ends a transaction that runs longer than timeoutMs.
221
+ */
168
222
  const postgresTransactionRun = async ({ pgPool, timeoutMs: timeoutMsGiven, work }) => {
169
223
  const timeoutMs = timeoutMsGiven ?? 5e3;
170
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer");
224
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("postgresTransactionRun: timeoutMs must be a positive integer");
171
225
  const pgClient = await pgPool.connect();
172
226
  let broken = false;
173
227
  let open = true;
@@ -213,7 +267,13 @@ const violationFind = (error) => {
213
267
  current = "cause" in current ? current.cause : void 0;
214
268
  }
215
269
  };
270
+ /** True when `error` or any error in its `.cause` chain is a unique violation on `constraint`. */
216
271
  const postgresUniqueViolationIs = (error, constraint) => violationFind(error)?.constraint === constraint;
272
+ /**
273
+ * Postgres words the detail `Key (a, b)=(1, x) already exists.` and quotes nothing, so a value
274
+ * that holds ", " in a key of two or more columns cannot be split: then both lists are empty
275
+ * rather than misaligned.
276
+ */
217
277
  const postgresUniqueViolationRead = (error) => {
218
278
  const found = violationFind(error);
219
279
  if (!found) return void 0;
package/dist/testing.d.ts CHANGED
@@ -4,6 +4,7 @@ type PostgresTestInterleavePool = {
4
4
  rows: unknown[];
5
5
  }>;
6
6
  };
7
+ /** What `postgresTestInterleave` takes. */
7
8
  type PostgresTestInterleaveOptions<A, B> = {
8
9
  /** Runs until it awaits `pause()`, typically right after it took a lock. */
9
10
  first: (pause: () => Promise<void>) => Promise<A>;
@@ -13,6 +14,12 @@ type PostgresTestInterleaveOptions<A, B> = {
13
14
  /** How long `second` may run without waiting on a lock or finishing. Default 5 s. */
14
15
  timeoutMs?: number | null;
15
16
  };
17
+ /**
18
+ * Forces the interleaving a race test needs: `first` runs to `pause()`, `second` starts, and
19
+ * `first` resumes only once `second` waits on a lock or has finished. `secondWaited` says which.
20
+ * A backend that waited on a lock before `second` started does not count; any other one in the
21
+ * same database does, so keep other work off the test's database while it runs.
22
+ */
16
23
  export declare const postgresTestInterleave: <A, B>({ first, pgPool, second, timeoutMs: timeoutMsGiven }: PostgresTestInterleaveOptions<A, B>) => Promise<{
17
24
  first: A;
18
25
  second: B;
package/dist/testing.js CHANGED
@@ -5,6 +5,12 @@ const lockWaitersRead = async (pgPool) => {
5
5
  WHERE datname = current_database() AND wait_event_type = 'Lock' AND pid <> pg_backend_pid()`);
6
6
  return new Set(rows.map((row) => typeof row === "object" && row !== null && "pid" in row ? row.pid : void 0));
7
7
  };
8
+ /**
9
+ * Forces the interleaving a race test needs: `first` runs to `pause()`, `second` starts, and
10
+ * `first` resumes only once `second` waits on a lock or has finished. `secondWaited` says which.
11
+ * A backend that waited on a lock before `second` started does not count; any other one in the
12
+ * same database does, so keep other work off the test's database while it runs.
13
+ */
8
14
  const postgresTestInterleave = async ({ first, pgPool, second, timeoutMs: timeoutMsGiven }) => {
9
15
  const timeoutMs = timeoutMsGiven ?? 5e3;
10
16
  const { promise: paused, resolve: pausedResolve } = Promise.withResolvers();
package/package.json CHANGED
@@ -1,21 +1,17 @@
1
1
  {
2
2
  "name": "@n8io/baseline-postgres",
3
- "version": "5.3.1",
4
- "description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
5
- "type": "module",
3
+ "version": "5.4.0",
4
+ "description": "One pool, transactions that follow your Result and migrations that run once however many processes start, plus prefixed-id columns and keyset paging.",
6
5
  "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
7
10
  "repository": {
8
11
  "type": "git",
9
12
  "url": "git+https://github.com/n8io/baseline.git",
10
13
  "directory": "packages/postgres"
11
14
  },
12
- "engines": {
13
- "node": ">=26"
14
- },
15
- "files": [
16
- "dist",
17
- "README.md"
18
- ],
19
15
  "exports": {
20
16
  ".": {
21
17
  "types": "./dist/index.d.ts",
@@ -26,14 +22,23 @@
26
22
  "default": "./dist/testing.js"
27
23
  }
28
24
  },
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
29
  "publishConfig": {
30
30
  "access": "public",
31
31
  "registry": "https://registry.npmjs.org"
32
32
  },
33
33
  "dependencies": {
34
- "@n8io/baseline-id": "^3.0.1",
35
- "@n8io/baseline-logger": "^3.1.1",
36
- "@n8io/baseline-result": "^1.1.2"
34
+ "@n8io/baseline-id": "^3.0.2",
35
+ "@n8io/baseline-logger": "^3.1.2",
36
+ "@n8io/baseline-result": "^1.1.4"
37
+ },
38
+ "devDependencies": {
39
+ "@types/pg": "^8.23.1",
40
+ "drizzle-orm": "1.0.0-rc.5",
41
+ "pg": "^8.23.1"
37
42
  },
38
43
  "peerDependencies": {
39
44
  "@types/pg": "^8",
@@ -45,11 +50,6 @@
45
50
  "optional": true
46
51
  }
47
52
  },
48
- "devDependencies": {
49
- "@types/pg": "^8.23.1",
50
- "drizzle-orm": "1.0.0-rc.5",
51
- "pg": "^8.23.1"
52
- },
53
53
  "scripts": {
54
54
  "build": "tsdown",
55
55
  "check": "tsc --noEmit && pnpm pack --out dist/package.tgz && publint dist/package.tgz --strict && attw dist/package.tgz --profile esm-only",