@ingram-tech/nk-db 1.6.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.
@@ -0,0 +1,130 @@
1
+ import { type AnyColumn, sql, type SQL } from "drizzle-orm";
2
+ import { customType } from "drizzle-orm/pg-core";
3
+ import { decodeAnyId, type Id, type IdHelper } from "./id.js";
4
+
5
+ /**
6
+ * Drizzle bindings for the id codec (`@ingram-tech/nk-db/id/drizzle`).
7
+ *
8
+ * Deliberately a separate subpath from the package root: this is imported by a
9
+ * site's `schema.ts`, so it pulls only `drizzle-orm` and the (isomorphic) codec
10
+ * — never `pg`, the pool, or the RLS helpers that the root export carries.
11
+ *
12
+ * The invariant these bindings hold: **application code only ever sees public
13
+ * ids**. A column declared with `idColumn` decodes a public id to its raw uuid
14
+ * on the way *into* Postgres and encodes the uuid on the way *out*, so a row
15
+ * read through Drizzle carries `inv_…`, a `where eq(invoices.id, "inv_…")`
16
+ * just works, and nothing above the schema converts by hand. Raw SQL crosses
17
+ * the same boundary with `id758_encode` / `id758_decode` in the query (see
18
+ * `@ingram-tech/nk-db/id/sql`) or with {@link IdColumnBindings.encodedId} /
19
+ * {@link IdColumnBindings.sqlUuid} here.
20
+ */
21
+
22
+ type IdColumnBindings<K extends string> = {
23
+ /**
24
+ * A `uuid` column that speaks public ids. Its TypeScript type is the
25
+ * entity's branded `Id<E>`, so an invoice id can't be handed to an account
26
+ * column.
27
+ *
28
+ * - `toDriver` (insert/update `SET` values **and** WHERE-clause comparison
29
+ * values: `eq`, `inArray`, …) decodes the public id to its uuid. Tolerant:
30
+ * a raw uuid passes through unchanged, so a value minted by the database
31
+ * or by Better Auth's `generateId` still inserts.
32
+ * - `fromDriver` (every selected value, including `returning()` and the
33
+ * relational `db.query`) encodes the uuid, so a read yields `inv_…`.
34
+ *
35
+ * `dataType` is unchanged (`uuid`), so this is a TypeScript-only mapping: no
36
+ * DDL, no migration, and `drizzle-kit generate` reports no schema diff.
37
+ */
38
+ idColumn: <E extends K>(
39
+ entity: E,
40
+ ) => ReturnType<typeof customType<IdColumnConfig<Id<E>>>>;
41
+ /**
42
+ * A `uuid` column for a **polymorphic** FK — an `entity_id` whose target is
43
+ * named by a sibling `*_type` column — where no single-entity codec applies.
44
+ * Decodes a public id of any entity in the registry (ids are
45
+ * self-describing) on the way in; reads stay raw uuids, because a column
46
+ * cannot see its sibling to know which prefix to put back. Encode such a
47
+ * value in the query with {@link IdColumnBindings.encodedId} once the type
48
+ * is known, or with `entityOf` in code.
49
+ *
50
+ * The same blindness means it accepts an id of the *wrong* entity. Where
51
+ * both halves are in hand, check them (`entityOf(registry, id) ===
52
+ * expectedType`) before writing, or the row is silently mislabelled.
53
+ */
54
+ polymorphicIdColumn: ReturnType<typeof customType<IdColumnConfig<string>>>;
55
+ /**
56
+ * A raw-SQL selection of a uuid column or expression as the entity's public
57
+ * id, for the queries the column layer cannot reach (a `sql` select, an
58
+ * aggregate, a polymorphic column whose type this row has resolved):
59
+ * `db.select({ id: encodedId("invoice", invoices.id) })`. Emits
60
+ * `id758_encode('inv', …)`, so the database must have the functions
61
+ * (`@ingram-tech/nk-db/id/sql`).
62
+ */
63
+ encodedId: <E extends K>(entity: E, column: AnyColumn | SQL) => SQL<Id<E>>;
64
+ /**
65
+ * Bind an id into raw SQL as a `uuid`. Raw SQL and RPC args bypass the column
66
+ * layer entirely, so this is the sanctioned binding for them:
67
+ * `sql\`select f(${sqlUuid(id)})\``. Needs no entity because ids are
68
+ * self-describing; a raw uuid passes through, and null/undefined binds as
69
+ * `null::uuid`. Decodes in JS, so it needs nothing installed in the
70
+ * database — the SQL-side alternative is `id758_decode(${id})`.
71
+ */
72
+ sqlUuid: (value: string | null | undefined) => SQL;
73
+ /**
74
+ * Bind a list of ids as a `uuid[]`, for RPCs taking a `uuid[]` arg. Built
75
+ * element-wise on purpose: pg binds a JS array as `text[]`, and
76
+ * `text[]::uuid[]` is not a legal direct cast (SQLSTATE 42846).
77
+ */
78
+ sqlUuidArray: (values: readonly string[]) => SQL;
79
+ };
80
+
81
+ type IdColumnConfig<TData extends string> = { data: TData; driverData: string };
82
+
83
+ /**
84
+ * Build the Drizzle id bindings for a site's registry:
85
+ *
86
+ * ```ts
87
+ * // ids.ts
88
+ * export const ids = createIdRegistry({ invoice: "inv", account: "acct" });
89
+ * export const { idColumn, polymorphicIdColumn, encodedId, sqlUuid } =
90
+ * createIdColumns(ids);
91
+ *
92
+ * // schema.ts
93
+ * export const invoices = pgTable("invoices", {
94
+ * id: idColumn("invoice")().primaryKey(), // Id<"invoice">, "inv_…" in and out
95
+ * account_id: idColumn("account")().notNull(),
96
+ * });
97
+ * ```
98
+ */
99
+ export function createIdColumns<K extends string>(
100
+ registry: Record<K, IdHelper>,
101
+ ): IdColumnBindings<K> {
102
+ const decodeAny = (value: string) => decodeAnyId(registry, value);
103
+
104
+ const sqlUuid = (value: string | null | undefined): SQL =>
105
+ sql`${value == null ? null : decodeAny(value)}::uuid`;
106
+
107
+ return {
108
+ idColumn: <E extends K>(entity: E) =>
109
+ customType<IdColumnConfig<Id<E>>>({
110
+ dataType: () => "uuid",
111
+ toDriver: (value) =>
112
+ typeof value === "string"
113
+ ? (registry[entity].decodeOrNull(value) ?? value)
114
+ : value,
115
+ fromDriver: (value) => registry[entity].encode(value) as Id<E>,
116
+ }),
117
+ polymorphicIdColumn: customType<IdColumnConfig<string>>({
118
+ dataType: () => "uuid",
119
+ toDriver: (value) => (typeof value === "string" ? decodeAny(value) : value),
120
+ }),
121
+ encodedId: <E extends K>(entity: E, column: AnyColumn | SQL) =>
122
+ sql<Id<E>>`id758_encode(${registry[entity].prefix}, ${column})`,
123
+ sqlUuid,
124
+ sqlUuidArray: (values) =>
125
+ sql`array[${sql.join(
126
+ values.map((value) => sqlUuid(value)),
127
+ sql`, `,
128
+ )}]::uuid[]`,
129
+ };
130
+ }
package/src/id-sql.ts ADDED
@@ -0,0 +1,32 @@
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
+
25
+ export { ID758_SQL, ID758_SQL_STATEMENTS } from "id758/sql";
26
+
27
+ /**
28
+ * The functions as the body of a Drizzle migration file: one statement per
29
+ * `--> statement-breakpoint`, which the migrator needs to run a multi-statement
30
+ * file (it sends each chunk as its own query).
31
+ */
32
+ export const id758Migration = `${ID758_SQL_STATEMENTS.join("\n--> statement-breakpoint\n")}\n`;
package/src/id.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `@ingram-tech/nk-db/id` — the fleet's id codec, now published standalone as
3
+ * [`id758`](https://github.com/ingram-technologies/id758). This subpath stays
4
+ * as the nextkit-facing entry point: it re-exports the whole `id758` surface
5
+ * plus the names nextkit sites adopted before the extraction, so nothing that
6
+ * imports from here needs to change. New code may import `id758` directly.
7
+ *
8
+ * Like `id758` itself, this module must stay isomorphic (no node-only imports):
9
+ * it is pulled into Drizzle schemas, client components and edge runtimes.
10
+ */
11
+ export * from "id758";
12
+ import { decodeId, encodeId, mintId, uuidv7 } from "id758";
13
+
14
+ /** @deprecated Use `uuidv7` from `id758`. */
15
+ export const uuidGenerateId = uuidv7;
16
+ /** @deprecated Use `encodeId` from `id758`. */
17
+ export const toPrefixedId = encodeId;
18
+ /** @deprecated Use `decodeId` from `id758`. */
19
+ export const fromPrefixedId = decodeId;
20
+ /** @deprecated Use `mintId` from `id758`. */
21
+ export const base58Id = mintId;
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ // The Ingram Postgres data layer. The PGlite dev/test harness lives behind the
2
+ // "@ingram-tech/nk-db/pglite" subpath so its WASM/dev-only deps never reach a
3
+ // production bundle.
4
+
5
+ export { pgNumericToNumber, pgTimestampToIso } from "./coerce.js";
6
+ export { createDb, withRlsTransaction } from "./drizzle.js";
7
+ export { isPgError, isUniqueViolation, PG_UNIQUE_VIOLATION } from "./errors.js";
8
+ export { type DbEnv, dbEnv, getDatabaseUrl, isConfigured } from "./keys.js";
9
+ export { type CreatePoolConfig, createPool } from "./pool.js";
10
+ export {
11
+ createQueries,
12
+ parseMaybeRow,
13
+ parseOneRow,
14
+ parseRows,
15
+ type PoolQueries,
16
+ type Queries,
17
+ type RowsResult,
18
+ } from "./queries.js";
19
+ export {
20
+ RLS_CLAIMS_SETTING,
21
+ RLS_DEFAULT_ROLE,
22
+ type ResolvedRlsConfig,
23
+ type RlsClaims,
24
+ type RlsOptions,
25
+ resolveRlsConfig,
26
+ rlsPreamble,
27
+ } from "./rls.js";
package/src/keys.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Environment contract for @ingram-tech/nk-db.
3
+ *
4
+ * Following the "each package owns its own env validation" pattern (see
5
+ * @ingram-tech/nk-auth). Env vars are external input, so we parse them with Zod
6
+ * (per docs/code-style.md) rather than reading `process.env` ad hoc.
7
+ *
8
+ * The connection string comes from `DATABASE_URL` — our DO cluster, or the local
9
+ * PGlite socket in dev (see docs/db-package.md).
10
+ *
11
+ * Optional TLS / pool controls:
12
+ * DATABASE_SSL — booleanish flag; only "true" sets DbEnv.ssl, but other
13
+ * libpq values (disable/require/…) are tolerated, not rejected
14
+ * DATABASE_CA_CERT — PEM CA; when set, verify the server cert + hostname
15
+ * DATABASE_POOL_MAX — pool size cap; keep small on serverless (e.g. 5)
16
+ */
17
+
18
+ import { z } from "zod";
19
+
20
+ const schema = z.object({
21
+ DATABASE_URL: z.string().min(1).optional(),
22
+ // Booleanish, but tolerant: only "true" flips DbEnv.ssl, yet libpq-style
23
+ // values (disable/require/prefer/…) are accepted rather than throwing —
24
+ // createPool decides TLS from the CA cert + host, never from this flag.
25
+ DATABASE_SSL: z.string().optional(),
26
+ DATABASE_CA_CERT: z.string().min(1).optional(),
27
+ DATABASE_POOL_MAX: z.coerce.number().int().positive().optional(),
28
+ });
29
+
30
+ export interface DbEnv {
31
+ /** The resolved connection string (precedence applied). */
32
+ connectionString: string;
33
+ /** PEM CA cert; when set, the pool verifies the server cert + hostname. */
34
+ caCert?: string;
35
+ /** Whether TLS was explicitly requested via DATABASE_SSL. */
36
+ ssl: boolean;
37
+ /** Pool size cap, if configured. */
38
+ poolMax?: number;
39
+ }
40
+
41
+ /**
42
+ * Resolve the connection string from the environment, without validating the
43
+ * rest of the contract. Returns `undefined` if unset — useful for "is a database
44
+ * configured?" checks (e.g. degrade in local dev).
45
+ */
46
+ export const getDatabaseUrl = (
47
+ env: NodeJS.ProcessEnv = process.env,
48
+ ): string | undefined => env.DATABASE_URL;
49
+
50
+ /**
51
+ * Read and validate the nk-db env vars at once. Throws a single error listing
52
+ * everything missing/invalid so a misconfigured site fails fast at startup
53
+ * rather than at first query.
54
+ */
55
+ export const dbEnv = (): DbEnv => {
56
+ const result = schema.safeParse(process.env);
57
+ if (!result.success) {
58
+ const issues = result.error.issues
59
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
60
+ .join(", ");
61
+ throw new Error(`@ingram-tech/nk-db: invalid environment — ${issues}`);
62
+ }
63
+ const connectionString = getDatabaseUrl();
64
+ if (!connectionString) {
65
+ throw new Error(
66
+ "@ingram-tech/nk-db: no database connection string — set DATABASE_URL.",
67
+ );
68
+ }
69
+ return {
70
+ connectionString,
71
+ caCert: result.data.DATABASE_CA_CERT,
72
+ ssl: result.data.DATABASE_SSL === "true",
73
+ poolMax: result.data.DATABASE_POOL_MAX,
74
+ };
75
+ };
76
+
77
+ /** Whether a database connection string is present (degrade gracefully if not). */
78
+ export const isConfigured = (): boolean => getDatabaseUrl() !== undefined;
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ // The `nk-pg-migrate` bin — a drop-in replacement for `drizzle-kit migrate` in a
3
+ // site's `db:migrate` script. Unlike drizzle-kit it surfaces the real Postgres
4
+ // error on failure (not an opaque exit 1), refuses to run against a drifted
5
+ // journal with an actionable message, and can reconcile a drifted-but-correct
6
+ // journal with `--baseline`.
7
+ //
8
+ // Connection comes from the env contract (DATABASE_URL [+ DATABASE_CA_CERT], or
9
+ // the nk-db `dbEnv()` vars). Run it via `bun run db:migrate` so the runner loads
10
+ // your `.env` / `.env.local` into the environment first.
11
+ //
12
+ // nk-pg-migrate apply pending migrations
13
+ // nk-pg-migrate --status print journal status, apply nothing
14
+ // nk-pg-migrate --baseline record the current file chain as applied,
15
+ // WITHOUT running DDL (push-built / regenerated
16
+ // baseline whose schema already matches)
17
+ // nk-pg-migrate --migrations <folder> (default: drizzle)
18
+ //
19
+ // Run directly by Node, so the relative import carries a `.js` extension.
20
+ import {
21
+ baselineMigrations,
22
+ inspectMigrations,
23
+ MigrationDriftError,
24
+ MigrationOrderError,
25
+ runMigrations,
26
+ } from "./migrate.js";
27
+
28
+ const argv = process.argv.slice(2);
29
+ const flag = (name: string): boolean => argv.includes(name);
30
+ const value = (name: string): string | undefined => {
31
+ const i = argv.indexOf(name);
32
+ const next = i >= 0 ? argv[i + 1] : undefined;
33
+ // `--migrations --status` must not eat the flag as its value (or silently
34
+ // fall back to the default on a trailing `--migrations`).
35
+ if (i >= 0 && (next === undefined || next.startsWith("--"))) {
36
+ console.error(`nk-pg-migrate: ${name} requires a value`);
37
+ process.exit(1);
38
+ }
39
+ return next;
40
+ };
41
+
42
+ const migrationsFolder =
43
+ value("--migrations") ?? value("--migrations-folder") ?? "drizzle";
44
+
45
+ const main = async (): Promise<void> => {
46
+ if (flag("--status")) {
47
+ const s = await inspectMigrations({ migrationsFolder });
48
+ console.log(
49
+ `nk-pg-migrate: ${s.files.length} file(s), ${s.recorded.length} recorded, ${s.pending.length} pending${s.drifted ? " — DRIFTED" : ""}`,
50
+ );
51
+ if (s.drift) console.log(` drift: ${s.drift.reason}`);
52
+ if (s.pending.length)
53
+ console.log(` pending: ${s.pending.map((m) => m.tag).join(", ")}`);
54
+ if (s.unreachable.length) {
55
+ console.log(
56
+ ` UNREACHABLE (the migrator would skip these silently): ${s.unreachable.map((m) => m.tag).join(", ")}`,
57
+ );
58
+ }
59
+ if (s.journalIssues.length)
60
+ console.log(` journal: ${s.journalIssues.join("; ")}`);
61
+ return;
62
+ }
63
+
64
+ if (flag("--baseline")) {
65
+ const { recorded } = await baselineMigrations({ migrationsFolder });
66
+ console.log(
67
+ `nk-pg-migrate: baselined journal to ${recorded.length} migration(s) — recorded as applied, no DDL run.`,
68
+ );
69
+ return;
70
+ }
71
+
72
+ const { applied } = await runMigrations({ migrationsFolder });
73
+ console.log(
74
+ applied.length
75
+ ? `nk-pg-migrate: applied ${applied.length} migration(s) — ${applied.join(", ")}`
76
+ : "nk-pg-migrate: up to date, nothing to apply.",
77
+ );
78
+ };
79
+
80
+ main().catch((error: unknown) => {
81
+ if (error instanceof MigrationDriftError || error instanceof MigrationOrderError) {
82
+ console.error(`nk-pg-migrate: ${error.message}`);
83
+ process.exit(2);
84
+ }
85
+ console.error("nk-pg-migrate: migration failed —", error);
86
+ process.exit(1);
87
+ });