@prisma-next/sql-contract 0.8.0 → 0.9.0-dev.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.
Files changed (52) hide show
  1. package/README.md +13 -11
  2. package/dist/factories.d.mts +2 -2
  3. package/dist/factories.d.mts.map +1 -1
  4. package/dist/factories.mjs +16 -14
  5. package/dist/factories.mjs.map +1 -1
  6. package/dist/index-type-validation.d.mts +2 -2
  7. package/dist/index-type-validation.mjs +1 -1
  8. package/dist/index-type-validation.mjs.map +1 -1
  9. package/dist/{index-types-DqVqGHwg.d.mts → index-types-B1cf5N0F.d.mts} +1 -1
  10. package/dist/{index-types-DqVqGHwg.d.mts.map → index-types-B1cf5N0F.d.mts.map} +1 -1
  11. package/dist/index-types.d.mts +1 -1
  12. package/dist/types-B0lbr9cb.d.mts +498 -0
  13. package/dist/types-B0lbr9cb.d.mts.map +1 -0
  14. package/dist/types-iqFGDcJp.mjs +389 -0
  15. package/dist/types-iqFGDcJp.mjs.map +1 -0
  16. package/dist/types.d.mts +2 -2
  17. package/dist/types.mjs +2 -2
  18. package/dist/validators.d.mts +27 -15
  19. package/dist/validators.d.mts.map +1 -1
  20. package/dist/validators.mjs +409 -2
  21. package/dist/validators.mjs.map +1 -0
  22. package/package.json +6 -7
  23. package/src/exports/types.ts +30 -9
  24. package/src/factories.ts +19 -32
  25. package/src/index-type-validation.ts +1 -1
  26. package/src/index.ts +0 -1
  27. package/src/ir/foreign-key-references.ts +26 -0
  28. package/src/ir/foreign-key.ts +50 -0
  29. package/src/ir/postgres-enum-storage-entry.ts +55 -0
  30. package/src/ir/primary-key.ts +22 -0
  31. package/src/ir/sql-index.ts +33 -0
  32. package/src/ir/sql-node.ts +52 -0
  33. package/src/ir/sql-storage.ts +154 -0
  34. package/src/ir/sql-unspecified-namespace.ts +51 -0
  35. package/src/ir/storage-column.ts +55 -0
  36. package/src/ir/storage-table.ts +63 -0
  37. package/src/ir/storage-type-instance.ts +60 -0
  38. package/src/ir/unique-constraint.ts +22 -0
  39. package/src/types.ts +38 -99
  40. package/src/validators.ts +268 -28
  41. package/dist/types-hgzy8ME1.mjs +0 -13
  42. package/dist/types-hgzy8ME1.mjs.map +0 -1
  43. package/dist/types-njsiV-Ck.d.mts +0 -186
  44. package/dist/types-njsiV-Ck.d.mts.map +0 -1
  45. package/dist/validate.d.mts +0 -9
  46. package/dist/validate.d.mts.map +0 -1
  47. package/dist/validate.mjs +0 -106
  48. package/dist/validate.mjs.map +0 -1
  49. package/dist/validators-Dm5X-Hvg.mjs +0 -294
  50. package/dist/validators-Dm5X-Hvg.mjs.map +0 -1
  51. package/src/exports/validate.ts +0 -1
  52. package/src/validate.ts +0 -227
package/src/factories.ts CHANGED
@@ -1,42 +1,32 @@
1
1
  import type { ScalarFieldType } from '@prisma-next/contract/types';
