@n8io/baseline-postgres 1.2.0 → 3.0.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
@@ -8,34 +8,33 @@ pnpm add @n8io/baseline-postgres
8
8
 
9
9
  ## Exports
10
10
 
11
- - `postgresPoolCreate({ databaseUrl, ...pg.PoolConfig })`: the process's one pool (10 connections, 3 s connect timeout).
12
- - `postgresTransaction(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).
13
- - `postgresPortsGuard(ports, isOpen)`: wraps a transaction's ports so a call after the transaction ended throws.
14
- - `postgresMigrate({ databaseUrl, migrationsFolder })`: applies pending Drizzle migrations under an advisory lock, so concurrent starts apply each one once.
15
- - `postgresIdColumn(prefix)`: a Drizzle `uuid` column that reads and writes `Id<prefix>`.
16
- - `postgresCursorEncode(cursor)`, `postgresCursorDecode(text, prefix)`, `PostgresCursor`: a list page's position as base64url; a cursor that does not decode reads as none.
17
- - `postgresUniqueViolation(error, constraint)`: true when a unique violation on that constraint is anywhere in the `cause` chain.
11
+ - `postgresPoolCreate({ databaseUrl, max?, connectTimeoutMs?, vendor? })`: the process's one pool (10 connections, 3 s connect timeout). `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.
12
+ - `PostgresPool`, `PostgresClient`: the pool and a checked-out connection. 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.
13
+ - `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).
14
+ - `postgresMigrate({ databaseUrl, migrationsFolder, vendor? })`: applies pending Drizzle migrations under an advisory lock, so concurrent starts apply each one once. `vendor` takes pg's settings for its one connection, under the same rules as the pool's.
15
+ - `postgresIdColumnCreate(prefix)`: a Drizzle `uuid` column that reads and writes `Id<prefix>`.
16
+ - `postgresUniqueViolationIs(error, constraint)`: true when a unique violation on that constraint is anywhere in the `cause` chain.
18
17
 
19
18
  ## Example
20
19
 
21
20
  ```ts
22
21
  import {
23
- postgresIdColumn,
22
+ postgresIdColumnCreate,
24
23
  postgresPoolCreate,
25
- postgresTransaction,
24
+ postgresTransactionRun,
26
25
  } from "@n8io/baseline-postgres";
27
26
  import { err, ok } from "@n8io/baseline-result";
28
27
  import { drizzle } from "drizzle-orm/node-postgres";
29
28
  import { pgTable, text } from "drizzle-orm/pg-core";
30
29
 
31
30
  export const fooTable = pgTable("foo", {
32
- id: postgresIdColumn("foo")().primaryKey(),
31
+ id: postgresIdColumnCreate("foo")().primaryKey(),
33
32
  name: text().notNull(),
34
33
  });
35
34
 
36
35
  const pgPool = postgresPoolCreate({ databaseUrl: ENV.DATABASE_URL });
37
36
 
