@ingram-tech/nk-db 1.6.0 → 2.0.1

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
@@ -155,44 +155,103 @@ Drizzle `schema.ts`, a client component or an edge runtime can all use it. Keep
155
155
  it that way: a single `node:crypto` import makes every module that touches an id
156
156
  node-only (a test enforces this).
157
157
 
158
- Store the raw `uuid` and encode at the edge. The prefixed id is presentation, not
159
- identity: inside the DB, "which entity is this?" is already carried by the
160
- column, so storing the prefix duplicates schema metadata into every row.
161
-
162
- **Ids are self-describing, uuids are not.** A prefix names its entity, so
163
- decoding needs no context — `entityOf(registry, id)` and `decodeAnyId(registry,
164
- id)` resolve one from the value alone, which is what makes polymorphic FKs and
165
- raw-SQL bindings work. The inverse does not hold: encoding always needs to know
166
- which entity you meant. Automate decode; enforce encode with the `Id<E>` brand.
158
+ Store the raw `uuid`; the prefixed id is presentation, not identity. Inside the
159
+ DB, "which entity is this?" is already carried by the column, so storing the
160
+ prefix duplicates schema metadata into every row.
161
+
162
+ **The rule: application code only ever sees public ids.** An id is `inv_…` in
163
+ a URL, a form, a log line, a row read through Drizzle and a value passed to a
164
+ query. The conversion to and from `uuid` happens in exactly two places — the
165
+ column (`idColumn`, below) and the database (`id758_encode` / `id758_decode`,
166
+ below) — and nowhere else. Code that calls `ids.invoice.decode(param)` before a
167
+ query, or `ids.invoice.encode(row.id)` after one, is converting at the wrong
168
+ layer; the `nextkit/no-id-codec-in-app-code` lint flags it. Validate untrusted
169
+ input with `ids.invoice.is(param)` (a 404 on a wrong-entity id) and pass it
170
+ straight through.
167
171
 
168
172
  ### Drizzle bindings (`@ingram-tech/nk-db/id/drizzle`)
169
173
 
170
- Decode public ids at the **column**, so a skinned id reaching a query stops being
171
- a failure mode:
174
+ A column declared with `idColumn` is a plain `uuid` in Postgres that speaks
175
+ public ids in TypeScript:
172
176
 
173
177
  ```ts
178
+ // ids.ts
174
179
  export const ids = createIdRegistry({ invoice: "inv", account: "acct" });
175
- export const { idColumn, polymorphicIdColumn, sqlUuid, sqlUuidArray } =
180
+ export const { idColumn, polymorphicIdColumn, encodedId, sqlUuid, sqlUuidArray } =
176
181
  createIdColumns(ids);
177
182
 
183
+ // schema.ts
178
184
  export const invoices = pgTable("invoices", {
179
- id: idColumn("invoice")().primaryKey(), // eq(invoices.id, "inv_…") just works
185
+ id: idColumn("invoice")().primaryKey().default(sql`uuidv7()`),
180
186
  account_id: idColumn("account")().notNull(),
181
- entity_id: polymorphicIdColumn(), // decodes any entity's id
187
+ entity_id: polymorphicIdColumn(), // any entity, raw on read
182
188
  });
183
- ```
184
189
 