2
- import type {
2
+ import {
3
+ applyFkDefaults,
3
4
  ForeignKey,
4
- ForeignKeyOptions,
5
- ForeignKeyReferences,
5
+ type ForeignKeyOptions,
6
6
  Index,
7
7
  PrimaryKey,
8
- SqlModelFieldStorage,
9
- SqlModelStorage,
8
+ type SqlModelFieldStorage,
9
+ type SqlModelStorage,
10
10
  StorageColumn,
11
+ type StorageColumnInput,
11
12
  StorageTable,
12
13
  UniqueConstraint,
13
14
  } from './types';
14
- import { applyFkDefaults } from './types';
15
15
 
16
16
  export function col(nativeType: string, codecId: string, nullable = false): StorageColumn {
17
- return {
18
- nativeType,
19
- codecId,
20
- nullable,
21
- };
17
+ return new StorageColumn({ nativeType, codecId, nullable });
22
18
  }
23
19
 
24
20
  export function pk(...columns: readonly string[]): PrimaryKey {
25
- return {
26
- columns,
27
- };
21
+ return new PrimaryKey({ columns });
28
22
  }
29
23
 
30
24
  export function unique(...columns: readonly string[]): UniqueConstraint {
31
- return {
32
- columns,
33
- };
25
+ return new UniqueConstraint({ columns });
34
26
  }
35
27
 
36
28
  export function index(...columns: readonly string[]): Index {
37
- return {
38
- columns,
39
- };
29
+ return new Index({ columns });
40
30
  }
41
31
 
42
32
  export function fk(
@@ -45,23 +35,20 @@ export function fk(
45
35
  refColumns: readonly string[],
46
36
  opts?: ForeignKeyOptions & { constraint?: boolean; index?: boolean },
47
37
  ): ForeignKey {
48
- const references: ForeignKeyReferences = {
49
- table: refTable,
50
- columns: refColumns,
51
- };
52
-
53
- return {
38
+ const defaults = applyFkDefaults({ constraint: opts?.constraint, index: opts?.index });
39
+ return new ForeignKey({
54
40
  columns,
55
- references,
41
+ references: { table: refTable, columns: refColumns },
56
42
  ...(opts?.name !== undefined && { name: opts.name }),
57
43
  ...(opts?.onDelete !== undefined && { onDelete: opts.onDelete }),
58
44
  ...(opts?.onUpdate !== undefined && { onUpdate: opts.onUpdate }),
59
- ...applyFkDefaults({ constraint: opts?.constraint, index: opts?.index }),
60
- };
45
+ constraint: defaults.constraint,
46
+ index: defaults.index,
47
+ });
61
48
  }
62
49
 
63
50
  export function table(
64
- columns: Record<string, StorageColumn>,
51
+ columns: Record<string, StorageColumn | StorageColumnInput>,
65
52
  opts?: {
66
53
  pk?: PrimaryKey;
67
54
  uniques?: readonly UniqueConstraint[];
@@ -69,13 +56,13 @@ export function table(
69
56
  fks?: readonly ForeignKey[];
70
57
  },
71
58
  ): StorageTable {
72
- return {
59
+ return new StorageTable({
73
60
  columns,
74
61
  ...(opts?.pk !== undefined && { primaryKey: opts.pk }),
75
62
  uniques: opts?.uniques ?? [],
76
63
  indexes: opts?.indexes ?? [],
77
64
  foreignKeys: opts?.fks ?? [],
78
- };
65
+ });
79
66
  }
80
67
 
81
68
  export function model(
@@ -1,5 +1,5 @@
1
+ import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';
1
2
  import type { Contract } from '@prisma-next/contract/types';
2
- import { ContractValidationError } from '@prisma-next/contract/validate-contract';
3
3
  import { type } from 'arktype';
4
4
  import type { IndexTypeRegistry } from './index-types';
5
5
  import type { SqlStorage } from './types';
package/src/index.ts CHANGED
@@ -2,5 +2,4 @@ export * from './exports/factories';
2
2
  export * from './exports/index-type-validation';
3
3
  export * from './exports/index-types';
4
4
  export * from './exports/types';
5
- export * from './exports/validate';
6
5
  export * from './exports/validators';
@@ -0,0 +1,26 @@
1
+ import { freezeNode } from '@prisma-next/framework-components/ir';
2
+ import { SqlNode } from './sql-node';
3
+
4
+ export interface ForeignKeyReferencesInput {
5
+ readonly table: string;
6
+ readonly columns: readonly string[];
7
+ }
8
+
9
+ /**
10
+ * SQL Contract IR node for the referenced side of a foreign key.
11
+ *
12
+ * The class is shaped around single-namespace references today; a
13
+ * future milestone introduces a cross-namespace coordinate on top of
14
+ * `(table, columns)` when namespace-keyed storage lands.
15
+ */
16
+ export class ForeignKeyReferences extends SqlNode {
17
+ readonly table: string;
18
+ readonly columns: readonly string[];
19
+
20
+ constructor(input: ForeignKeyReferencesInput) {
21
+ super();
22
+ this.table = input.table;
23
+ this.columns = input.columns;
24
+ freezeNode(this);
25
+ }
26
+ }
@@ -0,0 +1,50 @@
1
+ import { freezeNode } from '@prisma-next/framework-components/ir';
2
+ import { ForeignKeyReferences, type ForeignKeyReferencesInput } from './foreign-key-references';
3
+ import { SqlNode } from './sql-node';
4
+
5
+ export type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';
6
+
7
+ export interface ForeignKeyInput {
8
+ readonly columns: readonly string[];
9
+ readonly references: ForeignKeyReferences | ForeignKeyReferencesInput;
10
+ readonly name?: string;
11
+ readonly onDelete?: ReferentialAction;
12
+ readonly onUpdate?: ReferentialAction;
13
+ /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */
14
+ readonly constraint: boolean;
15
+ /** Whether to emit a backing index for the FK columns. */
16
+ readonly index: boolean;
17
+ }
18
+
19
+ /**
20
+ * SQL Contract IR node for a table-level foreign-key declaration.
21
+ *
22
+ * The nested `references` field is normalised to a
23
+ * {@link ForeignKeyReferences} instance inside the constructor so
24
+ * downstream walks see a uniform AST regardless of whether the input
25
+ * was a JSON literal or an already-constructed class instance.
26
+ */
27
+ export class ForeignKey extends SqlNode {
28
+ readonly columns: readonly string[];
29
+ readonly references: ForeignKeyReferences;
30
+ readonly constraint: boolean;
31
+ readonly index: boolean;
32
+ declare readonly name?: string;
33
+ declare readonly onDelete?: ReferentialAction;
34
+ declare readonly onUpdate?: ReferentialAction;
35
+
36
+ constructor(input: ForeignKeyInput) {
37
+ super();
38
+ this.columns = input.columns;
39
+ this.references =
40
+ input.references instanceof ForeignKeyReferences
41
+ ? input.references
42
+ : new ForeignKeyReferences(input.references);
43
+ this.constraint = input.constraint;
44
+ this.index = input.index;
45
+ if (input.name !== undefined) this.name = input.name;
46
+ if (input.onDelete !== undefined) this.onDelete = input.onDelete;
47
+ if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;
48
+ freezeNode(this);
49
+ }
50
+ }
@@ -0,0 +1,55 @@
1
+ import type { StorageType } from '@prisma-next/framework-components/ir';
2
+
3
+ /**
4
+ * Discriminator literal for the Postgres-enum variant on the polymorphic
5
+ * `SqlStorage.types` slot.
6
+ *
7
+ * Enums are a target-level concept: Postgres ships native
8
+ * `CREATE TYPE … AS ENUM` while other SQL targets approximate enums via
9
+ * constraints. The literal lives at the SQL family layer because every
10
+ * SQL-family consumer (verifier, planner, lowering, …) needs to
11
+ * discriminate enum-typed slot entries from codec-typed ones. The
12
+ * concrete IR class (`PostgresEnumType`) lives in the target-postgres
13
+ * package and implements this structural contract; cross-domain
14
+ * layering rules forbid the SQL family from importing the concrete
15
+ * target class directly, so the discriminator and structural interface
16
+ * carry the dispatch.
17
+ */
18
+ export const POSTGRES_ENUM_KIND = 'postgres-enum' as const;
19
+
20
+ /**
21
+ * Structural contract every Postgres-enum slot entry honours — both
22
+ * the live `PostgresEnumType` IR-class instance and the raw JSON
23
+ * envelope shape that survives `JSON.stringify` round-trips. SQL
24
+ * family-layer dispatch narrows polymorphic `StorageType` slot
25
+ * entries to this shape via `isPostgresEnumStorageEntry`.
26
+ *
27
+ * The `codecBinding` field is accessor-shaped (live class instance) on
28
+ * the IR class and undefined on the raw JSON envelope; consumers that
29
+ * need it must guard for its presence (the JSON path synthesises an
30
+ * equivalent shape from `codecId` + `values`).
31
+ */
32
+ export interface PostgresEnumStorageEntry extends StorageType {
33
+ readonly kind: typeof POSTGRES_ENUM_KIND;
34
+ readonly name: string;
35
+ readonly nativeType: string;
36
+ readonly values: readonly string[];
37
+ /**
38
+ * Enumerable own property on the persisted JSON envelope; the live
39
+ * IR-class instance carries it too. Family-shared dispatch sites
40
+ * read `codecId` directly rather than going through the IR-class
41
+ * `codecBinding` accessor (which lives on the prototype and isn't
42
+ * present on raw JSON envelopes).
43
+ */
44
+ readonly codecId: string;
45
+ }
46
+
47
+ /**
48
+ * Narrow a polymorphic `StorageType` entry to the Postgres-enum shape
49
+ * via its enumerable `kind` discriminator. Type guard returns true for
50
+ * both live `PostgresEnumType` instances and raw JSON envelopes.
51
+ */
52
+ export function isPostgresEnumStorageEntry(value: unknown): value is PostgresEnumStorageEntry {
53
+ if (typeof value !== 'object' || value === null) return false;
54
+ return (value as { kind?: unknown }).kind === POSTGRES_ENUM_KIND;
55
+ }
@@ -0,0 +1,22 @@
1
+ import { freezeNode } from '@prisma-next/framework-components/ir';
2
+ import { SqlNode } from './sql-node';
3
+
4
+ export interface PrimaryKeyInput {
5
+ readonly columns: readonly string[];
6
+ readonly name?: string;
7
+ }
8
+
9
+ /**
10
+ * SQL Contract IR node for a table's primary-key constraint.
11
+ */
12
+ export class PrimaryKey extends SqlNode {
13
+ readonly columns: readonly string[];
14
+ declare readonly name?: string;
15
+
16
+ constructor(input: PrimaryKeyInput) {
17
+ super();
18
+ this.columns = input.columns;
19
+ if (input.name !== undefined) this.name = input.name;
20
+ freezeNode(this);
21
+ }
22
+ }
@@ -0,0 +1,33 @@
1
+ import { freezeNode } from '@prisma-next/framework-components/ir';
2
+ import { SqlNode } from './sql-node';
3
+
4
+ export interface IndexInput {
5
+ readonly columns: readonly string[];
6
+ readonly name?: string;
7
+ readonly type?: string;
8
+ readonly options?: Record<string, unknown>;
9
+ }
10
+
11
+ /**
12
+ * SQL Contract IR node for a table-level secondary index.
13
+ *
14
+ * Note that this class shadows the global TypeScript `Index` lib type
15
+ * at the family-shared name; consumer files that need both should
16
+ * alias one (e.g.
17
+ * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).
18
+ */
19
+ export class Index extends SqlNode {
20
+ readonly columns: readonly string[];
21
+ declare readonly name?: string;
22
+ declare readonly type?: string;
23
+ declare readonly options?: Record<string, unknown>;
24
+
25
+ constructor(input: IndexInput) {
26
+ super();
27
+ this.columns = input.columns;
28
+ if (input.name !== undefined) this.name = input.name;
29
+ if (input.type !== undefined) this.type = input.type;
30
+ if (input.options !== undefined) this.options = input.options;
31
+ freezeNode(this);
32
+ }
33
+ }
@@ -0,0 +1,52 @@
1
+ import { IRNodeBase } from '@prisma-next/framework-components/ir';
2
+
3
+ /**
4
+ * SQL family IR node base. Carries the family-level `kind` discriminator
5
+ * `'sql'` and inherits the framework's `freezeNode` affordance.
6
+ *
7
+ * Single family-level discriminator (not per-leaf) reflects the fact that
8
+ * SQL IR has no polymorphic dispatch today — verifiers and serializers
9
+ * walk by structural position (`storage.tables[name].columns[name]`),
10
+ * not by inspecting `kind`. The abstract bar for per-leaf discriminators
11
+ * isn't earned until a future polymorphic consumer arrives.
12
+ *
13
+ * `kind` is installed as a non-enumerable own property on every instance,
14
+ * which keeps three things clean simultaneously:
15
+ *
16
+ * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope
17
+ * shape (no `kind` field), so emitted contract.json files and the
18
+ * `validateSqlContractFully` arktype schemas stay unchanged.
19
+ * - Test assertions that use `toEqual({...})` against the pre-lift flat
20
+ * shape continue to pass — only enumerable own properties are
21
+ * compared.
22
+ * - Direct access (`node.kind`) and runtime narrowing
23
+ * (`if (node.kind === 'sql')`) still work, so future polymorphic
24
+ * dispatch can begin reading `kind` without a runtime change.
25
+ *
26
+ * Future per-leaf overrides land cleanly: a class that gains a
27
+ * polymorphic-dispatch consumer (e.g. an enum type instance walked
28
+ * alongside other types) overrides `kind` with its narrower literal
29
+ * at that leaf level. Per-leaf overrides will use enumerable kind
30
+ * (matching the Mongo per-class-discriminator precedent) because they
31
+ * encode dispatch-relevant information that callers need to see in
32
+ * JSON envelopes; the family-level `'sql'` is uniform across all SQL
33
+ * IR and carries no dispatch-relevant information.
34
+ */
35
+ export abstract class SqlNode extends IRNodeBase {
36
+ readonly kind?: string;
37
+
38
+ constructor() {
39
+ super();
40
+ Object.defineProperty(this, 'kind', {
41
+ value: 'sql',
42
+ writable: false,
43
+ enumerable: false,
44
+ // configurable so per-leaf subclasses (e.g. PostgresEnumType in
45
+ // target-postgres) can override `kind` with their narrower
46
+ // enumerable literal via a class-field initializer. SqlNode
47
+ // itself never needs to mutate the property again, so
48
+ // configurability has no surface impact at this layer.
49
+ configurable: true,
50
+ });
51
+ }
52
+ }
@@ -0,0 +1,154 @@
1
+ import type { StorageHashBase } from '@prisma-next/contract/types';
2
+ import {
3
+ freezeNode,
4
+ type Namespace,
5
+ type Storage,
6
+ UNSPECIFIED_NAMESPACE_ID,
7
+ } from '@prisma-next/framework-components/ir';
8
+ import {
9
+ isPostgresEnumStorageEntry,
10
+ type PostgresEnumStorageEntry,
11
+ } from './postgres-enum-storage-entry';
12
+ import { SqlNode } from './sql-node';
13
+ import { SqlUnspecifiedNamespace } from './sql-unspecified-namespace';
14
+ import { StorageTable, type StorageTableInput } from './storage-table';
15
+ import {
16
+ isStorageTypeInstance,
17
+ type StorageTypeInstance,
18
+ type StorageTypeInstanceInput,
19
+ } from './storage-type-instance';
20
+
21
+ /**
22
+ * Polymorphic value type for `SqlStorage.types` entries (Decision 18,
23
+ * Option B). The slot's framework alphabet is `StorageType` — codec
24
+ * triples (`StorageTypeInstance` with `kind: 'codec-instance'`) and
25
+ * target-specific IR class instances structurally satisfying
26
+ * `PostgresEnumStorageEntry` (with `kind: 'postgres-enum'`) are the
27
+ * two variants the SQL family ships today. The construction side also
28
+ * accepts {@link StorageTypeInstanceInput} so callers can pass raw
29
+ * codec triples; the constructor stamps the discriminator.
30
+ */
31
+ export type SqlStorageTypeEntry =
32
+ | StorageTypeInstance
33
+ | PostgresEnumStorageEntry
34
+ | StorageTypeInstanceInput;
35
+
36
+ const DEFAULT_NAMESPACES: Readonly<Record<string, Namespace>> = Object.freeze({
37
+ [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance,
38
+ });
39
+
40
+ export interface SqlStorageInput<THash extends string = string> {
41
+ readonly storageHash: StorageHashBase<THash>;
42
+ readonly tables: Record<string, StorageTable | StorageTableInput>;
43
+ readonly types?: Record<string, SqlStorageTypeEntry>;
44
+ readonly namespaces?: Readonly<Record<string, Namespace>>;
45
+ }
46
+
47
+ /**
48
+ * SQL Contract IR root node for the `storage` field.
49
+ *
50
+ * Single concrete family-shared class — both Postgres and SQLite
51
+ * consume this same class today. Per-target storage subclasses are
52
+ * introduced when each target's namespace shape earns its
53
+ * target-specific concretion (target-specific derived fields,
54
+ * target-specific storage extensions).
55
+ *
56
+ * Honours the framework `Storage` interface: every SQL IR carries a
57
+ * `namespaces` map keyed by namespace id. The default singleton
58
+ * (`{ [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance }`)
59
+ * binds every contract authored before per-target namespace concretions
60
+ * land; per-target namespace classes (`PostgresSchema.unspecified`,
61
+ * `SqliteUnspecifiedDatabase.instance`) earn their slots when each
62
+ * target's namespace shape lands.
63
+ *
64
+ * The constructor normalises nested IR-class fields (`tables`, optional
65
+ * `types`) into class instances so downstream walks see a uniform AST.
66
+ * `types` is polymorphic per Decision 18 Option B: codec-triple inputs
67
+ * are stamped with `kind: 'codec-instance'`; class-instance kinds
68
+ * (e.g. Postgres-enum entries satisfying `PostgresEnumStorageEntry`)
69
+ * pass through; hydration of raw JSON class-instance entries (carrying
70
+ * their narrower `kind` literal) is the per-target serializer's
71
+ * responsibility (so the family base does not import target-specific
72
+ * subclasses).
73
+ */
74
+ export class SqlStorage<THash extends string = string> extends SqlNode implements Storage {
75
+ readonly storageHash: StorageHashBase<THash>;
76
+ readonly tables: Readonly<Record<string, StorageTable>>;
77
+ readonly namespaces: Readonly<Record<string, Namespace>>;
78
+ // SQL-family slot view: the two structural variants the family ships
79
+ // today (codec triples + Postgres-enum structural entries). Each
80
+ // variant extends the framework `StorageType` alphabet; the SQL
81
+ // narrowing keeps cross-domain layering clean — SQL-family consumers
82
+ // dispatch via `isStorageTypeInstance` / `isPostgresEnumStorageEntry`
83
+ // type guards rather than importing the target's concrete IR class
84
+ // (cross-domain rule: SQL may not import `target-*`).
85
+ declare readonly types?: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;
86
+
87
+ constructor(input: SqlStorageInput<THash>) {
88
+ super();
89
+ this.storageHash = input.storageHash;
90
+ this.tables = Object.freeze(
91
+ Object.fromEntries(
92
+ Object.entries(input.tables).map(([name, t]) => [
93
+ name,
94
+ t instanceof StorageTable ? t : new StorageTable(t),
95
+ ]),
96
+ ),
97
+ );
98
+ this.namespaces = input.namespaces ?? DEFAULT_NAMESPACES;
99
+ if (input.types !== undefined) {
100
+ this.types = Object.freeze(
101
+ Object.fromEntries(
102
+ Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]),
103
+ ),
104
+ );
105
+ }
106
+ freezeNode(this);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Strict polymorphic-slot dispatch for `SqlStorage.types` entries
112
+ * (TML-2536). Every entry must carry a recognised `kind` discriminator
113
+ * — either `'codec-instance'` (codec triple, family-shared) or
114
+ * `'postgres-enum'` (target-specific IR class). Untagged or
115
+ * unrecognised inputs throw a diagnostic naming the entry and its
116
+ * `kind`, so format drift surfaces loudly at the deserializer
117
+ * boundary instead of slipping past the seam and corrupting
118
+ * downstream IR walks.
119
+ *
120
+ * Codec-triple authors that have an untagged shape on hand can call
121
+ * `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`
122
+ * discriminator) before constructing `SqlStorage`. On-disk reads
123
+ * cross `familyInstance.deserializeContract` first; the structural
124
+ * arktype schema rejects untagged entries earlier, so this throw
125
+ * only fires for in-memory authoring bugs.
126
+ */
127
+ function normaliseTypeEntry(
128
+ name: string,
129
+ entry: SqlStorageTypeEntry,
130
+ ): StorageTypeInstance | PostgresEnumStorageEntry {
131
+ if (isPostgresEnumStorageEntry(entry)) {
132
+ // Live class instances pass through unchanged; raw JSON envelopes
133
+ // (e.g. `kind: 'postgres-enum'` without the class identity) are
134
+ // rejected so the target serializer's hydration path is the only
135
+ // way IR class instances enter the slot.
136
+ if (entry instanceof SqlNode) {
137
+ return entry;
138
+ }
139
+ throw new Error(
140
+ `Encountered raw postgres-enum JSON in storage.types[${JSON.stringify(name)}] without serializer hydration; use a target ContractSerializer that registers the matching entity-type factory.`,
141
+ );
142
+ }
143
+ if (isStorageTypeInstance(entry)) {
144
+ return entry;
145
+ }
146
+ const rawKind = (entry as { kind?: unknown }).kind;
147
+ const kindDescription =
148
+ rawKind === undefined
149
+ ? 'missing `kind` discriminator'
150
+ : `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`;
151
+ throw new Error(
152
+ `storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify('codec-instance')} or ${JSON.stringify('postgres-enum')}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`,
153
+ );
154
+ }
@@ -0,0 +1,51 @@
1
+ import {
2
+ freezeNode,
3
+ NamespaceBase,
4
+ UNSPECIFIED_NAMESPACE_ID,
5
+ } from '@prisma-next/framework-components/ir';
6
+
7
+ /**
8
+ * Family-layer placeholder for the SQL unspecified-namespace singleton.
9
+ *
10
+ * SQL contracts honour the framework `Storage.namespaces` invariant from
11
+ * the moment they appear in the IR. Today `SqlStorage` is family-shared
12
+ * (Postgres + SQLite consume the same class); a per-target namespace
13
+ * concretion (`PostgresSchema.unspecified`, `SqliteUnspecifiedDatabase.instance`)
14
+ * earns its existence when each target's namespace shape lands. Until
15
+ * then the family ships a single placeholder singleton so the JSON
16
+ * envelope and runtime walk are honest at every layer.
17
+ *
18
+ * The `kind` discriminator is installed as a non-enumerable own property
19
+ * so the JSON envelope reads `{ "id": "__unspecified__" }` — symmetric
20
+ * with the family-level non-enumerable `kind` on `SqlNode` and bounded
21
+ * to the minimum data the framework `Namespace` interface promises.
22
+ *
23
+ * **Freeze-trap warning.** The leaf constructor calls
24
+ * `freezeNode(this)` after installing `kind`. The leaf-class shape
25
+ * works today only because `NamespaceBase` does NOT freeze in its
26
+ * constructor — the `Object.defineProperty(this, 'kind', …)` call after
27
+ * `super()` succeeds because the instance is still mutable at that
28
+ * point. Subclasses that add instance fields will still hit the freeze
29
+ * trap once leaf-class `freezeNode(this)` runs; and if a future
30
+ * framework change lifts the freeze to `NamespaceBase`, even the
31
+ * `defineProperty` here would silently fail. To add subclass instance
32
+ * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each
33
+ * leaf calls explicitly at the end of its own constructor.
34
+ */
35
+ export class SqlUnspecifiedNamespace extends NamespaceBase {
36
+ static readonly instance: SqlUnspecifiedNamespace = new SqlUnspecifiedNamespace();
37
+
38
+ readonly id = UNSPECIFIED_NAMESPACE_ID;
39
+ declare readonly kind?: string;
40
+
41
+ private constructor() {
42
+ super();
43
+ Object.defineProperty(this, 'kind', {
44
+ value: 'sql-namespace',
45
+ writable: false,
46
+ enumerable: false,
47
+ configurable: true,
48
+ });
49
+ freezeNode(this);
50
+ }
51
+ }
@@ -0,0 +1,55 @@
1
+ import type { ColumnDefault } from '@prisma-next/contract/types';
2
+ import { freezeNode } from '@prisma-next/framework-components/ir';
3
+ import { SqlNode } from './sql-node';
4
+
5
+ /**
6
+ * Hydration / construction input shape for {@link StorageColumn}. Mirrors
7
+ * the on-disk storage JSON envelope exactly so the family-base
8
+ * serializer's hydration walker can hand an arktype-validated literal
9
+ * straight to `new`.
10
+ *
11
+ * `typeParams` and `typeRef` remain mutually exclusive (one or the
12
+ * other, not both); the constructor preserves whichever caller-side
13
+ * choice the input encodes.
14
+ */
15
+ export interface StorageColumnInput {
16
+ readonly nativeType: string;
17
+ readonly codecId: string;
18
+ readonly nullable: boolean;
19
+ readonly typeParams?: Record<string, unknown>;
20
+ readonly typeRef?: string;
21
+ readonly default?: ColumnDefault;
22
+ }
23
+
24
+ /**
25
+ * SQL Contract IR node for a single column entry in `StorageTable.columns`.
26
+ *
27
+ * Single concrete family-shared class — every SQL target reads the
28
+ * same column shape today, so there is no per-target subclass. The
29
+ * class type accepts any caller that constructs via
30
+ * `new StorageColumn(input)`; literal construction sites must pass
31
+ * through the constructor or the family-base hydration walker.
32
+ *
33
+ * The column's `name` is not on the class — columns are keyed by name
34
+ * in the parent `StorageTable.columns: Record<string, StorageColumn>`
35
+ * map, so a `name` field would be redundant with the key.
36
+ */
37
+ export class StorageColumn extends SqlNode {
38
+ readonly nativeType: string;
39
+ readonly codecId: string;
40
+ readonly nullable: boolean;
41
+ declare readonly typeParams?: Record<string, unknown>;
42
+ declare readonly typeRef?: string;
43
+ declare readonly default?: ColumnDefault;
44
+
45
+ constructor(input: StorageColumnInput) {
46
+ super();
47
+ this.nativeType = input.nativeType;
48
+ this.codecId = input.codecId;
49
+ this.nullable = input.nullable;
50
+ if (input.typeParams !== undefined) this.typeParams = input.typeParams;
51
+ if (input.typeRef !== undefined) this.typeRef = input.typeRef;
52
+ if (input.default !== undefined) this.default = input.default;
53
+ freezeNode(this);
54
+ }
55
+ }