@ingram-tech/nk-db 1.5.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/README.md +81 -26
- package/dist/id-drizzle.d.ts +47 -31
- package/dist/id-drizzle.d.ts.map +1 -1
- package/dist/id-drizzle.js +5 -2
- package/dist/id-drizzle.js.map +1 -1
- package/dist/id-sql.d.ts +8 -0
- package/dist/id-sql.d.ts.map +1 -0
- package/dist/id-sql.js +31 -0
- package/dist/id-sql.js.map +1 -0
- package/dist/id.d.ts +18 -131
- package/dist/id.d.ts.map +1 -1
- package/dist/id.js +17 -200
- package/dist/id.js.map +1 -1
- package/dist/pglite/index.d.ts +8 -0
- package/dist/pglite/index.d.ts.map +1 -1
- package/dist/pglite/index.js +3 -0
- package/dist/pglite/index.js.map +1 -1
- package/package.json +16 -8
- package/src/coerce.ts +50 -0
- package/src/drizzle.ts +51 -0
- package/src/errors.ts +35 -0
- package/src/id-drizzle.ts +130 -0
- package/src/id-sql.ts +32 -0
- package/src/id.ts +21 -0
- package/src/index.ts +27 -0
- package/src/keys.ts +78 -0
- package/src/migrate-bin.ts +87 -0
- package/src/migrate.ts +454 -0
- package/src/pglite/dev.ts +63 -0
- package/src/pglite/index.ts +255 -0
- package/src/pglite/reset.ts +31 -0
- package/src/pool.ts +148 -0
- package/src/queries.ts +244 -0
- package/src/rls.ts +90 -0
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
|
+
});
|