185
- Drizzle runs `toDriver` on WHERE values (`eq`, `inArray`) as well as insert/update
186
- `SET`, and `dataType` stays `uuid` — so there is **no DDL and no migration**, and
187
- `drizzle-kit generate` reports no diff. There is deliberately no `fromDriver`
188
- (see the encode asymmetry above).
190
+ const [row] = await db.select().from(invoices).where(eq(invoices.id, "inv_…"));
191
+ row.id; // "inv_…" — encoded on read
192
+ row.account_id; // "acct_…"
193
+ ```
189
194
 
190
- Raw SQL and RPC args bypass the column layer, so bind those with `sqlUuid(id)` /
191
- `sqlUuidArray(ids)` rather than a bare `${id}::uuid`.
195
+ - `toDriver` runs on insert/update `SET` values **and** WHERE values (`eq`,
196
+ `inArray`, …) and decodes the public id; a raw uuid (a database default,
197
+ Better Auth's `generateId`) passes through.
198
+ - `fromDriver` runs on every selected value (`select`, `returning()`, the
199
+ relational `db.query`) and encodes it.
200
+ - `dataType` stays `uuid`, so there is **no DDL and no migration** and
201
+ `drizzle-kit generate` reports no diff.
202
+ - The column is typed `string`, not `Id<E>`: Drizzle has one type for both
203
+ directions and the write side accepts a raw uuid, so a branded type would
204
+ reject every database- or client-minted uuid at the insert. The read side is
205
+ a public id at runtime; brand it where it leaves the data layer
206
+ (`ids.invoice.is()`, a typed response schema).
207
+
208
+ `polymorphicIdColumn` (an `entity_id` whose target is named by a sibling
209
+ `*_type` column) decodes any registered entity's id on the way in, but reads
210
+ stay raw: a column cannot see its sibling to know which prefix to put back.
211
+ Encode it in the query once the type is known — `encodedId("account",
212
+ invoices.entity_id)` — or with `entityOf` in code.
213
+
214
+ Raw SQL bypasses the column layer. Bind an incoming id with `sqlUuid(id)` /
215
+ `sqlUuidArray(ids)` (decoded in JS, nothing needed in the database), and select
216
+ a uuid as a public id with `encodedId(entity, column)` — which emits
217
+ `id758_encode(…)` and therefore needs the functions below.
192
218
 
193
219
  This subpath pulls only `drizzle-orm` and the codec — never `pg` — because it is
194
220
  imported by `schema.ts`.
195
221
 
222
+ ### The codec in Postgres (`@ingram-tech/nk-db/id/sql`)
223
+
224
+ `id758` ships the codec as plain plpgsql (`IMMUTABLE STRICT PARALLEL SAFE`, no
225
+ extensions, Postgres 14+), so the database itself accepts and produces either
226
+ form — in `psql`, in `createQueries` raw SQL, in an RPC, in an RLS policy:
227
+
228
+ ```sql
229
+ select * from invoices where id = id758_decode('inv_1CGtMb233ezidDvSwDLNBn');
230
+ select id758_encode('inv', id) as id, total from invoices;
231
+ create policy … using (account_id = id758_decode(auth.uid()));
232
+ ```
233
+
234
+ `id758_decode(id)` validates the shape and accepts any prefix; `id758_decode(id,
235
+ prefix)` also requires that prefix; `id758_prefix(id)` names it. An immutable
236
+ call on a bound literal is folded at plan time, so `where id =
237
+ id758_decode($1)` uses the ordinary primary-key index.
238
+
239
+ The functions are text, not a migration chain: the codec is frozen, so there is
240
+ never a second version to journal, and the script is `create or replace`. The
241
+ PGlite harness installs them on every boot (`id758: false` opts out), so dev and
242
+ test have them for free. Production gets them once, through the site's own
243
+ migrations:
244
+
245
+ ```sh
246
+ bunx drizzle-kit generate --custom --name id758
247
+ ```
248
+
249
+ and paste `id758Migration` (from `@ingram-tech/nk-db/id/sql`, the statements
250
+ joined by `--> statement-breakpoint`) into the generated file. Or, outside any
251
+ journal: `bunx id758 sql | psql "$DATABASE_URL"`. The `id758` bin also converts
252
+ at the shell — `bunx id758 decode inv_…` — for the moments a `psql` session
253
+ without the functions hands you the other form.
254
+
196
255
  ## PGlite dev & test (`@ingram-tech/nk-db/pglite`)
197
256
 
198
257
  `nk dev` runs the `nk-pglite-dev` bin automatically when this package is
@@ -1,6 +1,6 @@
1
- import { type SQL } from "drizzle-orm";
1
+ import { type AnyColumn, type SQL } from "drizzle-orm";
2
2
  import { customType } from "drizzle-orm/pg-core";
3
- import { type IdHelper } from "./id.js";
3
+ import { type Id, type IdHelper } from "./id.js";
4
4
  /**
5
5
  * Drizzle bindings for the id codec (`@ingram-tech/nk-db/id/drizzle`).
6
6
  *
@@ -8,47 +8,67 @@ import { type IdHelper } from "./id.js";
8
8
  * site's `schema.ts`, so it pulls only `drizzle-orm` and the (isomorphic) codec
9
9
  * — never `pg`, the pool, or the RLS helpers that the root export carries.
10
10
  *
11
- * The problem it solves: when a site stores raw `uuid` but exposes prefixed
12
- * public ids (`inv_…`), any id that reaches a query still skinned blows up with
13
- * `invalid input syntax for type uuid`. Rather than decoding at every call site
14
- * and hoping none are missed, decode once at the column.
11
+ * The invariant these bindings hold: **application code only ever sees public
12
+ * ids**. A column declared with `idColumn` decodes a public id to its raw uuid
13
+ * on the way *into* Postgres and encodes the uuid on the way *out*, so a row
14
+ * read through Drizzle carries `inv_…`, a `where eq(invoices.id, "inv_…")`
15
+ * just works, and nothing above the schema converts by hand. Raw SQL crosses
16
+ * the same boundary with `id758_encode` / `id758_decode` in the query (see
17
+ * `@ingram-tech/nk-db/id/sql`) or with {@link IdColumnBindings.encodedId} /
18
+ * {@link IdColumnBindings.sqlUuid} here.
15
19
  */
16
20
  type IdColumnBindings<K extends string> = {
17
21
  /**
18
- * A `uuid` column that decodes a public, prefixed id to its raw uuid *before*
19
- * the value reaches Postgres.
22
+ * A `uuid` column that speaks public ids.
20
23
  *
21
- * Drizzle runs `toDriver` on every JS→driver value: insert/update `SET`
22
- * values **and** WHERE-clause comparison values (`eq`, `inArray`, …), so
23
- * `eq(invoices.id, "inv_…")` is decoded transparently and feeding a skinned id
24
- * into a typed query stops being a failure mode.
24
+ * - `toDriver` (insert/update `SET` values **and** WHERE-clause comparison
25
+ * values: `eq`, `inArray`, …) decodes the public id to its uuid. Tolerant:
26
+ * a raw uuid passes through unchanged, so a value minted by the database
27
+ * or by Better Auth's `generateId` still inserts.
28
+ * - `fromDriver` (every selected value, including `returning()` and the
29
+ * relational `db.query`) encodes the uuid, so a read yields `inv_…`.
30
+ *
31
+ * Typed `string`, not `Id<E>`: Drizzle's `customType` has one `data` type
32
+ * for both directions, and the write side genuinely accepts a raw uuid, so
33
+ * a branded read type would make every database-minted or client-minted
34
+ * uuid a type error at the insert. The read-side guarantee is a runtime one
35
+ * (a selected value is always the public id); brand it at the seam where
36
+ * it leaves the data layer (`ids.x.is()`, or a typed response schema).
25
37
  *
26
38
  * `dataType` is unchanged (`uuid`), so this is a TypeScript-only mapping: no
27
39
  * DDL, no migration, and `drizzle-kit generate` reports no schema diff.
28
- *
29
- * Decode is tolerant — a raw uuid or a non-id sentinel passes through, so
30
- * adopting it never regresses a working call site. There is intentionally no
31
- * `fromDriver`: reads stay raw uuids. Encoding is the caller's job, because
32
- * (unlike decode) it cannot be inferred from the value — see `entityOf`.
33
40
  */
34
- idColumn: (entity: K) => ReturnType<typeof customType<IdColumnConfig>>;
41
+ idColumn: (entity: K) => ReturnType<typeof customType<IdColumnConfig<string>>>;
35
42
  /**
36
43
  * A `uuid` column for a **polymorphic** FK — an `entity_id` whose target is
37
- * named by a sibling `*_type` column — where no single-entity decoder applies.
38
- * Decodes a prefixed id of any entity in the registry (ids are
39
- * self-describing).
44
+ * named by a sibling `*_type` column — where no single-entity codec applies.
45
+ * Decodes a public id of any entity in the registry (ids are
46
+ * self-describing) on the way in; reads stay raw uuids, because a column
47
+ * cannot see its sibling to know which prefix to put back. Encode such a
48
+ * value in the query with {@link IdColumnBindings.encodedId} once the type
49
+ * is known, or with `entityOf` in code.
40
50
  *
41
- * A column cannot see its sibling, so this accepts an id of the *wrong*
42
- * entity. Where both halves are in hand, check them (`entityOf(registry, id)
43
- * === expectedType`) before writing, or the row is silently mislabelled.
51
+ * The same blindness means it accepts an id of the *wrong* entity. Where
52
+ * both halves are in hand, check them (`entityOf(registry, id) ===
53
+ * expectedType`) before writing, or the row is silently mislabelled.
54
+ */
55
+ polymorphicIdColumn: ReturnType<typeof customType<IdColumnConfig<string>>>;
56
+ /**
57
+ * A raw-SQL selection of a uuid column or expression as the entity's public
58
+ * id, for the queries the column layer cannot reach (a `sql` select, an
59
+ * aggregate, a polymorphic column whose type this row has resolved):
60
+ * `db.select({ id: encodedId("invoice", invoices.id) })`. Emits
61
+ * `id758_encode('inv', …)`, so the database must have the functions
62
+ * (`@ingram-tech/nk-db/id/sql`).
44
63
  */
45
- polymorphicIdColumn: ReturnType<typeof customType<IdColumnConfig>>;
64
+ encodedId: <E extends K>(entity: E, column: AnyColumn | SQL) => SQL<Id<E>>;
46
65
  /**
47
66
  * Bind an id into raw SQL as a `uuid`. Raw SQL and RPC args bypass the column
48
67
  * layer entirely, so this is the sanctioned binding for them:
49
68
  * `sql\`select f(${sqlUuid(id)})\``. Needs no entity because ids are
