@homeflare/alchemy 0.23.0 → 0.24.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.
Files changed (95) hide show
  1. package/README.md +15 -1
  2. package/dist/litellm/client.d.ts +76 -0
  3. package/dist/litellm/client.d.ts.map +1 -0
  4. package/dist/litellm/credentials.d.ts +48 -0
  5. package/dist/litellm/credentials.d.ts.map +1 -0
  6. package/dist/litellm/fake-litellm.d.ts +36 -0
  7. package/dist/litellm/fake-litellm.d.ts.map +1 -0
  8. package/dist/litellm/fake-stack.d.ts +30 -0
  9. package/dist/litellm/fake-stack.d.ts.map +1 -0
  10. package/dist/litellm/generated/pass-through.d.ts +71 -0
  11. package/dist/litellm/generated/pass-through.d.ts.map +1 -0
  12. package/dist/litellm/index.d.ts +13 -0
  13. package/dist/litellm/index.d.ts.map +1 -0
  14. package/dist/litellm/index.js +270 -0
  15. package/dist/litellm/index.js.map +14 -0
  16. package/dist/litellm/pass-through-endpoint.d.ts +94 -0
  17. package/dist/litellm/pass-through-endpoint.d.ts.map +1 -0
  18. package/dist/litellm/pass-through-form.d.ts +40 -0
  19. package/dist/litellm/pass-through-form.d.ts.map +1 -0
  20. package/dist/litellm/providers.d.ts +16 -0
  21. package/dist/litellm/providers.d.ts.map +1 -0
  22. package/dist/postgres/connection.d.ts +50 -0
  23. package/dist/postgres/connection.d.ts.map +1 -0
  24. package/dist/postgres/database-attrs.d.ts +79 -0
  25. package/dist/postgres/database-attrs.d.ts.map +1 -0
  26. package/dist/postgres/database-sql.d.ts +73 -0
  27. package/dist/postgres/database-sql.d.ts.map +1 -0
  28. package/dist/postgres/database.d.ts +63 -0
  29. package/dist/postgres/database.d.ts.map +1 -0
  30. package/dist/postgres/errors.d.ts +86 -0
  31. package/dist/postgres/errors.d.ts.map +1 -0
  32. package/dist/postgres/fake-sql.d.ts +22 -0
  33. package/dist/postgres/fake-sql.d.ts.map +1 -0
  34. package/dist/postgres/index.d.ts +16 -0
  35. package/dist/postgres/index.d.ts.map +1 -0
  36. package/dist/postgres/index.js +238 -0
  37. package/dist/postgres/index.js.map +15 -0
  38. package/dist/postgres/providers.d.ts +14 -0
  39. package/dist/postgres/providers.d.ts.map +1 -0
  40. package/dist/proxmox/index.js.map +2 -2
  41. package/dist/proxmox/zfs-pool.d.ts +10 -2
  42. package/dist/proxmox/zfs-pool.d.ts.map +1 -1
  43. package/dist/release/archive.d.ts +6 -2
  44. package/dist/release/archive.d.ts.map +1 -1
  45. package/dist/release/binary-form.d.ts +14 -9
  46. package/dist/release/binary-form.d.ts.map +1 -1
  47. package/dist/release/binary-pins.d.ts +17 -0
  48. package/dist/release/binary-pins.d.ts.map +1 -0
  49. package/dist/release/catalog.d.ts.map +1 -1
  50. package/dist/release/index.js +90 -40
  51. package/dist/release/index.js.map +8 -7
  52. package/dist/release/tar.d.ts +9 -2
  53. package/dist/release/tar.d.ts.map +1 -1
  54. package/docs/litellm.md +110 -0
  55. package/docs/peers.md +8 -1
  56. package/docs/postgres.md +125 -0
  57. package/docs/release-binary-catalogs.md +40 -4
  58. package/docs/release-binary-refusals.md +22 -8
  59. package/docs/release-binary-upstream.md +33 -15
  60. package/package.json +10 -1
  61. package/src/litellm/client.ts +195 -0
  62. package/src/litellm/credentials.ts +73 -0
  63. package/src/litellm/fake-litellm.ts +114 -0
  64. package/src/litellm/fake-stack.ts +100 -0
  65. package/src/litellm/generated/pass-through.ts +73 -0
  66. package/src/litellm/index.ts +42 -0
  67. package/src/litellm/pass-through-endpoint-delete-swallow.test.ts +66 -0
  68. package/src/litellm/pass-through-endpoint-replace.test.ts +84 -0
  69. package/src/litellm/pass-through-endpoint.test.ts +208 -0
  70. package/src/litellm/pass-through-endpoint.ts +258 -0
  71. package/src/litellm/pass-through-form.test.ts +128 -0
  72. package/src/litellm/pass-through-form.ts +136 -0
  73. package/src/litellm/providers.ts +19 -0
  74. package/src/postgres/connection.ts +62 -0
  75. package/src/postgres/database-attrs.ts +87 -0
  76. package/src/postgres/database-bigint-serialization.test.ts +140 -0
  77. package/src/postgres/database-lifecycle.test.ts +113 -0
  78. package/src/postgres/database-provenance.test.ts +118 -0
  79. package/src/postgres/database-refusals.test.ts +135 -0
  80. package/src/postgres/database-sql.ts +174 -0
  81. package/src/postgres/database.ts +193 -0
  82. package/src/postgres/errors.ts +131 -0
  83. package/src/postgres/fake-sql.ts +123 -0
  84. package/src/postgres/fixtures/pg-REL_18_6-create-database-synopsis.txt +26 -0
  85. package/src/postgres/fixtures/pg-REL_18_6-pg_database.h.txt +67 -0
  86. package/src/postgres/index.ts +30 -0
  87. package/src/postgres/providers.ts +16 -0
  88. package/src/proxmox/zfs-pool.ts +10 -2
  89. package/src/release/archive.ts +10 -4
  90. package/src/release/binary-form.ts +24 -76
  91. package/src/release/binary-pins.ts +95 -0
  92. package/src/release/binary-root.test.ts +122 -0
  93. package/src/release/catalog.ts +10 -2
  94. package/src/release/tar-root.test.ts +114 -0
  95. package/src/release/tar.ts +78 -12
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Provenance: every `PostgresDatabaseProps` field traces to a real `CREATE DATABASE` synopsis
3
+ * option AND a real `pg_database` column, and every synopsis option this family does NOT expose
4
+ * as a prop is named with a reason. Both fixtures are parsed, not eyeballed — deleting a fixture
5
+ * line, or adding a prop with no mapping, fails this file (S38, the house's provenance rule).
6
+ */
7
+ import { describe, expect, test } from 'bun:test';
8
+ import { readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+
11
+ const FIXTURES = join(import.meta.dir, 'fixtures');
12
+ const synopsis = readFileSync(join(FIXTURES, 'pg-REL_18_6-create-database-synopsis.txt'), 'utf8');
13
+ const struct = readFileSync(join(FIXTURES, 'pg-REL_18_6-pg_database.h.txt'), 'utf8');
14
+
15
+ const SYNOPSIS_BLOB = '4da8aeebb50a29e89bd9f68a8deac4b1a3ec7b18';
16
+ const STRUCT_BLOB = '54f0d38c9c9e1cd4d419b05b296b8f84875e9768';
17
+
18
+ const synopsisOptions = (): readonly string[] => {
19
+ const re = /\[\s*([A-Z][A-Z_ ]*?)\s*(?:\[=\]|=)\s*<replaceable/g;
20
+ const found: string[] = [];
21
+ for (const m of synopsis.matchAll(re)) found.push(m[1] as string);
22
+ return found;
23
+ };
24
+
25
+ const structColumns = (): readonly string[] => {
26
+ const re = /^\t[A-Za-z_][A-Za-z0-9_]*\s+(\w+)(?:\[\d+\])?\b/;
27
+ const found: string[] = [];
28
+ for (const line of struct.split('\n')) {
29
+ const m = re.exec(line);
30
+ if (m !== null) found.push(m[1] as string);
31
+ }
32
+ return found;
33
+ };
34
+
35
+ /** Every asserted prop except `name`, which is the mandatory `CREATE DATABASE <name>` token, not
36
+ * a bracketed `WITH` option — checked separately below. */
37
+ const PROP_MAPPING: Readonly<Record<string, { readonly option: string; readonly column: string }>> =
38
+ {
39
+ owner: { option: 'OWNER', column: 'datdba' },
40
+ encoding: { option: 'ENCODING', column: 'encoding' },
41
+ localeProvider: { option: 'LOCALE_PROVIDER', column: 'datlocprovider' },
42
+ lcCollate: { option: 'LC_COLLATE', column: 'datcollate' },
43
+ lcCtype: { option: 'LC_CTYPE', column: 'datctype' },
44
+ allowConnections: { option: 'ALLOW_CONNECTIONS', column: 'datallowconn' },
45
+ connectionLimit: { option: 'CONNECTION LIMIT', column: 'datconnlimit' },
46
+ isTemplate: { option: 'IS_TEMPLATE', column: 'datistemplate' },
47
+ tablespace: { option: 'TABLESPACE', column: 'dattablespace' },
48
+ };
49
+
50
+ /** Every synopsis option this family does NOT declare as a prop, and why. */
51
+ const EXCLUDED: Readonly<Record<string, string>> = {
52
+ TEMPLATE: 'consumed only at create time to copy from; pg_database has no column recording it',
53
+ STRATEGY: 'consumed only at create time (WAL_LOG vs FILE_COPY copy method); not stored',
54
+ LOCALE:
55
+ 'a shorthand that sets LC_COLLATE/LC_CTYPE (or BUILTIN_LOCALE); this family declares lcCollate/lcCtype directly instead',
56
+ BUILTIN_LOCALE:
57
+ "only meaningful when localeProvider='builtin'; folds into datcollate/datctype like LOCALE, no column of its own",
58
+ ICU_LOCALE:
59
+ "only meaningful when localeProvider='icu' (datlocale column exists); deferred — measured 2026-09-23, all 24 live databases are locale provider 'c' (libc)",
60
+ ICU_RULES:
61
+ 'stored in daticurules, but this family has no ICU-provider consumer yet (see ICU_LOCALE)',
62
+ COLLATION_VERSION:
63
+ 'intended for pg_upgrade only; normally omitted so PostgreSQL computes it from the OS',
64
+ OID: 'primarily for pg_upgrade\'s internal use (docs: "only pg_upgrade can specify a value less than 16384"); not something a stack should assert',
65
+ };
66
+
67
+ describe('postgres provenance', () => {
68
+ test('fixture headers name the measured blob shas', () => {
69
+ expect(synopsis).toContain(SYNOPSIS_BLOB);
70
+ expect(synopsis).toContain('doc/src/sgml/ref/create_database.sgml');
71
+ expect(struct).toContain(STRUCT_BLOB);
72
+ expect(struct).toContain('src/include/catalog/pg_database.h');
73
+ });
74
+
75
+ test('the name token is documented and backed by datname', () => {
76
+ expect(synopsis).toContain('CREATE DATABASE <replaceable class="parameter">name</replaceable>');
77
+ expect(structColumns()).toContain('datname');
78
+ });
79
+
80
+ test('every declared prop maps to a real synopsis option', () => {
81
+ const options = synopsisOptions();
82
+ for (const [prop, { option }] of Object.entries(PROP_MAPPING)) {
83
+ expect(options, `prop "${prop}" claims synopsis option "${option}"`).toContain(option);
84
+ }
85
+ });
86
+
87
+ test('every declared prop maps to a real pg_database column', () => {
88
+ const columns = structColumns();
89
+ for (const [prop, { column }] of Object.entries(PROP_MAPPING)) {
90
+ expect(columns, `prop "${prop}" claims column "${column}"`).toContain(column);
91
+ }
92
+ });
93
+
94
+ test('every synopsis option is either a declared prop or a documented exclusion', () => {
95
+ const declaredOptions = new Set(Object.values(PROP_MAPPING).map((m) => m.option));
96
+ for (const option of synopsisOptions()) {
97
+ const accounted = declaredOptions.has(option) || option in EXCLUDED;
98
+ expect(accounted, `synopsis option "${option}" is neither a prop nor in EXCLUDED`).toBe(true);
99
+ }
100
+ });
101
+
102
+ test('no excluded option is silently also a declared prop', () => {
103
+ const declaredOptions = new Set(Object.values(PROP_MAPPING).map((m) => m.option));
104
+ for (const option of Object.keys(EXCLUDED)) {
105
+ expect(declaredOptions.has(option), `"${option}" is both excluded and declared`).toBe(false);
106
+ }
107
+ });
108
+
109
+ test('every excluded option actually exists in the synopsis (no stale entries)', () => {
110
+ const options = new Set(synopsisOptions());
111
+ for (const option of Object.keys(EXCLUDED)) {
112
+ expect(
113
+ options.has(option),
114
+ `EXCLUDED names "${option}", which the synopsis no longer has`,
115
+ ).toBe(true);
116
+ }
117
+ });
118
+ });
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Every plan-time refusal, checked without a client: name-byte precision, identifier and string
3
+ * quoting, the rename refusal, a full sweep proving `diff` never answers `replace`, and `delete`.
4
+ */
5
+ import { describe, expect, test } from 'bun:test';
6
+ import { readFileSync } from 'node:fs';
7
+ import * as Effect from 'effect/Effect';
8
+ import { POSTGRES_NAME_MAX_BYTES, nameByteRefusal, utf8ByteLength } from './database-attrs.ts';
9
+ import { buildCreateDatabaseSql, quoteIdent, quoteStringLiteral } from './database-sql.ts';
10
+ import { diffPostgresDatabase, postgresDatabaseHandlers } from './database.ts';
11
+ import { PostgresDatabaseDropRefused, PostgresDatabaseRenameRefused } from './errors.ts';
12
+ import type { PostgresDatabaseAttributes, PostgresDatabaseProps } from './database-attrs.ts';
13
+
14
+ describe('name byte length', () => {
15
+ test('a 63-byte ASCII name is accepted', () => {
16
+ const name = 'a'.repeat(63);
17
+ expect(utf8ByteLength(name)).toBe(63);
18
+ expect(nameByteRefusal(name)).toBeUndefined();
19
+ });
20
+
21
+ test('a 64-byte ASCII name is refused', () => {
22
+ const name = 'a'.repeat(64);
23
+ const refusal = nameByteRefusal(name);
24
+ expect(refusal).toEqual({ byteLength: 64, limit: POSTGRES_NAME_MAX_BYTES });
25
+ });
26
+
27
+ test('a 63-byte multibyte name (21 three-byte characters) is accepted, though .length is 21', () => {
28
+ // U+4E2D ("中") is 3 UTF-8 bytes. 21 * 3 = 63 bytes exactly — the last size that survives.
29
+ const name = '中'.repeat(21);
30
+ expect(name.length).toBe(21);
31
+ expect(utf8ByteLength(name)).toBe(63);
32
+ expect(nameByteRefusal(name)).toBeUndefined();
33
+ });
34
+
35
+ test('one more multibyte character (64 bytes) is refused', () => {
36
+ const name = `${'中'.repeat(21)}a`;
37
+ expect(utf8ByteLength(name)).toBe(64);
38
+ expect(nameByteRefusal(name)).toEqual({ byteLength: 64, limit: POSTGRES_NAME_MAX_BYTES });
39
+ });
40
+ });
41
+
42
+ describe('quoting', () => {
43
+ test('quoteIdent doubles an embedded double quote and leaves a hyphen alone', () => {
44
+ expect(quoteIdent('a"b-c')).toBe('"a""b-c"');
45
+ });
46
+
47
+ test('quoteIdent does not split a dot the way a qualified-name escaper would', () => {
48
+ // The hazard this file exists to avoid — see database-sql.ts's header.
49
+ expect(quoteIdent('my.app')).toBe('"my.app"');
50
+ });
51
+
52
+ test('quoteStringLiteral doubles an embedded single quote', () => {
53
+ expect(quoteStringLiteral("en_US.UTF-8'; DROP")).toBe("'en_US.UTF-8''; DROP'");
54
+ });
55
+
56
+ test('buildCreateDatabaseSql never string-concatenates an unescaped value', () => {
57
+ const sql = buildCreateDatabaseSql({ name: 'db"1', owner: 'ro"le', encoding: "UT'F8" });
58
+ expect(sql).toBe('CREATE DATABASE "db""1" WITH OWNER "ro""le" ENCODING \'UT\'\'F8\'');
59
+ });
60
+ });
61
+
62
+ const sampleOutput: PostgresDatabaseAttributes = {
63
+ name: 'widgets',
64
+ oid: 1,
65
+ owner: 'tim',
66
+ encoding: 'UTF8',
67
+ localeProvider: 'libc',
68
+ collate: 'C',
69
+ ctype: 'C',
70
+ allowConnections: true,
71
+ connectionLimit: -1,
72
+ isTemplate: false,
73
+ tablespace: 'pg_default',
74
+ };
75
+ const base: PostgresDatabaseProps = { name: 'widgets', owner: 'tim' };
76
+
77
+ describe('diff', () => {
78
+ const output = sampleOutput;
79
+
80
+ test('a rename is refused at plan, before reconcile ever runs', async () => {
81
+ const error = await Effect.runPromise(
82
+ Effect.flip(diffPostgresDatabase({ ...base, name: 'gadgets' }, output)),
83
+ );
84
+ expect(error).toBeInstanceOf(PostgresDatabaseRenameRefused);
85
+ });
86
+
87
+ test('an unchanged declaration answers noop', async () => {
88
+ const result = await Effect.runPromise(diffPostgresDatabase(base, output));
89
+ expect(result).toEqual({ action: 'noop' });
90
+ });
91
+
92
+ test('a change in any single prop answers update, and NEVER replace — swept across every prop', async () => {
93
+ const variants: ReadonlyArray<Partial<PostgresDatabaseProps>> = [
94
+ { owner: 'someone-else' },
95
+ { encoding: 'LATIN1' },
96
+ { localeProvider: 'icu' },
97
+ { lcCollate: 'en_US.UTF-8' },
98
+ { lcCtype: 'en_US.UTF-8' },
99
+ { allowConnections: false },
100
+ { connectionLimit: 5 },
101
+ { isTemplate: true },
102
+ { tablespace: 'fast_ssd' },
103
+ ];
104
+ for (const variant of variants) {
105
+ const result = await Effect.runPromise(diffPostgresDatabase({ ...base, ...variant }, output));
106
+ expect(result?.action, `variant ${JSON.stringify(variant)}`).toBe('update');
107
+ expect(result).not.toEqual({ action: 'replace' });
108
+ }
109
+ });
110
+ });
111
+
112
+ describe('delete', () => {
113
+ test('the real handler refuses with PostgresDatabaseDropRefused naming the database', async () => {
114
+ const error = await Effect.runPromise(
115
+ Effect.flip(
116
+ postgresDatabaseHandlers.delete({
117
+ id: 'x',
118
+ fqn: 'x',
119
+ instanceId: 'x',
120
+ olds: base,
121
+ output: sampleOutput,
122
+ session: undefined as never,
123
+ bindings: [] as never,
124
+ }),
125
+ ),
126
+ );
127
+ expect(error).toBeInstanceOf(PostgresDatabaseDropRefused);
128
+ expect((error as PostgresDatabaseDropRefused).database).toBe('widgets');
129
+ });
130
+
131
+ test('defaultRemovalPolicy is retain (declared alongside PostgresDatabase, checked in source)', () => {
132
+ const source = readFileSync(new URL('./database.ts', import.meta.url), 'utf8');
133
+ expect(source).toContain("defaultRemovalPolicy: 'retain'");
134
+ });
135
+ });
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The four statements `Postgres.Database` ever issues, and the quoting each one needs.
3
+ *
4
+ * ⛔ `CREATE DATABASE` TAKES NO BIND PARAMETERS FOR ANY OF ITS VALUES, INCLUDING `OWNER`.
5
+ * Measured at `gram.y@REL_18_6`: `CreatedbStmt: CREATE DATABASE name opt_with
6
+ * createdb_opt_list`, and every `createdb_opt_item` value is `NumericOnly`,
7
+ * `opt_boolean_or_string` or the bare keyword `DEFAULT` — none of those productions reaches
8
+ * `PARAM` (`$n`). `sql\`…\`` cannot help here; every free-form value in this statement is
9
+ * escaped by hand, once, in this file, and the assembled text runs through `.unsafe()`.
10
+ * ⚠️ THE DATABASE NAME AND EFFECT'S OWN `sql(value)` IDENTIFIER HELPER DO NOT MIX. `name` is a
11
+ * `ColId` (`gram.y@REL_18_6` line 17327), a single token — but `Statement.defaultEscape('"')`
12
+ * (what `sql(value)` compiles to) also rewrites every `.` in the value to `"."`, because it is
13
+ * built for a *qualified* name like `schema.table`. A database named `"my.app"` would come out
14
+ * as `"my"."app"` — two tokens where `CreatedbStmt` parses exactly one — a syntax error the
15
+ * engine would blame on this provider. `quoteIdent` below is the single-token form: it quotes
16
+ * and doubles embedded `"`, and nothing else.
17
+ * ★ EVERY OTHER `WITH` VALUE (`OWNER`, `TABLESPACE`, `ENCODING`, `LOCALE_PROVIDER`,
18
+ * `LC_COLLATE`, `LC_CTYPE`) IS A STRING LITERAL, NOT AN IDENTIFIER. Measured at the same tag:
19
+ * `createdb_opt_item`'s string branch is `opt_boolean_or_string → NonReservedWord_or_Sconst →
20
+ * NonReservedWord | Sconst`. A locale like `en_US.UTF-8` would hit the same dot-splitting
21
+ * `quoteIdent` avoids if it were identifier-quoted; a plain `Sconst` (`quoteStringLiteral`) has
22
+ * no such rule. This rests on `standard_conforming_strings = on` (the PG18 default, and
23
+ * measured live 2026-09-23 — `docs/postgres.md#measured`); the escaper only ever doubles `'`
24
+ * and never emits a backslash, so it never depends on which way that setting points.
25
+ */
26
+ import type { SqlError } from 'effect/unstable/sql/SqlError';
27
+ import * as Effect from 'effect/Effect';
28
+ import type { PostgresDatabaseAttributes, PostgresDatabaseProps } from './database-attrs.ts';
29
+
30
+ /** What every function in this file needs from a client — real (`PgClient.PgClient`) or fake
31
+ * (`fake-sql.ts`). Deliberately smaller than `SqlClient`: nothing here ever needs the tagged
32
+ * template, transactions or streaming, because every statement is either bound params through
33
+ * `.unsafe(text, params)` or a hand-escaped literal through `.unsafe(text)`. */
34
+ export interface PgExecutor {
35
+ readonly unsafe: <A extends object>(
36
+ sql: string,
37
+ params?: ReadonlyArray<unknown>,
38
+ ) => Effect.Effect<ReadonlyArray<A>, SqlError>;
39
+ }
40
+
41
+ /** Single-token identifier quoting: wrap in `"`, double any embedded `"`. No dot-splitting —
42
+ * see the file header. Used for the database name and, since a role or tablespace name is a
43
+ * `NonReservedWord` too, for `OWNER` and `TABLESPACE`. */
44
+ export const quoteIdent = (value: string): string => `"${value.replace(/"/g, '""')}"`;
45
+
46
+ /** SQL string-literal quoting: wrap in `'`, double any embedded `'`. Used for every `WITH`
47
+ * value that is locale or encoding text, never for an identifier (see the file header). */
48
+ export const quoteStringLiteral = (value: string): string => `'${value.replace(/'/g, "''")}'`;
49
+
50
+ const withOptions = (props: PostgresDatabaseProps): string => {
51
+ const parts: string[] = [`OWNER ${quoteIdent(props.owner)}`];
52
+ if (props.encoding !== undefined) parts.push(`ENCODING ${quoteStringLiteral(props.encoding)}`);
53
+ if (props.localeProvider !== undefined) {
54
+ parts.push(`LOCALE_PROVIDER ${quoteStringLiteral(props.localeProvider)}`);
55
+ }
56
+ if (props.lcCollate !== undefined)
57
+ parts.push(`LC_COLLATE ${quoteStringLiteral(props.lcCollate)}`);
58
+ if (props.lcCtype !== undefined) parts.push(`LC_CTYPE ${quoteStringLiteral(props.lcCtype)}`);
59
+ if (props.tablespace !== undefined) parts.push(`TABLESPACE ${quoteIdent(props.tablespace)}`);
60
+ if (props.allowConnections !== undefined) {
61
+ parts.push(`ALLOW_CONNECTIONS ${props.allowConnections ? 'true' : 'false'}`);
62
+ }
63
+ if (props.connectionLimit !== undefined) {
64
+ parts.push(`CONNECTION LIMIT ${String(Math.trunc(props.connectionLimit))}`);
65
+ }
66
+ if (props.isTemplate !== undefined)
67
+ parts.push(`IS_TEMPLATE ${props.isTemplate ? 'true' : 'false'}`);
68
+ return parts.join(' ');
69
+ };
70
+
71
+ /**
72
+ * Build the exact `CREATE DATABASE` text — a pure function, unit-tested on its own with no
73
+ * client at all. `CONNECTION LIMIT` and the two booleans are never string-escaped: an integer is
74
+ * `Math.trunc`ed and stringified, and a boolean is one of exactly two literal words this file
75
+ * writes, so no declared value reaches the statement through string interpolation unescaped.
76
+ */
77
+ export const buildCreateDatabaseSql = (props: PostgresDatabaseProps): string =>
78
+ `CREATE DATABASE ${quoteIdent(props.name)} WITH ${withOptions(props)}`;
79
+
80
+ /** `42P04` (`duplicate_database`) is a race: something else created the name between our read
81
+ * and our create. Measured at `internal/sqlError.ts@effect/sql-pg 4.0.0-rc.115`: every SQLSTATE
82
+ * starting `42` — this one included — classifies as `SqlSyntaxError`, the same tag a genuine
83
+ * syntax error would raise; there is no more specific tag to `catchTag` on. So this reads the
84
+ * raw code PostgreSQL sent, carried on `reason.cause.code` (`PgConnection.ts#errorFromFields`,
85
+ * `Object.assign(new Error(...), fields)`), rather than trusting the tag alone. */
86
+ export const isDuplicateDatabaseRace = (error: SqlError): boolean => {
87
+ if (error.reason._tag !== 'SqlSyntaxError') return false;
88
+ const cause = error.reason.cause;
89
+ return (
90
+ typeof cause === 'object' && cause !== null && (cause as { code?: unknown }).code === '42P04'
91
+ );
92
+ };
93
+
94
+ const ROLE_EXISTS_SQL = 'SELECT 1 AS present FROM pg_roles WHERE rolname = $1';
95
+
96
+ /** `OWNER` is checked against `pg_roles` before any `CREATE`, so a missing role is
97
+ * `PostgresDatabaseOwnerMissing` at reconcile time rather than the server's own
98
+ * `ERROR: role "…" does not exist` surfacing as an unclassified statement failure. */
99
+ export const roleExists = (pg: PgExecutor, role: string): Effect.Effect<boolean, SqlError> =>
100
+ Effect.map(
101
+ pg.unsafe<{ readonly present: number }>(ROLE_EXISTS_SQL, [role]),
102
+ (rows) => rows.length > 0,
103
+ );
104
+
105
+ /** `datlocprovider` is Postgres's internal 1-byte `"char"` type, which this client decodes as
106
+ * raw bytes rather than text (measured 2026-09-23 against the live socket — `docs/postgres.md`);
107
+ * the `CASE` maps it to the same three words `pg_collation.h@REL_18_6#collprovider_name` returns
108
+ * for the same codes, so the row never crosses the wire as anything but ordinary `text`.
109
+ *
110
+ * ⛔ `oid` AND `datconnlimit` ARE READ AT THEIR NATIVE CATALOG WIDTH — NEVER CAST TO `::int8`.
111
+ * `pg_database.h@REL_18_6` types them `Oid oid` (4 bytes, builtin OID 26) and
112
+ * `int32 datconnlimit` (4 bytes, builtin OID 23); `@effect/sql-pg`'s codec table
113
+ * (`PgTypes.ts@4.0.0-rc.115`) decodes both of those as a plain JS `number`
114
+ * (`readUint32`/`readInt32`), matching `PostgresDatabaseAttributes`'s declared `number`
115
+ * fields. Casting either to `::int8` changes the WIRE type the server sends, so the same
116
+ * codec table decodes it as a JS `bigint` instead (`OID.int8`'s codec calls
117
+ * `DataView.getBigInt64`) — and alchemy's `encodeState`
118
+ * (`node_modules/alchemy/lib/State/StateEncoding.js`) has no `bigint` branch, so
119
+ * `JSON.stringify`ing the persisted state throws `TypeError: Do not know how to serialize a
120
+ * BigInt` on every successful reconcile, and a live `bigint` compared against a declared
121
+ * `number` in `firstDrift` below is never `===`, so a matching `connectionLimit` reads as
122
+ * permanent drift. Measured 2026-09-23; regression test:
123
+ * `database-bigint-serialization.test.ts`. */
124
+ const SELECT_DATABASE_SQL = `SELECT
125
+ d.oid AS oid,
126
+ d.datname AS name,
127
+ pg_get_userbyid(d.datdba) AS owner,
128
+ pg_encoding_to_char(d.encoding) AS encoding,
129
+ CASE d.datlocprovider
130
+ WHEN 'b' THEN 'builtin' WHEN 'i' THEN 'icu' WHEN 'c' THEN 'libc'
131
+ ELSE 'libc'
132
+ END AS "localeProvider",
133
+ d.datcollate AS collate,
134
+ d.datctype AS ctype,
135
+ d.datallowconn AS "allowConnections",
136
+ d.datconnlimit AS "connectionLimit",
137
+ d.datistemplate AS "isTemplate",
138
+ t.spcname AS tablespace
139
+ FROM pg_database d
140
+ JOIN pg_tablespace t ON t.oid = d.dattablespace
141
+ WHERE d.datname = $1`;
142
+
143
+ /** The read: one bound `SELECT` on `pg_database`, joined to the two functions that turn its raw
144
+ * owner and encoding columns into names (`docs/postgres.md#mapping`). `undefined` when the row
145
+ * is absent — ownership branding happens one layer up, in `database.ts`, not here. */
146
+ export const selectDatabase = (
147
+ pg: PgExecutor,
148
+ name: string,
149
+ ): Effect.Effect<PostgresDatabaseAttributes | undefined, SqlError> =>
150
+ Effect.map(pg.unsafe<PostgresDatabaseAttributes>(SELECT_DATABASE_SQL, [name]), (rows) => rows[0]);
151
+
152
+ /** Compare every declared, asserted prop against the live row. Returns the name of the first
153
+ * prop that drifted, or `undefined` when every declared prop matches. `name` and `owner` are
154
+ * compared by their callers (identity and the create-time assertion), never here. */
155
+ export const firstDrift = (
156
+ props: PostgresDatabaseProps,
157
+ live: PostgresDatabaseAttributes,
158
+ ): { readonly prop: string; readonly declared: unknown; readonly live: unknown } | undefined => {
159
+ const checks: ReadonlyArray<readonly [string, unknown, unknown]> = [
160
+ ['encoding', props.encoding, live.encoding],
161
+ ['localeProvider', props.localeProvider, live.localeProvider],
162
+ ['lcCollate', props.lcCollate, live.collate],
163
+ ['lcCtype', props.lcCtype, live.ctype],
164
+ ['allowConnections', props.allowConnections, live.allowConnections],
165
+ ['connectionLimit', props.connectionLimit, live.connectionLimit],
166
+ ['isTemplate', props.isTemplate, live.isTemplate],
167
+ ['tablespace', props.tablespace, live.tablespace],
168
+ ];
169
+ for (const [prop, declared, liveValue] of checks) {
170
+ if (declared !== undefined && declared !== liveValue)
171
+ return { prop, declared, live: liveValue };
172
+ }
173
+ return undefined;
174
+ };
@@ -0,0 +1,193 @@
1
+ /**
2
+ * `Postgres.Database` — create-and-assert over a self-hosted PostgreSQL 18 cluster.
3
+ *
4
+ * ⛔ THIS IS NOT AN ALTER-CAPABLE RESOURCE. Every optional prop is asserted ONCE, at create, and
5
+ * compared against the live row on every later plan; a mismatch is a typed
6
+ * `PostgresDatabaseDrift` refusal, never an `ALTER DATABASE`. `docs/postgres.md` says why:
7
+ * several of these props (`LC_COLLATE`, `LC_CTYPE`, `LOCALE_PROVIDER`) cannot be altered on a
8
+ * live database at all without `ALTER … REFRESH COLLATION VERSION` semantics this family does
9
+ * not implement, and the rest are left alone on principle rather than by accident.
10
+ * ⛔ `delete` NEVER DROPS. See `errors.ts#PostgresDatabaseDropRefused` and
11
+ * `defaultRemovalPolicy: 'retain'` below — two independent reasons the engine never issues
12
+ * `DROP DATABASE` through this provider.
13
+ * ★ A DATABASE CARRIES NO OWNERSHIP MARK (H1). `read` always answers `Unowned` for a match, the
14
+ * same rule `Cloudflare.Snippets.Snippet` uses for a marker-less API — so every one of the
15
+ * mini's 19 already-live databases needs `adopt(true)` in the stack that declares it.
16
+ */
17
+ import { Resource } from 'alchemy';
18
+ import { Unowned } from 'alchemy/AdoptPolicy';
19
+ import { isResolved } from 'alchemy/Diff';
20
+ import type { Input } from 'alchemy/Input';
21
+ import * as Provider from 'alchemy/Provider';
22
+ import * as Effect from 'effect/Effect';
23
+ import type { SqlError } from 'effect/unstable/sql/SqlError';
24
+ import type { PostgresDatabaseAttributes, PostgresDatabaseProps } from './database-attrs.ts';
25
+ import { nameByteRefusal } from './database-attrs.ts';
26
+ import {
27
+ buildCreateDatabaseSql,
28
+ firstDrift,
29
+ isDuplicateDatabaseRace,
30
+ roleExists,
31
+ selectDatabase,
32
+ } from './database-sql.ts';
33
+ import { type PostgresConnection, withPg } from './connection.ts';
34
+ import type { PgExecutor } from './database-sql.ts';
35
+ import {
36
+ PostgresDatabaseCreateVanished,
37
+ PostgresDatabaseDrift,
38
+ PostgresDatabaseDropRefused,
39
+ PostgresDatabaseNameRefused,
40
+ PostgresDatabaseOwnerMissing,
41
+ PostgresDatabaseRenameRefused,
42
+ } from './errors.ts';
43
+
44
+ export interface PostgresDatabase extends Resource<
45
+ 'Postgres.Database',
46
+ PostgresDatabaseProps,
47
+ PostgresDatabaseAttributes,
48
+ never,
49
+ PostgresConnection
50
+ > {}
51
+
52
+ export const PostgresDatabase = Resource<PostgresDatabase>('Postgres.Database', {
53
+ defaultRemovalPolicy: 'retain',
54
+ });
55
+
56
+ /** Mirrors `alchemy/Resource`'s own `isResourceOfType`: a resource constructor is a callable
57
+ * `Object.assign`ed function, not a plain object, so `typeof` must accept both — a bare
58
+ * `'object'` check (measured live in `scripts/smoke.ts`: it rejects `PostgresDatabase` itself,
59
+ * matching only an instance) is the regression this comment exists to prevent. */
60
+ export const isPostgresDatabase = (value: unknown): value is PostgresDatabase =>
61
+ (typeof value === 'object' || typeof value === 'function') &&
62
+ value !== null &&
63
+ (value as { Type?: unknown }).Type === 'Postgres.Database';
64
+
65
+ /** Every asserted-prop mismatch against the LIVE row, owner included — reconcile's own
66
+ * authoritative check, independent of what `diff` compared at plan time (S10: cloud state is
67
+ * authoritative). */
68
+ const liveDrift = (props: PostgresDatabaseProps, live: PostgresDatabaseAttributes) => {
69
+ if (props.owner !== live.owner) {
70
+ return { prop: 'owner', declared: props.owner, live: live.owner };
71
+ }
72
+ return firstDrift(props, live);
73
+ };
74
+
75
+ /**
76
+ * The core of `reconcile`, against any {@link PgExecutor} — the real pooled client through
77
+ * `withPg`, or `fake-sql.ts`'s recording fake in tests. Kept apart from the provider wiring
78
+ * below so a lifecycle test drives this exact function, not a re-implementation of it.
79
+ */
80
+ export const reconcileWithClient = (
81
+ pg: PgExecutor,
82
+ props: PostgresDatabaseProps,
83
+ ): Effect.Effect<
84
+ PostgresDatabaseAttributes,
85
+ PostgresDatabaseOwnerMissing | PostgresDatabaseDrift | PostgresDatabaseCreateVanished | SqlError
86
+ > =>
87
+ Effect.gen(function* () {
88
+ const observed = yield* selectDatabase(pg, props.name);
89
+ if (observed === undefined) {
90
+ const ownerPresent = yield* roleExists(pg, props.owner);
91
+ if (!ownerPresent) {
92
+ return yield* Effect.fail(
93
+ new PostgresDatabaseOwnerMissing({ database: props.name, owner: props.owner }),
94
+ );
95
+ }
96
+ yield* pg.unsafe(buildCreateDatabaseSql(props)).pipe(
97
+ Effect.asVoid,
98
+ Effect.catchTag('SqlError', (error) =>
99
+ isDuplicateDatabaseRace(error) ? Effect.succeed(undefined) : Effect.fail(error),
100
+ ),
101
+ );
102
+ // Never trust the write's own report (S10): re-read what the server actually stored.
103
+ const created = yield* selectDatabase(pg, props.name);
104
+ if (created === undefined) {
105
+ return yield* Effect.fail(new PostgresDatabaseCreateVanished({ database: props.name }));
106
+ }
107
+ return created;
108
+ }
109
+ const drift = liveDrift(props, observed);
110
+ if (drift !== undefined) {
111
+ return yield* Effect.fail(
112
+ new PostgresDatabaseDrift({
113
+ database: props.name,
114
+ prop: drift.prop,
115
+ declared: drift.declared,
116
+ live: drift.live,
117
+ }),
118
+ );
119
+ }
120
+ // Unchanged: the row already read is the authoritative answer. No write, no second round trip.
121
+ return observed;
122
+ });
123
+
124
+ /** The core of `read`: one bound `SELECT`, no ownership branding — the caller (the provider's
125
+ * `read` below, or a test) decides whether to wrap a match in `Unowned`. */
126
+ export const readWithClient = (pg: PgExecutor, name: string) => selectDatabase(pg, name);
127
+
128
+ /**
129
+ * The core of `diff`, entirely offline: `news` (declared) against `output` (last-applied
130
+ * attributes) — never a live query (that authoritative check is `reconcileWithClient`'s job, per
131
+ * S10). A rename is a plan-time refusal; over-long names are too, so a bad name never even reaches
132
+ * `reconcile`; every other change answers `update`, which `reconcileWithClient` then either
133
+ * applies (create) or refuses (drift on an already-live database).
134
+ */
135
+ export const diffPostgresDatabase = (
136
+ news: Input<PostgresDatabaseProps>,
137
+ output: PostgresDatabaseAttributes | undefined,
138
+ ) =>
139
+ Effect.gen(function* () {
140
+ if (output === undefined || !isResolved(news)) return undefined;
141
+ if (news.name !== output.name) {
142
+ return yield* Effect.fail(
143
+ new PostgresDatabaseRenameRefused({ from: output.name, to: news.name }),
144
+ );
145
+ }
146
+ const nameRefusal = nameByteRefusal(news.name);
147
+ if (nameRefusal !== undefined) {
148
+ return yield* Effect.fail(
149
+ new PostgresDatabaseNameRefused({ name: news.name, ...nameRefusal }),
150
+ );
151
+ }
152
+ const changed = news.owner !== output.owner || firstDrift(news, output) !== undefined;
153
+ return changed ? ({ action: 'update' } as const) : ({ action: 'noop' } as const);
154
+ });
155
+
156
+ /**
157
+ * The five lifecycle handlers, wired to `withPg` for anything that touches a client. Exported
158
+ * on its own — not only through {@link PostgresDatabaseProvider}'s `Layer` — so a test can call
159
+ * `postgresDatabaseHandlers.delete(...)` directly, against the real implementation, without
160
+ * standing up the engine's provider machinery.
161
+ */
162
+ export const postgresDatabaseHandlers = PostgresDatabase.Provider.of({
163
+ // ⚠️ EMPTY, NOT A LIVE SWEEP. Enumerating `pg_database` would list every database on the
164
+ // cluster, most of which nothing declared — the same reasoning `NetboxPrefix` documents
165
+ // for its own marker-less `list`. Adoption for this family is one declaration at a time.
166
+ list: () => Effect.succeed([]),
167
+ nuke: { skip: true },
168
+
169
+ read: ({ olds, output }) =>
170
+ Effect.gen(function* () {
171
+ const name = output?.name ?? olds.name;
172
+ const live = yield* withPg((pg) => readWithClient(pg, name));
173
+ return live === undefined ? undefined : Unowned(live);
174
+ }),
175
+
176
+ diff: ({ news, output }) => diffPostgresDatabase(news, output),
177
+
178
+ reconcile: ({ news }) =>
179
+ Effect.gen(function* () {
180
+ const nameRefusal = nameByteRefusal(news.name);
181
+ if (nameRefusal !== undefined) {
182
+ return yield* Effect.fail(
183
+ new PostgresDatabaseNameRefused({ name: news.name, ...nameRefusal }),
184
+ );
185
+ }
186
+ return yield* withPg((pg) => reconcileWithClient(pg, news));
187
+ }),
188
+
189
+ delete: ({ olds }) => Effect.fail(new PostgresDatabaseDropRefused({ database: olds.name })),
190
+ });
191
+
192
+ export const PostgresDatabaseProvider = () =>
193
+ Provider.succeed(PostgresDatabase, postgresDatabaseHandlers);