-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathinterpreter.ts
More file actions
2374 lines (2223 loc) · 86.4 KB
/
Copy pathinterpreter.ts
File metadata and controls
2374 lines (2223 loc) · 86.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
ContractSourceDiagnostic,
ContractSourceDiagnosticSpan,
ContractSourceDiagnostics,
} from '@prisma-next/config/config-types';
import type {
Contract,
ContractField,
ContractModel,
ContractValueObject,
ControlPolicy,
} from '@prisma-next/contract/types';
import { crossRef } from '@prisma-next/contract/types';
import type {
AuthoringContributions,
AuthoringEntityContext,
AuthoringEntityTypeDescriptor,
AuthoringEntityTypeNamespace,
AuthoringPslBlockDescriptorNamespace,
PslExtensionBlock,
} from '@prisma-next/framework-components/authoring';
import {
instantiateAuthoringEntityType,
isAuthoringEntityTypeDescriptor,
isAuthoringPslBlockDescriptor,
} from '@prisma-next/framework-components/authoring';
import type { CodecLookup } from '@prisma-next/framework-components/codec';
import type {
CapabilityMatrix,
ExtensionPackRef,
TargetPackRef,
} from '@prisma-next/framework-components/components';
import type {
ControlMutationDefaultRegistry,
ControlMutationDefaults,
MutationDefaultGeneratorDescriptor,
} from '@prisma-next/framework-components/control';
import {
type BlockSymbol,
type CompositeTypeSymbol,
type FieldSymbol,
keywordPslSpan,
type ModelSymbol,
type NamespaceSymbol,
nodePslSpan,
type ResolvedAttribute,
type ScalarSymbol,
type SymbolTable,
type TypeAliasSymbol,
} from '@prisma-next/psl-parser';
import type { SourceFile } from '@prisma-next/psl-parser/syntax';
import type {
SqlModelStorage,
SqlNamespaceBase,
SqlNamespaceInput,
} from '@prisma-next/sql-contract/types';
import { deriveValueSetFromEntity } from '@prisma-next/sql-contract/value-set-derivation-hook';
import {
buildSqlContractFromDefinition,
type EnumTypeHandle,
type FieldNode,
type ForeignKeyNode,
type IndexNode,
type ModelNode,
type PrimaryKeyNode,
type RelationNode,
type UniqueConstraintNode,
} from '@prisma-next/sql-contract-ts/contract-builder';
import { assertDefined, invariant } from '@prisma-next/utils/assertions';
import { blindCast } from '@prisma-next/utils/casts';
import { ifDefined } from '@prisma-next/utils/defined';
import { notOk, ok, type Result } from '@prisma-next/utils/result';
import {
findDuplicateFieldName,
getAttribute,
getNamedArgument,
getPositionalArgument,
mapFieldNamesToColumns,
parseAttributeFieldList,
parseConstraintMapArgument,
parseControlPolicyAttribute,
parseObjectLiteralStringMap,
parseQuotedStringLiteral,
} from './psl-attribute-parsing';
import type { ColumnDescriptor } from './psl-column-resolution';
import {
checkUncomposedNamespace,
getAuthoringEntity,
reportUncomposedNamespace,
resolveFieldTypeDescriptor,
} from './psl-column-resolution';
import {
buildModelMappings,
collectResolvedFields,
type ModelNameMapping,
type ModelNamespaceEntry,
modelCoordinateKey,
type ResolvedField,
} from './psl-field-resolution';
import { resolveNamedTypeDeclarations } from './psl-named-type-resolution';
import {
applyBackrelationCandidates,
type FkRelationMetadata,
indexFkRelations,
interpretRelationAttribute,
type ModelBackrelationCandidate,
normalizeReferentialAction,
type ParsedThrough,
resolveTargetIdFieldNames,
SYNTHESIZED_JUNCTION_COLUMN_A,
SYNTHESIZED_JUNCTION_COLUMN_B,
type SynthesizedJunction,
validateNavigationListFieldAttributes,
} from './psl-relation-resolution';
type NamedTypeSymbol = ScalarSymbol | TypeAliasSymbol;
export interface InterpretPslDocumentToSqlContractInput {
readonly symbolTable: SymbolTable;
readonly sourceFile: SourceFile;
readonly sourceId: string;
readonly target: TargetPackRef<'sql', string>;
readonly scalarTypeDescriptors: ReadonlyMap<string, ColumnDescriptor>;
readonly composedExtensionPacks?: readonly string[];
readonly composedExtensionPackRefs?: readonly ExtensionPackRef<'sql', string>[];
readonly controlMutationDefaults?: ControlMutationDefaults;
readonly authoringContributions?: AuthoringContributions;
/**
* Extension contracts keyed by space ID. Required for cross-space FK
* resolution. A composed space must have an entry here; if the space ID
* appears in `composedExtensionPacks` but is absent from this map, the
* interpreter emits `PSL_UNKNOWN_CONTRACT_SPACE` and fails fast — there
* is no silent fallback. If a space's contract is present but the
* referenced model or namespace is not found in it, the interpreter
* emits `PSL_UNKNOWN_CROSS_SPACE_TARGET`.
*/
readonly composedExtensionContracts: ReadonlyMap<string, Contract>;
/** Target-supplied factory that materialises a `SqlNamespaceBase` concretion for each namespace coordinate. */
readonly createNamespace: (input: SqlNamespaceInput) => SqlNamespaceBase;
readonly codecLookup?: CodecLookup;
readonly seedDiagnostics?: readonly ContractSourceDiagnostic[];
/** The target's default codec ids for an `enum` block that omits `@@type`. */
readonly enumInferenceCodecs?: { readonly text: string; readonly int: string };
readonly capabilities: CapabilityMatrix;
}
function buildComposedExtensionPackRefs(
target: TargetPackRef<'sql', string>,
extensionIds: readonly string[],
extensionPackRefs: readonly ExtensionPackRef<'sql', string>[] = [],
): Record<string, ExtensionPackRef<'sql', string>> | undefined {
if (extensionIds.length === 0) {
return undefined;
}
const extensionPackRefById = new Map(extensionPackRefs.map((packRef) => [packRef.id, packRef]));
return Object.fromEntries(
extensionIds.map((extensionId) => [
extensionId,
extensionPackRefById.get(extensionId) ??
({
kind: 'extension',
id: extensionId,
familyId: target.familyId,
targetId: target.targetId,
version: '0.0.1',
} satisfies ExtensionPackRef<'sql', string>),
]),
);
}
function compareStrings(left: string, right: string): -1 | 0 | 1 {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}
/**
* Name of the framework-parser synthesised bucket for top-level
* declarations. Re-declared here so the per-target dispatch does not
* have to import from `@prisma-next/framework-components/psl-ast`
* (which would cross a layer that the interpreter does not otherwise
* import from). The value is part of the framework parser's contract;
* if it changes there, the matching test in this package's
* `interpreter.diagnostics.test.ts` flips first.
*/
const UNSPECIFIED_PSL_NAMESPACE_NAME = '__unspecified__';
/**
* Per-target namespace-block validation: walk the AST's namespace buckets and
* emit diagnostics for syntactic constructs the target does not accept.
*
* - **SQLite** has no schema concept and rejects every explicit
* `namespace { … }` block. The implicit `__unspecified__` bucket
* (produced by the parser for top-level declarations outside any
* block) is the only namespace SQLite accepts.
* - **Postgres** accepts every explicit block — `namespace unbound { … }`
* is the late-binding opt-in (lowers to the IR `__unbound__` slot in
* a follow-on commit), `namespace public { … }` reopen-merges with
* the implicit bucket, and any other name lowers to a named schema.
*
* Storage-side lowering of these buckets to IR namespace slots is not
* yet wired; this helper closes only the diagnostic surface.
*/
/**
* Per-target namespace lowering: map a PSL AST namespace bucket name to the
* resolved IR namespace id (the key downstream consumers use against
* `SqlStorage.namespaces`).
*
* - **Postgres**: an explicit `namespace unbound { … }` block lowers
* to the framework sentinel `__unbound__` — the slot whose binding
* the connection's `search_path` resolves at runtime. Every other
* explicit bucket name (e.g. `auth`, `public`) passes through as a
* named schema id. The implicit `__unspecified__` bucket — top-level
* declarations outside any `namespace { … }` block — leaves the
* coordinate unset; downstream consumers treat unset as the
* late-bound default, and TS / PSL authoring stay byte-identical
* on single-namespace contracts. (A future round will add a
* target-default-namespace surface so `__unspecified__` lowers to
* `public` consistently on both authoring paths.)
* - **SQLite**: SQLite has no schema concept; every namespace
* collapses to the late-bound default. The namespace-block
* validation step (above) has already rejected any explicit
* `namespace { … }` block on SQLite, so the only bucket the
* lowering ever sees there is `__unspecified__`.
*
* Returns `undefined` for targets / bucket names with no explicit
* namespaceId to assign — callers leave the model's `namespaceId`
* slot empty (which means the late-bound default at the `StorageTable`
* layer; emitted JSON omits the field).
*/
function resolveNamespaceIdForSqlTarget(input: {
readonly bucketName: string;
readonly targetId: string;
}): string | undefined {
if (input.targetId !== 'postgres') {
return undefined;
}
if (input.bucketName === UNSPECIFIED_PSL_NAMESPACE_NAME) {
return 'public';
}
if (input.bucketName === 'unbound') {
return '__unbound__';
}
return input.bucketName;
}
function validateNamespaceBlocksForSqlTarget(input: {
readonly namespaces: readonly NamespaceSymbol[];
readonly targetId: string;
readonly sourceId: string;
readonly sourceFile: SourceFile;
readonly diagnostics: ContractSourceDiagnostic[];
}): void {
if (input.targetId === 'sqlite') {
for (const namespace of input.namespaces) {
input.diagnostics.push({
code: 'PSL_UNSUPPORTED_NAMESPACE_BLOCK',
message: `SQLite does not support \`namespace ${namespace.name} { … }\` blocks (SQLite has no schema concept; declare models at the document top level instead).`,
sourceId: input.sourceId,
span: nodePslSpan(namespace.node.syntax, input.sourceFile),
});
}
return;
}
if (input.targetId === 'postgres') {
const hasUnbound = input.namespaces.some((ns) => ns.name === 'unbound');
const hasSibling = input.namespaces.some((ns) => ns.name !== 'unbound');
if (hasUnbound && hasSibling) {
const unboundBlock = input.namespaces.find((ns) => ns.name === 'unbound');
input.diagnostics.push({
code: 'PSL_RESERVED_NAMESPACE_NAME',
message:
'Namespace "unbound" is reserved for the late-binding sentinel mapping and cannot appear alongside other named namespace blocks. ' +
'Use `namespace unbound { … }` alone (no sibling named namespaces) for late-binding multi-tenant contracts.',
sourceId: input.sourceId,
...(unboundBlock !== undefined
? { span: nodePslSpan(unboundBlock.node.syntax, input.sourceFile) }
: {}),
});
}
}
}
/**
* Walks the flat `entityTypes` namespace tree in `authoringContributions` and
* returns a map from discriminator string to the matching descriptor. The
* interpreter uses this to dispatch parsed extension blocks to their factory
* without naming any specific discriminator value (generic, by-discriminator).
*/
function buildEntityTypesByDiscriminator(
contributions: AuthoringContributions | undefined,
): ReadonlyMap<string, AuthoringEntityTypeDescriptor> {
const result = new Map<string, AuthoringEntityTypeDescriptor>();
const namespace = contributions?.entityTypes;
if (namespace === undefined) return result;
const walk = (node: AuthoringEntityTypeNamespace): void => {
for (const value of Object.values(node)) {
if (isAuthoringEntityTypeDescriptor(value)) {
result.set(value.discriminator, value);
} else if (typeof value === 'object' && value !== null) {
walk(value);
}
}
};
walk(namespace);
return result;
}
/**
* For a single PSL namespace, lowers all extension blocks (parsed by
* `namespacePslExtensionBlocks`) into IR entities via the registered
* factory for each block's discriminator. Groups results by discriminator
* (the entries key — one-string rule: discriminator === entries key).
*
* This pass is intentionally generic: no discriminator value is named here.
* The factory (registered by the target pack) owns all block-specific logic.
* A descriptor's factory output may also opt into value-set derivation via
* the SQL family's `SqlValueSetDerivingEntityTypeOutput.deriveValueSet` hook
* (probed by {@link deriveValueSetFromEntity}) — when present, the derived
* value-set is folded into the namespace's `valueSet` slot (keyed by block
* name), so a value-set-carrying pack entity (e.g. Postgres `native_enum`)
* contributes the value-set that drives value-set → codec typing without
* this pass inspecting a target-specific shape.
*
* The `namespaceId` is attached to the block before the factory call so the
* factory can record the namespace coordinate without the interpreter
* containing any target-specific knowledge about how namespace ids are used.
*/
function lowerExtensionBlocksForNamespace(
ns: NamespaceSymbol,
nsId: string,
entityTypesByDiscriminator: ReadonlyMap<string, AuthoringEntityTypeDescriptor>,
entityContext: AuthoringEntityContext,
): Readonly<Record<string, Readonly<Record<string, unknown>>>> {
const blockSymbols = Object.values(ns.blocks);
if (blockSymbols.length === 0) return {};
const result: Record<string, Record<string, unknown>> = {};
for (const blockSymbol of blockSymbols) {
const block = blockSymbol.block;
const descriptor = entityTypesByDiscriminator.get(block.kind);
if (descriptor === undefined) continue;
const annotatedBlock = { ...block, namespaceId: nsId };
const entity = instantiateAuthoringEntityType(
descriptor.discriminator,
descriptor,
[annotatedBlock],
entityContext,
);
if (entity === undefined) continue;
const entriesKey = descriptor.discriminator;
const slot = result[entriesKey] ?? {};
result[entriesKey] = slot;
slot[block.name] = entity;
const derivedValueSet = deriveValueSetFromEntity(descriptor.output, entity);
if (derivedValueSet !== undefined) {
const valueSetSlot = result['valueSet'] ?? {};
result['valueSet'] = valueSetSlot;
valueSetSlot[block.name] = derivedValueSet;
}
}
return result;
}
interface ProcessEnumDeclarationsInput {
readonly enumBlocks: readonly PslExtensionBlock[];
readonly sourceId: string;
readonly authoringContributions: AuthoringContributions | undefined;
readonly entityContext: AuthoringEntityContext;
readonly diagnostics: ContractSourceDiagnostic[];
}
function processEnumDeclarations(input: ProcessEnumDeclarationsInput): {
readonly enumHandles: Record<string, EnumTypeHandle>;
readonly enumTypeDescriptors: Map<string, ColumnDescriptor>;
} {
const enumHandles: Record<string, EnumTypeHandle> = {};
const enumTypeDescriptors = new Map<string, ColumnDescriptor>();
if (input.enumBlocks.length === 0) {
return { enumHandles, enumTypeDescriptors };
}
const enumDescriptor = getAuthoringEntity(input.authoringContributions, ['enum']);
if (!enumDescriptor) {
for (const decl of input.enumBlocks) {
input.diagnostics.push({
code: 'PSL_ENUM_MISSING_FACTORY',
message: `enum "${decl.name}" requires an "enum" entityType factory in the active authoring contributions`,
sourceId: input.sourceId,
span: decl.span,
});
}
return { enumHandles, enumTypeDescriptors };
}
for (const decl of input.enumBlocks) {
const handle = instantiateAuthoringEntityType<EnumTypeHandle | undefined>(
'enum',
enumDescriptor,
[decl],
input.entityContext,
);
if (handle === undefined || handle === null) continue;
enumHandles[decl.name] = handle;
enumTypeDescriptors.set(decl.name, {
codecId: handle.codecId,
nativeType: handle.nativeType,
});
}
return { enumHandles, enumTypeDescriptors };
}
/** Generic top-level blocks are supported only when a composed descriptor claims their keyword. */
function composedBlockKeywords(
authoringContributions: AuthoringContributions | undefined,
): ReadonlySet<string> {
const keywords = new Set<string>();
const descriptors: AuthoringPslBlockDescriptorNamespace =
authoringContributions?.pslBlockDescriptors ?? {};
for (const [keyword, value] of Object.entries(descriptors)) {
if (isAuthoringPslBlockDescriptor(value)) {
keywords.add(keyword);
}
}
return keywords;
}
interface BuildModelNodeInput {
readonly model: ModelSymbol;
readonly mapping: ModelNameMapping;
readonly modelMappings: ReadonlyMap<string, ModelNameMapping>;
/**
* Model mappings keyed by `(namespaceId, modelName)` coordinate. Used to
* resolve a namespace-qualified relation target (`auth.User`) to the exact
* model even when the bare name is shared across namespaces.
*/
readonly modelMappingsByCoordinate: ReadonlyMap<string, ModelNameMapping>;
readonly modelNames: Set<string>;
readonly compositeTypeNames: ReadonlySet<string>;
readonly enumTypeDescriptors: Map<string, ColumnDescriptor>;
readonly namedTypeDescriptors: Map<string, ColumnDescriptor>;
readonly composedExtensions: Set<string>;
/** Extension contracts keyed by space ID for cross-space FK table-name resolution. */
readonly composedExtensionContracts: ReadonlyMap<string, Contract>;
readonly familyId: string;
readonly targetId: string;
readonly authoringContributions: AuthoringContributions | undefined;
readonly defaultFunctionRegistry: ControlMutationDefaultRegistry;
readonly generatorDescriptorById: ReadonlyMap<string, MutationDefaultGeneratorDescriptor>;
readonly scalarTypeDescriptors: ReadonlyMap<string, ColumnDescriptor>;
readonly sourceId: string;
readonly sourceFile: SourceFile;
readonly symbolTable: SymbolTable;
readonly diagnostics: ContractSourceDiagnostic[];
/** Resolved namespace id keyed by model name — used to stamp the target namespace on FKs. */
readonly modelNamespaceIds: ReadonlyMap<string, string>;
readonly enumHandles?: ReadonlyMap<string, EnumTypeHandle>;
readonly capabilities: CapabilityMatrix;
/**
* Extension entities already lowered per namespace (the exact shape
* `lowerExtensionBlocksForNamespace` produces), keyed by namespace id then
* entries-slot discriminator then block name. Forwarded to
* `collectResolvedFields` for entity-ref type-constructor resolution (e.g.
* `pg.enum(Ref)`).
*/
readonly namespaceExtensionEntities?: ReadonlyMap<
string,
Readonly<Record<string, Readonly<Record<string, unknown>>>>
>;
/** Codec-id-keyed descriptor lookup — forwarded to `collectResolvedFields` for entity-ref type-constructor resolution (e.g. `pg.enum(Ref)`). */
readonly codecLookup?: CodecLookup;
}
interface BuildModelNodeResult {
readonly modelNode: ModelNode;
readonly fkRelationMetadata: FkRelationMetadata[];
readonly backrelationCandidates: ModelBackrelationCandidate[];
readonly resolvedFields: readonly ResolvedField[];
/** Cross-contract-space relation nodes that bypass the local back-relation matching. */
readonly crossSpaceRelations: RelationNode[];
}
function buildModelNodeFromPsl(input: BuildModelNodeInput): BuildModelNodeResult {
const { model, mapping, sourceId, diagnostics } = input;
const tableName = mapping.tableName;
const modelNamespaceId = input.modelNamespaceIds.get(model.name);
const namespaceExtensionEntitiesForModel =
modelNamespaceId !== undefined
? input.namespaceExtensionEntities?.get(modelNamespaceId)
: undefined;
const resolvedFields = collectResolvedFields({
model,
mapping,
enumTypeDescriptors: input.enumTypeDescriptors,
namedTypeDescriptors: input.namedTypeDescriptors,
modelNames: input.modelNames,
compositeTypeNames: input.compositeTypeNames,
composedExtensions: input.composedExtensions,
authoringContributions: input.authoringContributions,
familyId: input.familyId,
targetId: input.targetId,
defaultFunctionRegistry: input.defaultFunctionRegistry,
generatorDescriptorById: input.generatorDescriptorById,
diagnostics,
sourceId,
scalarTypeDescriptors: input.scalarTypeDescriptors,
...ifDefined('enumHandles', input.enumHandles),
capabilities: input.capabilities,
...ifDefined('namespaceId', modelNamespaceId),
...ifDefined('namespaceExtensionEntities', namespaceExtensionEntitiesForModel),
...ifDefined('codecLookup', input.codecLookup),
});
const inlineIdFields = resolvedFields.filter((field) => field.isId);
if (inlineIdFields.length > 1) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `Model "${model.name}" cannot declare inline @id on multiple fields; use model-level @@id([...]) for composite identity`,
sourceId,
span: model.span,
});
}
const singleInlineIdField = inlineIdFields.length === 1 ? inlineIdFields[0] : undefined;
let primaryKey: PrimaryKeyNode | undefined = singleInlineIdField
? {
columns: [singleInlineIdField.columnName],
...ifDefined('name', singleInlineIdField.idName),
}
: undefined;
const hasInlinePrimaryKey = primaryKey !== undefined;
let blockPrimaryKeyDeclared = false;
let controlPolicyDeclared = false;
let controlPolicy: ControlPolicy | undefined;
const resultBackrelationCandidates: ModelBackrelationCandidate[] = [];
for (const field of Object.values(model.fields)) {
if (!field.list || !input.modelNames.has(field.typeName)) {
continue;
}
const attributesValid = validateNavigationListFieldAttributes({
modelName: model.name,
field,
sourceId,
composedExtensions: input.composedExtensions,
authoringContributions: input.authoringContributions,
diagnostics,
familyId: input.familyId,
targetId: input.targetId,
});
const relationAttribute = getAttribute(field.attributes, 'relation');
let through: ParsedThrough | undefined;
let inverse: string | undefined;
if (relationAttribute) {
const parsedRelation = interpretRelationAttribute({
selfModel: model,
field,
symbols: input.symbolTable,
sourceFile: input.sourceFile,
sourceId,
diagnostics,
});
if (!parsedRelation) {
continue;
}
if (parsedRelation.fields || parsedRelation.references) {
diagnostics.push({
code: 'PSL_INVALID_RELATION_ATTRIBUTE',
message: `Backrelation list field "${model.name}.${field.name}" cannot declare fields/references or from/to; define them on the FK-side relation field`,
sourceId,
span: relationAttribute.span,
});
continue;
}
if (parsedRelation.onDelete || parsedRelation.onUpdate) {
diagnostics.push({
code: 'PSL_INVALID_RELATION_ATTRIBUTE',
message: `Backrelation list field "${model.name}.${field.name}" cannot declare onDelete/onUpdate; define referential actions on the FK-side relation field`,
sourceId,
span: relationAttribute.span,
});
continue;
}
through = parsedRelation.through;
inverse = parsedRelation.inverse;
}
if (!attributesValid) {
continue;
}
resultBackrelationCandidates.push({
modelName: model.name,
tableName,
field,
targetModelName: field.typeName,
...ifDefined('through', through),
...ifDefined('inverse', inverse),
});
}
const relationAttributes = Object.values(model.fields)
.map((field) => ({
field,
relation: getAttribute(field.attributes, 'relation'),
}))
.filter((entry): entry is { field: FieldSymbol; relation: ResolvedAttribute } =>
Boolean(entry.relation),
);
const uniqueConstraints: UniqueConstraintNode[] = resolvedFields
.filter((field) => field.isUnique)
.map((field) => ({
columns: [field.columnName],
...ifDefined('name', field.uniqueName),
}));
const indexNodes: IndexNode[] = [];
const foreignKeyNodes: ForeignKeyNode[] = [];
for (const modelAttribute of model.attributes) {
if (modelAttribute.name === 'map') {
continue;
}
if (modelAttribute.name === 'discriminator' || modelAttribute.name === 'base') {
continue;
}
if (modelAttribute.name === 'control') {
if (controlPolicyDeclared) {
diagnostics.push({
code: 'PSL_DUPLICATE_ATTRIBUTE',
message: `\`@@control\` declared more than once on model "${model.name}".`,
sourceId,
span: modelAttribute.span,
});
continue;
}
controlPolicyDeclared = true;
const parsed = parseControlPolicyAttribute({
attribute: modelAttribute,
sourceId,
diagnostics,
});
if (parsed !== undefined) {
controlPolicy = parsed;
}
continue;
}
const attributeLabel = `Model "${model.name}" @@${modelAttribute.name}`;
if (modelAttribute.name === 'id') {
if (blockPrimaryKeyDeclared) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `Model "${model.name}" declares @@id more than once`,
sourceId,
span: modelAttribute.span,
});
continue;
}
if (hasInlinePrimaryKey) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `Model "${model.name}" cannot declare both field-level @id and model-level @@id`,
sourceId,
span: modelAttribute.span,
});
blockPrimaryKeyDeclared = true;
continue;
}
const fieldNames = parseAttributeFieldList({
attribute: modelAttribute,
sourceId,
diagnostics,
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
entityLabel: attributeLabel,
});
if (!fieldNames) {
continue;
}
const duplicateFieldName = findDuplicateFieldName(fieldNames);
if (duplicateFieldName !== undefined) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `${attributeLabel} list contains duplicate field "${duplicateFieldName}"`,
sourceId,
span: modelAttribute.span,
});
continue;
}
const nullableFieldName = fieldNames.find((name) => model.fields[name]?.optional === true);
if (nullableFieldName !== undefined) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `${attributeLabel} cannot include optional field "${nullableFieldName}"; primary key columns must be NOT NULL`,
sourceId,
span: modelAttribute.span,
});
continue;
}
const columnNames = mapFieldNamesToColumns({
modelName: model.name,
fieldNames,
mapping,
sourceId,
diagnostics,
span: modelAttribute.span,
entityLabel: attributeLabel,
});
if (!columnNames) {
continue;
}
const constraintName = parseConstraintMapArgument({
attribute: modelAttribute,
sourceId,
diagnostics,
entityLabel: attributeLabel,
span: modelAttribute.span,
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
});
primaryKey = {
columns: columnNames,
...ifDefined('name', constraintName),
};
blockPrimaryKeyDeclared = true;
continue;
}
if (modelAttribute.name === 'unique' || modelAttribute.name === 'index') {
const fieldNames = parseAttributeFieldList({
attribute: modelAttribute,
sourceId,
diagnostics,
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
entityLabel: attributeLabel,
});
if (!fieldNames) {
continue;
}
const duplicateFieldName = findDuplicateFieldName(fieldNames);
if (duplicateFieldName !== undefined) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `${attributeLabel} list contains duplicate field "${duplicateFieldName}"`,
sourceId,
span: modelAttribute.span,
});
continue;
}
const columnNames = mapFieldNamesToColumns({
modelName: model.name,
fieldNames,
mapping,
sourceId,
diagnostics,
span: modelAttribute.span,
entityLabel: attributeLabel,
});
if (!columnNames) {
continue;
}
const constraintName = parseConstraintMapArgument({
attribute: modelAttribute,
sourceId,
diagnostics,
entityLabel: attributeLabel,
span: modelAttribute.span,
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
});
if (modelAttribute.name === 'unique') {
uniqueConstraints.push({
columns: columnNames,
...ifDefined('name', constraintName),
});
} else {
const indexEntityLabel = `Model "${model.name}" @@index`;
const rawTypeArg = getNamedArgument(modelAttribute, 'type');
let indexType: string | undefined;
if (rawTypeArg !== undefined) {
const parsed = parseQuotedStringLiteral(rawTypeArg);
if (parsed === undefined) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `${indexEntityLabel} type argument must be a quoted string literal`,
sourceId,
span: modelAttribute.span,
});
continue;
}
indexType = parsed;
}
const rawOptionsArg = getNamedArgument(modelAttribute, 'options');
let indexOptions: Record<string, string> | undefined;
if (rawOptionsArg !== undefined) {
if (indexType === undefined) {
diagnostics.push({
code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',
message: `${indexEntityLabel} options argument requires a type argument`,
sourceId,
span: modelAttribute.span,
});
continue;
}
const parsed = parseObjectLiteralStringMap({
raw: rawOptionsArg,
diagnostics,
sourceId,
span: modelAttribute.span,
entityLabel: indexEntityLabel,
});
if (parsed === undefined) {
continue;
}
indexOptions = parsed;
}
indexNodes.push({
columns: columnNames,
...ifDefined('name', constraintName),
...ifDefined('type', indexType),
...ifDefined('options', indexOptions),
});
}
continue;
}
const uncomposedNamespace = checkUncomposedNamespace(
modelAttribute.name,
input.composedExtensions,
{
familyId: input.familyId,
targetId: input.targetId,
authoringContributions: input.authoringContributions,
},
);
if (uncomposedNamespace) {
reportUncomposedNamespace({
subjectLabel: `Attribute "@@${modelAttribute.name}"`,
namespace: uncomposedNamespace,
sourceId,
span: modelAttribute.span,
diagnostics,
});
continue;
}
diagnostics.push({
code: 'PSL_UNSUPPORTED_MODEL_ATTRIBUTE',
message: `Model "${model.name}" uses unsupported attribute "@@${modelAttribute.name}"`,
sourceId,
span: modelAttribute.span,
});
}
const resultFkRelationMetadata: FkRelationMetadata[] = [];
const resultCrossSpaceRelations: RelationNode[] = [];
for (const relationAttribute of relationAttributes) {
const {
typeName: fieldTypeName,
typeNamespaceId: fieldTypeNamespaceId,
typeContractSpaceId: fieldTypeContractSpaceId,
} = relationAttribute.field;
if (relationAttribute.field.list) {
// F-list: cross-space list relations are explicitly unsupported (Option B does not
// navigate, so a list target makes no sense to carry). Emit a diagnostic instead of
// silently dropping the field — the author needs to know the field was ignored.
if (fieldTypeContractSpaceId !== undefined) {
diagnostics.push({
code: 'PSL_UNSUPPORTED_CROSS_SPACE_LIST',
message: `Relation field "${model.name}.${relationAttribute.field.name}" is a cross-space list relation (type "${fieldTypeContractSpaceId}:${fieldTypeNamespaceId !== undefined ? `${fieldTypeNamespaceId}.` : ''}${fieldTypeName}[]"). Cross-space relations must be singular in v0.1 — list cross-space relations are not supported.`,
sourceId,
span: relationAttribute.field.span,
});
}
continue;
}
// Cross-contract-space relation: the target model lives in a different contract space
// identified by `typeContractSpaceId` (e.g. `supabase:auth.User`).
if (fieldTypeContractSpaceId !== undefined) {
// Fail fast if the space has no entry in composedExtensionContracts (AC5 PSL half).
const extContractForSpace = input.composedExtensionContracts.get(fieldTypeContractSpaceId);
if (extContractForSpace === undefined) {
diagnostics.push({
code: 'PSL_UNKNOWN_CONTRACT_SPACE',
message: `Relation field "${model.name}.${relationAttribute.field.name}" references contract space "${fieldTypeContractSpaceId}" which is not declared in extensionPacks. Add "${fieldTypeContractSpaceId}" to extensionPacks in prisma-next.config.ts.`,
sourceId,
span: relationAttribute.field.span,
data: { space: fieldTypeContractSpaceId, suggestedPack: fieldTypeContractSpaceId },
});
continue;
}
const parsedRelation = interpretRelationAttribute({
selfModel: model,
field: relationAttribute.field,
symbols: input.symbolTable,
sourceFile: input.sourceFile,
sourceId,
diagnostics,
});
if (!parsedRelation) {
continue;
}
if (!parsedRelation.fields || !parsedRelation.references) {
diagnostics.push({
code: 'PSL_INVALID_RELATION_ATTRIBUTE',
message: `Cross-space relation field "${model.name}.${relationAttribute.field.name}" requires from and to arguments; to cannot be inferred across contract spaces`,
sourceId,
span: relationAttribute.relation.span,
});
continue;
}
const localColumns = mapFieldNamesToColumns({
modelName: model.name,
fieldNames: parsedRelation.fields,
mapping,
sourceId,
diagnostics,
span: relationAttribute.relation.span,
entityLabel: `Relation field "${model.name}.${relationAttribute.field.name}"`,
});
if (!localColumns) {
continue;
}
// For cross-space references the `references` list provides field names from the remote
// model. Since the interpreter has no access to the extension contract, these field names
// are treated as column names directly (matching the TS builder's cross-space path).
const referencedColumns = parsedRelation.references;
if (localColumns.length !== referencedColumns.length) {
diagnostics.push({
code: 'PSL_INVALID_RELATION_ATTRIBUTE',
message: `Relation field "${model.name}.${relationAttribute.field.name}" must provide the same number of fields and references`,
sourceId,
span: relationAttribute.relation.span,
});
continue;
}
const onDelete = parsedRelation.onDelete
? normalizeReferentialAction(parsedRelation.onDelete)
: undefined;
const onUpdate = parsedRelation.onUpdate
? normalizeReferentialAction(parsedRelation.onUpdate)
: undefined;
// Target namespace: use the colon-prefix namespace qualifier, or `__unbound__` when the
// no-namespace form is used (e.g. `supabase:User` → AC3).
const crossTargetNamespaceId = fieldTypeNamespaceId ?? '__unbound__';
// Target table name: resolved from the extension contract. The get() check above
// guarantees extContractForSpace is defined here; if the model or namespace is not
// found in it, emit PSL_UNKNOWN_CROSS_SPACE_TARGET (user typo).
const extContract = extContractForSpace;
const resolvedTable =
extContract.domain.namespaces[crossTargetNamespaceId]?.models[fieldTypeName]?.storage[
'table'
];
if (typeof resolvedTable !== 'string') {
const availableModels =
Object.keys(extContract.domain.namespaces[crossTargetNamespaceId]?.models ?? {}).join(
', ',
) || '(none)';
diagnostics.push({
code: 'PSL_UNKNOWN_CROSS_SPACE_TARGET',
message: `Relation field "${model.name}.${relationAttribute.field.name}" references model "${fieldTypeName}" in namespace "${crossTargetNamespaceId}" of space "${fieldTypeContractSpaceId}", but that model was not found in the extension contract. Available models: ${availableModels}`,
sourceId,
span: relationAttribute.field.span,
data: {
space: fieldTypeContractSpaceId,
namespace: crossTargetNamespaceId,
model: fieldTypeName,
},
});
continue;
}
const crossTargetTableName = resolvedTable;
foreignKeyNodes.push({
columns: localColumns,
references: {
model: fieldTypeName,
table: crossTargetTableName,
columns: referencedColumns,
namespaceId: crossTargetNamespaceId,
spaceId: fieldTypeContractSpaceId,