@n8io/baseline-postgres 0.0.0-stage → 1.1.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.
@@ -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,53 @@
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.1.0",
4
+ "description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
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
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "registry": "https://registry.npmjs.org"
27
+ },
28
+ "dependencies": {
29
+ "@n8io/baseline-id": "^1.0.0",
30
+ "@n8io/baseline-logger": "^2.0.0",
31
+ "@n8io/baseline-result": "^1.0.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@types/pg": "^8",
35
+ "drizzle-orm": "1.0.0-rc.5",
36
+ "pg": "^8.23.1"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "@types/pg": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "devDependencies": {
44
+ "@types/pg": "^8.23.1",
45
+ "drizzle-orm": "1.0.0-rc.5",
46
+ "pg": "^8.23.1"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "check": "tsc --noEmit && pnpm pack --out dist/package.tgz && publint dist/package.tgz --strict && attw dist/package.tgz --profile esm-only",
51
+ "test": "vitest run"
52
+ }
6
53
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.