38
- const result = await postgresTransaction(pgPool, async (pgClient) => {
37
+ const result = await postgresTransactionRun(pgPool, async (pgClient) => {
39
38
  const rows = await drizzle({ client: pgClient })
40
39
  .insert(fooTable)
41
40
  .values(foo)
package/dist/index.d.ts CHANGED
@@ -2,28 +2,55 @@ import { Id } from "@n8io/baseline-id";
2
2
  import { PgCustomColumnBuilder } from "drizzle-orm/pg-core";
3
3
  import pg from "pg";
4
4
  import { Result } from "@n8io/baseline-result";
5
- type PostgresCursor<P extends string> = {
6
- k: string;
7
- id: Id<P>;
8
- };
9
- export declare const postgresCursorEncode: <P extends string>(cursor: PostgresCursor<P>) => string;
10
- export declare const postgresCursorDecode: <P extends string>(cursor: string, prefix: P) => PostgresCursor<P> | undefined;
11
5
  type PostgresIdColumnBuilder<P extends string> = PgCustomColumnBuilder<{
12
6
  data: Id<P>;
13
7
  dataType: "custom";
14
8
  driverParam: string;
15
9
  }>;
16
- export declare const postgresIdColumn: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
10
+ export declare const postgresIdColumnCreate: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
11
+ declare const postgresVendorOwnedKeys: {
12
+ readonly connectionString: "databaseUrl";
13
+ readonly connectionTimeoutMillis: "connectTimeoutMs";
14
+ readonly database: "databaseUrl";
15
+ readonly host: "databaseUrl";
16
+ readonly password: "databaseUrl";
17
+ readonly port: "databaseUrl";
18
+ readonly user: "databaseUrl";
19
+ };
20
+ type PostgresVendorOwnedKey = keyof typeof postgresVendorOwnedKeys;
21
+ /**
22
+ * pg's own client settings for the migration's one connection, passed through as they are.
23
+ * Outside this Package's contract, like `PostgresPoolVendorOptions`.
24
+ */
25
+ type PostgresMigrateVendorOptions = Omit<pg.ClientConfig, PostgresVendorOwnedKey>;
17
26
  export declare const postgresMigrate: (options: {
18
27
  databaseUrl: string;
19
28
  migrationsFolder: string;
29
+ /** Settings only pg has, such as `ssl`: the same ones the pool takes. */
30
+ vendor?: PostgresMigrateVendorOptions;
20
31
  }) => Promise<void>;
21
- export declare const postgresPoolCreate: (options: {
32
+ /** The process's Postgres connection pool. Close it with `end()`. */
33
+ type PostgresPool = pg.Pool;
34
+ /** One connection checked out of the pool: what `postgresTransactionRun` hands to its work. */
35
+ type PostgresClient = pg.PoolClient;
36
+ /**
37
+ * pg's own pool settings, passed through as they are. Outside this Package's contract: nothing
38
+ * here is tested, and moving off pg deletes it. The keys the named options and the URL set are
39
+ * refused.
40
+ */
41
+ type PostgresPoolVendorOptions = Omit<pg.PoolConfig, PostgresVendorOwnedKey | "max">;
42
+ type PostgresPoolOptions = {
22
43
  databaseUrl: string;
23
- } & Partial<pg.PoolConfig>) => pg.Pool;
24
- export declare const postgresPortsGuard: <T extends object>(ports: T, isOpen: () => boolean) => T;
25
- export declare const postgresTransaction: <T, E>(pgPool: pg.Pool, work: (pgClient: pg.PoolClient) => Promise<Result<T, E>>, options?: {
44
+ /** How long a connect may take. Default 3 s. */
45
+ connectTimeoutMs?: number;
46
+ /** The most connections the pool opens. Default 10. */
47
+ max?: number;
48
+ /** Settings only pg has, such as `ssl` or `idleTimeoutMillis`. */
49
+ vendor?: PostgresPoolVendorOptions;
50
+ };
51
+ export declare const postgresPoolCreate: ({ connectTimeoutMs, databaseUrl, max, vendor }: PostgresPoolOptions) => PostgresPool;
52
+ export declare const postgresTransactionRun: <T, E>(pgPool: PostgresPool, work: (pgClient: PostgresClient) => Promise<Result<T, E>>, options?: {
26
53
  timeoutMs?: number;
27
54
  }) => Promise<Result<T, E>>;
28
- export declare const postgresUniqueViolation: (error: unknown, constraint: string) => boolean;
29
- export type { PostgresCursor };
55
+ export declare const postgresUniqueViolationIs: (error: unknown, constraint: string) => boolean;
56
+ export type { PostgresClient, PostgresMigrateVendorOptions, PostgresPool, PostgresPoolOptions, PostgresPoolVendorOptions };
package/dist/index.js CHANGED
@@ -5,23 +5,8 @@ import { drizzle } from "drizzle-orm/node-postgres";
5
5
  import { migrate } from "drizzle-orm/node-postgres/migrator";
6
6
  import pg from "pg";
7
7
  import { logger } from "@n8io/baseline-logger";
8
- // src/postgres-cursor.ts
9
- const postgresCursorEncode = (cursor) => Buffer.from(JSON.stringify(cursor)).toString("base64url");
10
- const postgresCursorDecode = (cursor, prefix) => {
11
- try {
12
- const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString());
13
- if (typeof parsed !== "object" || parsed === null) return void 0;
14
- const { id, k } = parsed;
15
- return typeof k === "string" && typeof id === "string" && id.startsWith(`${prefix}_`) ? {
16
- id,
17
- k
18
- } : void 0;
19
- } catch {
20
- return;
21
- }
22
- };
23
8
  // src/postgres-id-column.ts
24
- const postgresIdColumn = (prefix) => {
9
+ const postgresIdColumnCreate = (prefix) => {
25
10
  const column = customType({
26
11
  dataType: () => "uuid",
27
12
  fromDriver: (value) => idFromUuid(prefix, value),
@@ -39,11 +24,39 @@ const postgresUrlAssert = (databaseUrl) => {
39
24
  const found = scheme ? `"${scheme}://"` : "no scheme";
40
25
  throw new TypeError(`Invalid database URL: found ${found}; use postgres:// or postgresql://`);
41
26
  };
27
+ // src/postgres-vendor-assert.ts
28
+ const postgresVendorOwnedKeys = {
29
+ connectionString: "databaseUrl",
30
+ connectionTimeoutMillis: "connectTimeoutMs",
31
+ database: "databaseUrl",
32
+ host: "databaseUrl",
33
+ password: "databaseUrl",
34
+ port: "databaseUrl",
35
+ user: "databaseUrl"
36
+ };
37
+ const postgresUrlSslParams = [
38
+ "ssl",
39
+ "sslcert",
40
+ "sslkey",
41
+ "sslmode",
42
+ "sslrootcert"
43
+ ];
44
+ const postgresVendorAssert = (vendor, databaseUrl, owned = {}) => {
45
+ for (const [key, option] of Object.entries({
46
+ ...postgresVendorOwnedKeys,
47
+ ...owned
48
+ })) if (key in vendor) throw new TypeError(`vendor.${key} is not allowed: set it with ${option} instead`);
49
+ const urlParams = new URL(databaseUrl).searchParams;
50
+ const sslParam = postgresUrlSslParams.find((name) => urlParams.has(name));
51
+ 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`);
52
+ };
42
53
  // src/postgres-migrate.ts
43
54
  const postgresMigrateLockKey = createHash("sha256").update("baseline:migrate").digest().readBigInt64BE(0).toString();
44
55
  const postgresMigrate = async (options) => {
45
56
  postgresUrlAssert(options.databaseUrl);
57
+ postgresVendorAssert(options.vendor ?? {}, options.databaseUrl);
46
58
  const pgClient = new pg.Client({
59
+ ...options.vendor,
47
60
  connectionString: options.databaseUrl,
48
61
  connectionTimeoutMillis: 3e3
49
62
  });
@@ -57,34 +70,29 @@ const postgresMigrate = async (options) => {
57
70
  await pgClient.end();
58
71
  }
59
72
  };
60
- // src/postgres-pool-create.ts
61
- const postgresPoolCreate = (options) => {
62
- const { databaseUrl, ...overrides } = options;
73
+ // src/postgres-pool.ts
74
+ const postgresPoolCreate = ({ connectTimeoutMs = 3e3, databaseUrl, max = 10, vendor = {} }) => {
63
75
  postgresUrlAssert(databaseUrl);
76
+ postgresVendorAssert(vendor, databaseUrl, { max: "max" });
64
77
  const pgPool = new pg.Pool({
65
- connectionString: databaseUrl,
66
- connectionTimeoutMillis: 3e3,
67
78
  keepAlive: true,
68
- max: 10,
69
- ...overrides
79
+ ...vendor,
80
+ connectionString: databaseUrl,
81
+ connectionTimeoutMillis: connectTimeoutMs,
82
+ max
70
83
  });
71
84
  pgPool.on("error", (error) => {
72
85
  logger.error({ err: error }, "Postgres idle client error");
73
86
  });
74
87
  return pgPool;
75
88
  };
76
- // src/postgres-ports-guard.ts
77
- const postgresPortsGuard = (ports, isOpen) => Object.fromEntries(Object.entries(ports).map(([key, value]) => [key, typeof value === "function" ? async (...args) => {
78
- if (!isOpen()) throw new Error("Transaction ports used after the transaction ended; keep every call inside the callback");
79
- return value(...args);
80
- } : value]));
81
- // src/postgres-transaction.ts
89
+ // src/postgres-transaction-run.ts
82
90
  const clientGuard = (pgClient, isOpen) => new Proxy(pgClient, { get(target, property) {
83
91
  if (!isOpen()) throw new Error("Postgres client used after its transaction ended; keep every query inside the callback");
84
92
  const value = Reflect.get(target, property, target);
85
93
  return typeof value === "function" ? value.bind(target) : value;
86
94
  } });
87
- const postgresTransaction = async (pgPool, work, options = {}) => {
95
+ const postgresTransactionRun = async (pgPool, work, options = {}) => {
88
96
  const timeoutMs = options.timeoutMs ?? 5e3;
89
97
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer");
90
98
  const pgClient = await pgPool.connect();
@@ -119,8 +127,8 @@ const postgresTransaction = async (pgPool, work, options = {}) => {
119
127
  pgClient.release(broken || void 0);
120
128
  }
121
129
  };
122
- // src/postgres-unique-violation.ts
123
- const postgresUniqueViolation = (error, constraint) => {
130
+ // src/postgres-unique-violation-is.ts
131
+ const postgresUniqueViolationIs = (error, constraint) => {
124
132
  const seen = /* @__PURE__ */ new Set();
125
133
  let current = error;
126
134
  while (typeof current === "object" && current !== null && !seen.has(current)) {
@@ -130,4 +138,4 @@ const postgresUniqueViolation = (error, constraint) => {
130
138
  }
131
139
  return false;
132
140
  };
133
- export { postgresCursorDecode, postgresCursorEncode, postgresIdColumn, postgresMigrate, postgresPoolCreate, postgresPortsGuard, postgresTransaction, postgresUniqueViolation };
141
+ export { postgresIdColumnCreate, postgresMigrate, postgresPoolCreate, postgresTransactionRun, postgresUniqueViolationIs };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n8io/baseline-postgres",
3
- "version": "1.2.0",
3
+ "version": "3.0.0",
4
4
  "description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,9 +27,9 @@
27
27
  "registry": "https://registry.npmjs.org"
28
28
  },
29
29
  "dependencies": {
30
- "@n8io/baseline-id": "^1.1.0",
31
- "@n8io/baseline-logger": "^2.1.0",
32
- "@n8io/baseline-result": "^1.1.0"
30
+ "@n8io/baseline-id": "^2.0.0",
31
+ "@n8io/baseline-logger": "^3.0.0",
32
+ "@n8io/baseline-result": "^1.1.1"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "@types/pg": "^8",
@@ -49,6 +49,7 @@
49
49
  "scripts": {
50
50
  "build": "tsdown",
51
51
  "check": "tsc --noEmit && pnpm pack --out dist/package.tgz && publint dist/package.tgz --strict && attw dist/package.tgz --profile esm-only",
52
- "test": "vitest run"
52
+ "test": "vitest run",
53
+ "test:unit": "vitest run --project unit --passWithNoTests"
53
54
  }
54
55
  }