@n8io/baseline-postgres 0.0.0-stage → 1.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nate Clark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @n8io/baseline-postgres
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Postgres on [pg](https://node-postgres.com) and [Drizzle](https://orm.drizzle.team): one pool, Result-aware transactions, migrations under a lock, and columns that store prefixed ids as `uuid`.
4
+
5
+ ```sh
6
+ pnpm add @n8io/baseline-postgres
7
+ ```
8
+
9
+ ## Exports
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.
18
+
19
+ ## Example
20
+
21
+ ```ts
22
+ import {
23
+ postgresIdColumn,
24
+ postgresPoolCreate,
25
+ postgresTransaction,
26
+ } from "@n8io/baseline-postgres";
27
+ import { err, ok } from "@n8io/baseline-result";
28
+ import { drizzle } from "drizzle-orm/node-postgres";
29
+ import { pgTable, text } from "drizzle-orm/pg-core";
30
+
31
+ export const fooTable = pgTable("foo", {
32
+ id: postgresIdColumn("foo")().primaryKey(),
33
+ name: text().notNull(),
34
+ });
35
+
36
+ const pgPool = postgresPoolCreate({ databaseUrl: ENV.DATABASE_URL });
37
+
38
+ const result = await postgresTransaction(pgPool, async (pgClient) => {
39
+ const rows = await drizzle({ client: pgClient })
40
+ .insert(fooTable)
41
+ .values(foo)
42
+ .returning();
43
+ return rows[0] ? ok(rows[0]) : err({ type: "FooNotCreated" as const });
44
+ });
45
+ ```
46
+
47
+ ## Needs
48
+
49
+ - Peers: `pg`, `drizzle-orm` (`1.0.0-rc.5`, pinned until 1.0 is out) and, for types, `@types/pg`.
50
+ - Env, by the template's convention: `DATABASE_URL` (`postgres://` or `postgresql://`). Transactions use `transaction_timeout`, so Postgres 17 or newer.
51
+
52
+ ## Tests
53
+
54
+ `pnpm test` needs Docker: it starts a Postgres container.
@@ -0,0 +1,29 @@
1
+ import { Id } from "@n8io/baseline-id";
2
+ import { PgCustomColumnBuilder } from "drizzle-orm/pg-core";
3
+ import pg from "pg";
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
+ type PostgresIdColumnBuilder<P extends string> = PgCustomColumnBuilder<{
12
+ data: Id<P>;
13
+ dataType: "custom";
14
+ driverParam: string;
15
+ }>;
16
+ export declare const postgresIdColumn: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
17
+ export declare const postgresMigrate: (options: {
18
+ databaseUrl: string;
19
+ migrationsFolder: string;
20
+ }) => Promise<void>;
21
+ export declare const postgresPoolCreate: (options: {
22
+ 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?: {
26
+ timeoutMs?: number;
27
+ }) => Promise<Result<T, E>>;
28
+ export declare const postgresUniqueViolation: (error: unknown, constraint: string) => boolean;
29
+ export type { PostgresCursor };
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ import { idFromUuid, idToUuid } from "@n8io/baseline-id";
2
+ import { customType } from "drizzle-orm/pg-core";
3
+ import { createHash } from "node:crypto";
4
+ import { drizzle } from "drizzle-orm/node-postgres";
5
+ import { migrate } from "drizzle-orm/node-postgres/migrator";
6
+ import pg from "pg";
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
+ // src/postgres-id-column.ts
24
+ const postgresIdColumn = (prefix) => {
25
+ const column = customType({
26
+ dataType: () => "uuid",
27
+ fromDriver: (value) => idFromUuid(prefix, value),
28
+ toDriver: (value) => {
29
+ if (!value.startsWith(`${prefix}_`)) throw new TypeError(`Expected a ${prefix} id`);
30
+ return idToUuid(value);
31
+ }
32
+ });
33
+ return (name) => name === void 0 ? column() : column(name);
34
+ };
35
+ // src/postgres-url-assert.ts
36
+ const postgresUrlAssert = (databaseUrl) => {
37
+ if (/^postgres(ql)?:\/\//.test(databaseUrl)) return;
38
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(databaseUrl)?.[1];
39
+ const found = scheme ? `"${scheme}://"` : "no scheme";
40
+ throw new TypeError(`Invalid database URL: found ${found}; use postgres:// or postgresql://`);
41
+ };
42
+ // src/postgres-migrate.ts
43
+ const postgresMigrateLockKey = createHash("sha256").update("baseline:migrate").digest().readBigInt64BE(0).toString();
44
+ const postgresMigrate = async (options) => {
45
+ postgresUrlAssert(options.databaseUrl);
46
+ const pgClient = new pg.Client({
47
+ connectionString: options.databaseUrl,
48
+ connectionTimeoutMillis: 3e3
49
+ });
50
+ await pgClient.connect();
51
+ try {
52
+ await pgClient.query("SET statement_timeout = 0");
53
+ await pgClient.query("SELECT pg_advisory_lock($1::bigint)", [postgresMigrateLockKey]);
54
+ await pgClient.query("SET lock_timeout = '5s'");
55
+ await migrate(drizzle({ client: pgClient }), { migrationsFolder: options.migrationsFolder });
56
+ } finally {
57
+ await pgClient.end();
58
+ }
59
+ };
60
+ // src/postgres-pool-create.ts
61
+ const postgresPoolCreate = (options) => {
62
+ const { databaseUrl, ...overrides } = options;
63
+ postgresUrlAssert(databaseUrl);
64
+ const pgPool = new pg.Pool({
65
+ connectionString: databaseUrl,
66
+ connectionTimeoutMillis: 3e3,
67
+ keepAlive: true,
68
+ max: 10,
69
+ ...overrides
70
+ });
71
+ pgPool.on("error", (error) => {
72
+ logger.error({ err: error }, "Postgres idle client error");
73
+ });
74
+ return pgPool;
75
+ };
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
82
+ const clientGuard = (pgClient, isOpen) => new Proxy(pgClient, { get(target, property) {
83
+ if (!isOpen()) throw new Error("Postgres client used after its transaction ended; keep every query inside the callback");
84
+ const value = Reflect.get(target, property, target);
85
+ return typeof value === "function" ? value.bind(target) : value;
86
+ } });
87
+ const postgresTransaction = async (pgPool, work, options = {}) => {
88
+ const timeoutMs = options.timeoutMs ?? 5e3;
89
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer");
90
+ const pgClient = await pgPool.connect();
91
+ let broken = false;
92
+ let open = true;
93
+ const onError = (error) => {
94
+ broken = true;
95
+ logger.error({ err: error }, "Postgres transaction client error");
96
+ };
97
+ pgClient.on("error", onError);
98
+ try {
99
+ await pgClient.query("BEGIN");
100
+ await pgClient.query(`SET LOCAL transaction_timeout = '${timeoutMs}ms'`);
101
+ let result;
102
+ try {
103
+ result = await work(clientGuard(pgClient, () => open));
104
+ } finally {
105
+ open = false;
106
+ }
107
+ await pgClient.query(result.ok ? "COMMIT" : "ROLLBACK");
108
+ return result;
109
+ } catch (error) {
110
+ try {
111
+ await pgClient.query("ROLLBACK");
112
+ } catch {
113
+ broken = true;
114
+ }
115
+ throw error;
116
+ } finally {
117
+ open = false;
118
+ pgClient.off("error", onError);
119
+ pgClient.release(broken || void 0);
120
+ }
121
+ };
122
+ // src/postgres-unique-violation.ts
123
+ const postgresUniqueViolation = (error, constraint) => {
124
+ const seen = /* @__PURE__ */ new Set();
125
+ let current = error;
126
+ while (typeof current === "object" && current !== null && !seen.has(current)) {
127
+ seen.add(current);
128
+ if ("code" in current && current.code === "23505" && "constraint" in current && current.constraint === constraint) return true;
129
+ current = "cause" in current ? current.cause : void 0;
130
+ }
131
+ return false;
132
+ };
133
+ export { postgresCursorDecode, postgresCursorEncode, postgresIdColumn, postgresMigrate, postgresPoolCreate, postgresPortsGuard, postgresTransaction, postgresUniqueViolation };
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@n8io/baseline-postgres",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.2.0",
4
+ "description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/n8io/baseline.git",
10
+ "directory": "packages/postgres"
11
+ },
12
+ "engines": {
13
+ "node": ">=26"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org"
28
+ },
29
+ "dependencies": {
30
+ "@n8io/baseline-id": "^1.1.0",
31
+ "@n8io/baseline-logger": "^2.1.0",
32
+ "@n8io/baseline-result": "^1.1.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@types/pg": "^8",
36
+ "drizzle-orm": "1.0.0-rc.5",
37
+ "pg": "^8.23.1"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@types/pg": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "devDependencies": {
45
+ "@types/pg": "^8.23.1",
46
+ "drizzle-orm": "1.0.0-rc.5",
47
+ "pg": "^8.23.1"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown",
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"
53
+ }
6
54
  }