@n8io/baseline-postgres 1.1.0 → 2.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/LICENSE +21 -0
- package/README.md +52 -0
- package/dist/index.d.ts +4 -11
- package/dist/index.js +7 -27
- package/package.json +9 -7
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
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# @n8io/baseline-postgres
|
|
2
|
+
|
|
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
|
+
- `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).
|
|
13
|
+
- `postgresMigrate({ databaseUrl, migrationsFolder })`: applies pending Drizzle migrations under an advisory lock, so concurrent starts apply each one once.
|
|
14
|
+
- `postgresIdColumnCreate(prefix)`: a Drizzle `uuid` column that reads and writes `Id<prefix>`.
|
|
15
|
+
- `postgresUniqueViolationIs(error, constraint)`: true when a unique violation on that constraint is anywhere in the `cause` chain.
|
|
16
|
+
|
|
17
|
+
## Example
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import {
|
|
21
|
+
postgresIdColumnCreate,
|
|
22
|
+
postgresPoolCreate,
|
|
23
|
+
postgresTransactionRun,
|
|
24
|
+
} from "@n8io/baseline-postgres";
|
|
25
|
+
import { err, ok } from "@n8io/baseline-result";
|
|
26
|
+
import { drizzle } from "drizzle-orm/node-postgres";
|
|
27
|
+
import { pgTable, text } from "drizzle-orm/pg-core";
|
|
28
|
+
|
|
29
|
+
export const fooTable = pgTable("foo", {
|
|
30
|
+
id: postgresIdColumnCreate("foo")().primaryKey(),
|
|
31
|
+
name: text().notNull(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const pgPool = postgresPoolCreate({ databaseUrl: ENV.DATABASE_URL });
|
|
35
|
+
|
|
36
|
+
const result = await postgresTransactionRun(pgPool, async (pgClient) => {
|
|
37
|
+
const rows = await drizzle({ client: pgClient })
|
|
38
|
+
.insert(fooTable)
|
|
39
|
+
.values(foo)
|
|
40
|
+
.returning();
|
|
41
|
+
return rows[0] ? ok(rows[0]) : err({ type: "FooNotCreated" as const });
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Needs
|
|
46
|
+
|
|
47
|
+
- Peers: `pg`, `drizzle-orm` (`1.0.0-rc.5`, pinned until 1.0 is out) and, for types, `@types/pg`.
|
|
48
|
+
- Env, by the template's convention: `DATABASE_URL` (`postgres://` or `postgresql://`). Transactions use `transaction_timeout`, so Postgres 17 or newer.
|
|
49
|
+
|
|
50
|
+
## Tests
|
|
51
|
+
|
|
52
|
+
`pnpm test` needs Docker: it starts a Postgres container.
|
package/dist/index.d.ts
CHANGED
|
@@ -2,18 +2,12 @@ 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
|
|
10
|
+
export declare const postgresIdColumnCreate: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
|
|
17
11
|
export declare const postgresMigrate: (options: {
|
|
18
12
|
databaseUrl: string;
|
|
19
13
|
migrationsFolder: string;
|
|
@@ -21,9 +15,8 @@ export declare const postgresMigrate: (options: {
|
|
|
21
15
|
export declare const postgresPoolCreate: (options: {
|
|
22
16
|
databaseUrl: string;
|
|
23
17
|
} & Partial<pg.PoolConfig>) => pg.Pool;
|
|
24
|
-
export declare const
|
|
25
|
-
export declare const postgresTransaction: <T, E>(pgPool: pg.Pool, work: (pgClient: pg.PoolClient) => Promise<Result<T, E>>, options?: {
|
|
18
|
+
export declare const postgresTransactionRun: <T, E>(pgPool: pg.Pool, work: (pgClient: pg.PoolClient) => Promise<Result<T, E>>, options?: {
|
|
26
19
|
timeoutMs?: number;
|
|
27
20
|
}) => Promise<Result<T, E>>;
|
|
28
|
-
export declare const
|
|
29
|
-
export
|
|
21
|
+
export declare const postgresUniqueViolationIs: (error: unknown, constraint: string) => boolean;
|
|
22
|
+
export {};
|
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
|
|
9
|
+
const postgresIdColumnCreate = (prefix) => {
|
|
25
10
|
const column = customType({
|
|
26
11
|
dataType: () => "uuid",
|
|
27
12
|
fromDriver: (value) => idFromUuid(prefix, value),
|
|
@@ -57,7 +42,7 @@ const postgresMigrate = async (options) => {
|
|
|
57
42
|
await pgClient.end();
|
|
58
43
|
}
|
|
59
44
|
};
|
|
60
|
-
// src/postgres-pool
|
|
45
|
+
// src/postgres-pool.ts
|
|
61
46
|
const postgresPoolCreate = (options) => {
|
|
62
47
|
const { databaseUrl, ...overrides } = options;
|
|
63
48
|
postgresUrlAssert(databaseUrl);
|
|
@@ -73,18 +58,13 @@ const postgresPoolCreate = (options) => {
|
|
|
73
58
|
});
|
|
74
59
|
return pgPool;
|
|
75
60
|
};
|
|
76
|
-
// src/postgres-
|
|
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
|
|
61
|
+
// src/postgres-transaction-run.ts
|
|
82
62
|
const clientGuard = (pgClient, isOpen) => new Proxy(pgClient, { get(target, property) {
|
|
83
63
|
if (!isOpen()) throw new Error("Postgres client used after its transaction ended; keep every query inside the callback");
|
|
84
64
|
const value = Reflect.get(target, property, target);
|
|
85
65
|
return typeof value === "function" ? value.bind(target) : value;
|
|
86
66
|
} });
|
|
87
|
-
const
|
|
67
|
+
const postgresTransactionRun = async (pgPool, work, options = {}) => {
|
|
88
68
|
const timeoutMs = options.timeoutMs ?? 5e3;
|
|
89
69
|
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer");
|
|
90
70
|
const pgClient = await pgPool.connect();
|
|
@@ -119,8 +99,8 @@ const postgresTransaction = async (pgPool, work, options = {}) => {
|
|
|
119
99
|
pgClient.release(broken || void 0);
|
|
120
100
|
}
|
|
121
101
|
};
|
|
122
|
-
// src/postgres-unique-violation.ts
|
|
123
|
-
const
|
|
102
|
+
// src/postgres-unique-violation-is.ts
|
|
103
|
+
const postgresUniqueViolationIs = (error, constraint) => {
|
|
124
104
|
const seen = /* @__PURE__ */ new Set();
|
|
125
105
|
let current = error;
|
|
126
106
|
while (typeof current === "object" && current !== null && !seen.has(current)) {
|
|
@@ -130,4 +110,4 @@ const postgresUniqueViolation = (error, constraint) => {
|
|
|
130
110
|
}
|
|
131
111
|
return false;
|
|
132
112
|
};
|
|
133
|
-
export {
|
|
113
|
+
export { postgresIdColumnCreate, postgresMigrate, postgresPoolCreate, postgresTransactionRun, postgresUniqueViolationIs };
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n8io/baseline-postgres",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"license": "
|
|
6
|
+
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
9
|
"url": "git+https://github.com/n8io/baseline.git",
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
"node": ">=26"
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
|
-
"dist"
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
17
18
|
],
|
|
18
19
|
"exports": {
|
|
19
20
|
".": {
|
|
@@ -26,9 +27,9 @@
|
|
|
26
27
|
"registry": "https://registry.npmjs.org"
|
|
27
28
|
},
|
|
28
29
|
"dependencies": {
|
|
29
|
-
"@n8io/baseline-id": "^
|
|
30
|
-
"@n8io/baseline-logger": "^2.
|
|
31
|
-
"@n8io/baseline-result": "^1.
|
|
30
|
+
"@n8io/baseline-id": "^2.0.0",
|
|
31
|
+
"@n8io/baseline-logger": "^2.1.0",
|
|
32
|
+
"@n8io/baseline-result": "^1.1.1"
|
|
32
33
|
},
|
|
33
34
|
"peerDependencies": {
|
|
34
35
|
"@types/pg": "^8",
|
|
@@ -48,6 +49,7 @@
|
|
|
48
49
|
"scripts": {
|
|
49
50
|
"build": "tsdown",
|
|
50
51
|
"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
|
+
"test": "vitest run",
|
|
53
|
+
"test:unit": "vitest run --project unit --passWithNoTests"
|
|
52
54
|
}
|
|
53
55
|
}
|