50
- * self-describing; a raw uuid (the common case) passes through, and
51
- * null/undefined binds as `null::uuid`.
69
+ * self-describing; a raw uuid passes through, and null/undefined binds as
70
+ * `null::uuid`. Decodes in JS, so it needs nothing installed in the
71
+ * database — the SQL-side alternative is `id758_decode(${id})`.
52
72
  */
53
73
  sqlUuid: (value: string | null | undefined) => SQL;
54
74
  /**
@@ -58,8 +78,8 @@ type IdColumnBindings<K extends string> = {
58
78
  */
59
79
  sqlUuidArray: (values: readonly string[]) => SQL;
60
80
  };
61
- type IdColumnConfig = {
62
- data: string;
81
+ type IdColumnConfig<TData extends string> = {
82
+ data: TData;
63
83
  driverData: string;
64
84
  };
65
85
  /**
@@ -68,11 +88,12 @@ type IdColumnConfig = {
68
88
  * ```ts
69
89
  * // ids.ts
70
90
  * export const ids = createIdRegistry({ invoice: "inv", account: "acct" });
71
- * export const { idColumn, polymorphicIdColumn, sqlUuid } = createIdColumns(ids);
91
+ * export const { idColumn, polymorphicIdColumn, encodedId, sqlUuid } =
92
+ * createIdColumns(ids);
72
93
  *
73
94
  * // schema.ts
74
95
  * export const invoices = pgTable("invoices", {
75
- * id: idColumn("invoice")().primaryKey(),
96
+ * id: idColumn("invoice")().primaryKey(), // "inv_…" in and out
76
97
  * account_id: idColumn("account")().notNull(),
77
98
  * });
78
99
  * ```
@@ -1 +1 @@
1
- {"version":3,"file":"id-drizzle.d.ts","sourceRoot":"","sources":["../src/id-drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAO,KAAK,GAAG,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAe,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAC;AAErD;;;;;;;;;;;GAWG;AAEH,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,IAAI;IACzC;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,UAAU,CAAC,OAAO,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC;IACvE;;;;;;;;;OASG;IACH,mBAAmB,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC;IACnE;;;;;;OAMG;IACH,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,KAAK,GAAG,CAAC;IACnD;;;;OAIG;IACH,YAAY,EAAE,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,KAAK,GAAG,CAAC;CACjD,CAAC;AAEF,KAAK,cAAc,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC;AAE3D;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,EAC/C,QAAQ,EAAE,MAAM,CAAC,CAAC,E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eAAe,CAAC,CAAC,SAAS,MAAM,EAC/C,QAAQ,EAAE,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,GAC3B,gBAAgB,CAAC,CAAC,CAAC,CA6BrB"}
@@ -7,11 +7,12 @@ import { decodeAnyId } from "./id.js";
7
7
  * ```ts
8
8
  * // ids.ts
9
9
  * export const ids = createIdRegistry({ invoice: "inv", account: "acct" });
10
- * export const { idColumn, polymorphicIdColumn, sqlUuid } = createIdColumns(ids);
10
+ * export const { idColumn, polymorphicIdColumn, encodedId, sqlUuid } =
11
+ * createIdColumns(ids);
11
12
  *
12
13
  * // schema.ts
13
14
  * export const invoices = pgTable("invoices", {
14
- * id: idColumn("invoice")().primaryKey(),
15
+ * id: idColumn("invoice")().primaryKey(), // "inv_…" in and out
15
16
  * account_id: idColumn("account")().notNull(),
16
17
  * });
17
18
  * ```
@@ -25,11 +26,13 @@ export function createIdColumns(registry) {
25
26
  toDriver: (value) => typeof value === "string"
26
27
  ? (registry[entity].decodeOrNull(value) ?? value)
27
28
  : value,
29
+ fromDriver: (value) => registry[entity].encode(value),
28
30
  }),
29
31
  polymorphicIdColumn: customType({
30
32
  dataType: () => "uuid",
31
33
  toDriver: (value) => (typeof value === "string" ? decodeAny(value) : value),
32
34
  }),
35
+ encodedId: (entity, column) => sql `id758_encode(${registry[entity].prefix}, ${column})`,
33
36
  sqlUuid,
34
37
  sqlUuidArray: (values) => sql `array[${sql.join(values.map((value) => sqlUuid(value)), sql `, `)}]::uuid[]`,
35
38
  };
@@ -1 +1 @@
1
- {"version":3,"file":"id-drizzle.js","sourceRoot":"","sources":["../src/id-drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAiB,MAAM,SAAS,CAAC;AA+DrD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAC9B,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AChE,OAAO;QACP,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE,CACxB,GAAG,CAAA,SAAS,GAAG,CAAC,IAAI,CACnB,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EACrC,GAAG,CAAA,IAAI,CACP,WAAW;KACb,CAAC;AACH,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { ID758_SQL, ID758_SQL_STATEMENTS } from "id758/sql";
2
+ /**
3
+ * The functions as the body of a Drizzle migration file: one statement per
4
+ * `--> statement-breakpoint`, which the migrator needs to run a multi-statement
5
+ * file (it sends each chunk as its own query).
6
+ */
7
+ export declare const id758Migration: string;
8
+ //# sourceMappingURL=id-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id-sql.d.ts","sourceRoot":"","sources":["../src/id-sql.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAE5D;;;;GAIG;AACH,eAAO,MAAM,cAAc,QAAmE,CAAC"}
package/dist/id-sql.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `@ingram-tech/nk-db/id/sql` — the id codec as Postgres functions, from
3
+ * `id758/sql`, plus the form a site pastes into a Drizzle migration.
4
+ *
5
+ * The functions (`id758_encode`, `id758_decode`, `id758_prefix`) let the
6
+ * database speak both forms of an id, so raw SQL, `psql` and RPCs need no
7
+ * conversion in application code:
8
+ *
9
+ * select * from invoices where id = id758_decode('inv_…');
10
+ * select id758_encode('inv', id) as id from invoices;
11
+ *
12
+ * They ship as text, not as a migration chain: the codec is frozen, so there
13
+ * is never a second version to journal, and the script is `create or replace`
14
+ * (idempotent). The PGlite harness applies it on every boot, so dev and test
15
+ * have the functions for free; production gets them once, through the site's
16
+ * own migrations:
17
+ *
18
+ * bunx drizzle-kit generate --custom --name id758
19
+ * # paste `id758Migration` into the generated drizzle/NNNN_id758.sql
20
+ *
21
+ * Or on the fly, outside any journal: `bunx id758 sql | psql "$DATABASE_URL"`.
22
+ */
23
+ import { ID758_SQL_STATEMENTS } from "id758/sql";
24
+ export { ID758_SQL, ID758_SQL_STATEMENTS } from "id758/sql";
25
+ /**
26
+ * The functions as the body of a Drizzle migration file: one statement per
27
+ * `--> statement-breakpoint`, which the migrator needs to run a multi-statement
28
+ * file (it sends each chunk as its own query).
29
+ */
30
+ export const id758Migration = `${ID758_SQL_STATEMENTS.join("\n--> statement-breakpoint\n")}\n`;
31
+ //# sourceMappingURL=id-sql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id-sql.js","sourceRoot":"","sources":["../src/id-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAE5D;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,oBAAoB,CAAC,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC"}
@@ -31,6 +31,14 @@ export interface PgliteServerOptions {
31
31
  /** Journal table schema. Default `drizzle`. */
32
32
  schema?: string;
33
33
  }>;
34
+ /**
35
+ * Install the id codec's Postgres functions (`id758_encode` / `id758_decode`,
36
+ * see `@ingram-tech/nk-db/id/sql`) before any migration runs. Default `true`:
37
+ * the script is idempotent and costs nothing, and having it in dev/test means
38
+ * a query can use the functions before — or without — the site journaling
39
+ * them. Set `false` to boot exactly what the migrations declare.
40
+ */
41
+ id758?: boolean;
34
42
  /** Override how the primary `migrationsFolder` is applied (e.g. raw-SQL apps).
35
43
  * `dependencyMigrations` still run first, before this. */
36
44
  migrate?: (db: PGlite) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,MAAM,EAA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KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;CACxB;AAED,MAAM,WAAW,YAAY;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,kBAAkB,CAAC;IAC3B,wDAAwD;IACxD,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AA2CD;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,aACrB,mBAAmB,KAC1B,OAAO,CAAC,YAAY,CAoCtB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,aACjB,mBAAmB,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,KACpD,OAAO,CAAC,IAAI,CAgCd,CAAC;AAEF,MAAM,WAAW,MAAM;IACtB,2EAA2E;IAC3E,IAAI,EAAE,IAAI,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,iEAAiE;IACjE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,4DAA4D;IAC5D,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,YAAY,aACf,mBAAmB,KAC1B,OAAO,CAAC,MAAM,CAiBhB,CAAC"}
@@ -12,6 +12,7 @@ import { rm } from "node:fs/promises";
12
12
  import { createServer } from "node:net";
13
13
  import { PGlite } from "@electric-sql/pglite";
14
14
  import { PGLiteSocketServer } from "@electric-sql/pglite-socket";
15
+ import { ID758_SQL } from "id758/sql";
15
16
  import { resetPublicTables } from "./reset.js";
16
17
  /** Ask the OS for a currently-free TCP port (bind :0, read it back, release).
17
18
  * Used so the test harness never collides with a dev Postgres on 5432. */
@@ -74,6 +75,8 @@ export const createPgliteServer = async (options = {}) => {
74
75
  // until a --fresh wipe). A custom `migrate` must be idempotent the same way.
75
76
  // Dependency chains (e.g. nk-auth's tables) go first so the app's own
76
77
  // migrations can reference them by FK.
78
+ if (options.id758 !== false)
79
+ await db.exec(ID758_SQL);
77
80
  await applyDependencyMigrations(db, options.dependencyMigrations ?? []);
78
81
  await (options.migrate ?? defaultMigrate(migrationsFolder))(db);
79
82
  const server = new PGLiteSocketServer({ db, host, port });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,iFAAiF;AACjF,sBAAsB;AACtB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,2CAA2C;AAE3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,MAAM,EAAmB,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAoD/C;2EAC2E;AAC3E,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAmB,EAAE,CAClD,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAC/B,MAAM,GAAG,GAAG,YAAY,EAAE,CAAC;IAC3B,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC1B,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC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AAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC5C,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ingram-tech/nk-db",
3
- "version": "1.6.0",
3
+ "version": "2.0.1",
4
4
  "description": "The Ingram Postgres data layer: one TLS-aware pg pool, raw-SQL helpers, Drizzle wiring, and a PGlite (no-Docker) dev/test harness for Next.js sites.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,7 +13,10 @@
13
13
  "access": "public"
14
14
  },
15
15
  "files": [
16
- "dist"
16
+ "dist",
17
+ "src",
18
+ "!src/**/*.test.ts",
19
+ "!src/**/*.test.tsx"
17
20
  ],
18
21
  "bin": {
19
22
  "nk-pglite-dev": "./dist/pglite/dev.js",
@@ -32,6 +35,10 @@
32
35
  "types": "./dist/id-drizzle.d.ts",
33
36
  "default": "./dist/id-drizzle.js"
34
37
  },
38
+ "./id/sql": {
39
+ "types": "./dist/id-sql.d.ts",
40
+ "default": "./dist/id-sql.js"
41
+ },
35
42
  "./migrate": {
36
43
  "types": "./dist/migrate.d.ts",
37
44
  "default": "./dist/migrate.js"
@@ -51,7 +58,7 @@
51
58
  "test": "vitest run"
52
59
  },
53
60
  "dependencies": {
54
- "id758": "^1.0.0",
61
+ "id758": "^1.1.0",
55
62
  "zod": "^4.4.3"
56
63
  },
57
64
  "peerDependencies": {
@@ -71,7 +78,7 @@
71
78
  "devDependencies": {
72
79
  "@electric-sql/pglite": "^0.5.5",
73
80
  "@electric-sql/pglite-socket": "^0.2.8",
74
- "@ingram-tech/nk-dev": "0.11.1",
81
+ "@ingram-tech/nk-dev": "0.12.1",
75
82
  "@types/node": "^26.2.0",
76
83
  "@types/pg": "^8.23.1",
77
84
  "drizzle-orm": "^0.45.2",
package/src/coerce.ts ADDED
@@ -0,0 +1,50 @@
1
+ // Coerce Postgres value representations back to the JS types app code expects.
2
+ //
3
+ // Why these exist: `pg` (and Drizzle on top of it) surfaces some columns in a
4
+ // form a strict response/validation schema rejects — `numeric` as a string (to
5
+ // avoid losing precision), and `timestamp(..., { mode: "string" })` as Postgres'
6
+ // own text form ("2026-06-21 18:22:08.331494+00", space separator, short
7
+ // offset). Neither satisfies a schema expecting `z.number()` / strict
8
+ // `z.iso.datetime()`.
9
+ //
10
+ // Use these at the read/response boundary when handing Drizzle/`pg` rows to such
11
+ // a schema. They are presentation coercions, not domain math — keep money
12
+ // arithmetic on the string/decimal value, and only convert for output.
13
+
14
+ /**
15
+ * Normalize a Postgres timestamp string to a strict ISO-8601 UTC string
16
+ * ("2026-06-21T18:22:08.331Z"), the form `z.iso.datetime()` (no offset) accepts.
17
+ *
18
+ * `Date` parses both Postgres' space-separated form and the `+00:00` offset
19
+ * form to the same instant, and `.toISOString()` emits the canonical `T…Z`.
20
+ * An offset-less value (a `timestamp` *without* time zone column) is treated
21
+ * as UTC — `new Date()` alone would read it in the server's local zone, so the
22
+ * same row would shift by host timezone. `null` passes through.
23
+ */
24
+ export function pgTimestampToIso(value: string): string;
25
+ export function pgTimestampToIso(value: null): null;
26
+ export function pgTimestampToIso(value: string | null): string | null;
27
+ export function pgTimestampToIso(value: string | null): string | null {
28
+ if (value === null) return null;
29
+ // Postgres text forms: "YYYY-MM-DD HH:MM:SS[.ffffff]" with an optional
30
+ // trailing offset like "+00", "+05:30" or "Z". A time with no offset gets
31
+ // UTC appended; a date-only value already parses as UTC per the Date spec.
32
+ const needsUtcMarker =
33
+ /\d{2}:\d{2}/.test(value) && !/(?:[+-]\d{2}(?::?\d{2})?|Z)$/i.test(value);
34
+ return new Date(needsUtcMarker ? `${value}Z` : value).toISOString();
35
+ }
36
+
37
+ /**
38
+ * Coerce a Postgres `numeric` value (which `pg`/Drizzle return as a string to
39
+ * preserve arbitrary precision) to a JS number, for schemas that expect
40
+ * `z.number()`. `null` passes through.
41
+ *
42
+ * Lossy for values outside `Number`'s safe range — only use at the response
43
+ * boundary, never for money math (keep that on the string/decimal value).
44
+ */
45
+ export function pgNumericToNumber(value: string): number;
46
+ export function pgNumericToNumber(value: null): null;
47
+ export function pgNumericToNumber(value: string | null): number | null;
48
+ export function pgNumericToNumber(value: string | null): number | null {
49
+ return value === null ? null : Number(value);
50
+ }
package/src/drizzle.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
3
+ import type { Pool } from "pg";
4
+ import { type RlsClaims, type RlsOptions, resolveRlsConfig } from "./rls.js";
5
+
6
+ /**
7
+ * Build the Drizzle instance on the shared pool. This is the default query path
8
+ * for app tables — schema-first, with `drizzle-kit` generating the migrations
9
+ * (kills the hand-written-SQL drift). It rides the same `pg.Pool` that backs the
10
+ * raw helpers and Better Auth, so there's still exactly one pool per process.
11
+ *
12
+ * import * as schema from "./schema";
13
+ * export const pool = createPool();
14
+ * export const db = createDb(pool, schema);
15
+ */
16
+ export const createDb = <TSchema extends Record<string, unknown>>(
17
+ pool: Pool,
18
+ schema: TSchema,
19
+ ): NodePgDatabase<TSchema> => drizzle(pool, { schema });
20
+
21
+ /** The transaction handle Drizzle hands its `db.transaction(fn)` callback. */
22
+ type DrizzleTx<TSchema extends Record<string, unknown>> = Parameters<
23
+ Parameters<NodePgDatabase<TSchema>["transaction"]>[0]
24
+ >[0];
25
+
26
+ /**
27
+ * Run `fn` inside a Drizzle transaction **scoped to a user**, so RLS policies
28
+ * apply on a direct connection. It sets `request.jwt.claims` +
29
+ * `SET LOCAL ROLE` (default `authenticated`) as the first statement, so existing
30
+ * `auth.uid()` policies fire unchanged; the `tx` passed to `fn` is a normal
31
+ * Drizzle transaction (full query builder + `tx.execute`). Use for user-facing
32
+ * reads/writes; use plain `db` for service-role paths. The connection role must
33
+ * not bypass RLS for the rows touched — see `rls.ts`.
34
+ *
35
+ * const notes = await withRlsTransaction(db, { sub: user.id }, (tx) =>
36
+ * tx.select().from(schema.notes),
37
+ * );
38
+ */
39
+ export const withRlsTransaction = <TSchema extends Record<string, unknown>, T>(
40
+ db: NodePgDatabase<TSchema>,
41
+ claims: RlsClaims,
42
+ fn: (tx: DrizzleTx<TSchema>) => Promise<T>,
43
+ options: RlsOptions = {},
44
+ ): Promise<T> =>
45
+ db.transaction(async (tx) => {
46
+ const { role, claimsSetting, claimsJson } = resolveRlsConfig(claims, options);
47
+ await tx.execute(
48
+ sql`select set_config(${claimsSetting}, ${claimsJson}, true), set_config('role', ${role}, true)`,
49
+ );
50
+ return fn(tx);
51
+ });
package/src/errors.ts ADDED
@@ -0,0 +1,35 @@
1
+ // Inspect Postgres driver errors by SQLSTATE without hand-rolling the `.cause`
2
+ // chain walk at every call site. `pg` puts the SQLSTATE on `error.code`, but
3
+ // wrappers (Drizzle, our own helpers) often re-throw with the original error
4
+ // nested under `.cause`, so a flat `err.code === …` check silently misses it.
5
+
6
+ /** SQLSTATE `23505` — `unique_violation`. */
7
+ export const PG_UNIQUE_VIOLATION = "23505";
8
+
9
+ /**
10
+ * True when `error`, or anything in its `.cause` chain, is a Postgres error
11
+ * whose SQLSTATE equals `code`.
12
+ *
13
+ * Prefer `INSERT … ON CONFLICT` over catch-and-branch where you can (it avoids
14
+ * the pooled-connection-destroy footgun — see `docs/db-package.md`), but use
15
+ * this for the cases that genuinely must inspect the failure.
16
+ */
17
+ export const isPgError = (error: unknown, code: string): boolean => {
18
+ let current: unknown = error;
19
+ // Depth cap: a cyclic `.cause` chain (err.cause = err) must not hang.
20
+ for (
21
+ let depth = 0;
22
+ depth < 32 && current !== null && current !== undefined;
23
+ depth++
24
+ ) {
25
+ if (typeof current === "object" && "code" in current && current.code === code) {
26
+ return true;
27
+ }
28
+ current = current instanceof Error ? current.cause : undefined;
29
+ }
30
+ return false;
31
+ };
32
+
33
+ /** Convenience for the most common check: a `23505` unique violation. */
34
+ export const isUniqueViolation = (error: unknown): boolean =>
35
+ isPgError(error, PG_UNIQUE_VIOLATION);