@aventara/prisma7-adapter 0.1.0-pilot.4 → 1.0.0-rc.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 (68) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/README.md +363 -317
  3. package/dist/discovery/artifact.loader.d.ts +4 -4
  4. package/dist/discovery/artifact.loader.js +17 -19
  5. package/dist/discovery/capability-surface.interface.d.ts +8 -1
  6. package/dist/discovery/capability.deriver.d.ts +6 -6
  7. package/dist/discovery/capability.deriver.js +6 -3
  8. package/dist/discovery/client-shape.verifier.d.ts +1 -1
  9. package/dist/discovery/client-shape.verifier.js +2 -2
  10. package/dist/discovery/discovery-artifact.interface.d.ts +38 -43
  11. package/dist/discovery/discovery-artifact.interface.js +1 -1
  12. package/dist/discovery/enum.mapper.d.ts +2 -2
  13. package/dist/discovery/field.mapper.d.ts +13 -13
  14. package/dist/discovery/field.mapper.js +11 -11
  15. package/dist/discovery/identifier.mapper.d.ts +7 -7
  16. package/dist/discovery/model.discoverer.d.ts +4 -4
  17. package/dist/discovery/model.discoverer.js +51 -20
  18. package/dist/discovery/operations.deriver.d.ts +6 -5
  19. package/dist/discovery/schema-facts.interface.d.ts +3 -3
  20. package/dist/discovery/schema.reader.d.ts +2 -2
  21. package/dist/discovery/schema.reader.js +5 -5
  22. package/dist/discovery/types.reader.d.ts +2 -2
  23. package/dist/discovery/types.reader.js +33 -22
  24. package/dist/discovery/vocabulary.dictionary.d.ts +14 -13
  25. package/dist/discovery/vocabulary.dictionary.js +1 -1
  26. package/dist/errors/error.normalizer.d.ts +11 -5
  27. package/dist/errors/error.normalizer.js +27 -5
  28. package/dist/errors/prisma-error.reader.d.ts +2 -0
  29. package/dist/errors/prisma-error.reader.js +1 -0
  30. package/dist/execution/first-variant.emulator.d.ts +4 -4
  31. package/dist/execution/first-variant.emulator.js +13 -9
  32. package/dist/execution/operation.executor.d.ts +9 -8
  33. package/dist/execution/operation.executor.js +17 -13
  34. package/dist/execution/result.shaper.d.ts +3 -3
  35. package/dist/execution/result.shaper.js +7 -7
  36. package/dist/execution/sql-statement.executor.d.ts +9 -0
  37. package/dist/execution/sql-statement.executor.js +58 -0
  38. package/dist/execution/transaction.executor.d.ts +8 -7
  39. package/dist/execution/transaction.executor.js +9 -5
  40. package/dist/generate/artifact.emitter.d.ts +5 -7
  41. package/dist/generate/artifact.emitter.js +11 -22
  42. package/dist/generate/discovery.cli.d.ts +3 -3
  43. package/dist/generate/discovery.cli.js +11 -11
  44. package/dist/generate/existence.gate.d.ts +4 -4
  45. package/dist/generate/existence.gate.js +4 -4
  46. package/dist/generate/index.d.ts +5 -5
  47. package/dist/generate/index.js +2 -2
  48. package/dist/generate/prisma.generate.d.ts +7 -8
  49. package/dist/generate/prisma.generate.js +11 -12
  50. package/dist/index.d.ts +4 -4
  51. package/dist/prisma-client.interface.d.ts +22 -8
  52. package/dist/prisma-client.interface.js +7 -0
  53. package/dist/prisma.adapter.d.ts +12 -12
  54. package/dist/prisma.adapter.js +12 -3
  55. package/dist/provider/provider-profile.d.ts +11 -11
  56. package/dist/translation/mutation.translator.d.ts +8 -8
  57. package/dist/translation/mutation.translator.js +31 -31
  58. package/dist/translation/operation.translator.d.ts +7 -6
  59. package/dist/translation/operation.translator.js +12 -12
  60. package/dist/translation/order-pagination.translator.d.ts +5 -5
  61. package/dist/translation/order-pagination.translator.js +16 -16
  62. package/dist/translation/projection.translator.d.ts +4 -4
  63. package/dist/translation/projection.translator.js +11 -11
  64. package/dist/translation/scalar.conversion.d.ts +9 -8
  65. package/dist/translation/scalar.conversion.js +11 -11
  66. package/dist/translation/where.translator.d.ts +5 -5
  67. package/dist/translation/where.translator.js +15 -15
  68. package/package.json +5 -4
@@ -1,15 +1,15 @@
1
- import { BUILT_IN_SCALARS, } from "@aventara/core";
1
+ import { BUILT_IN_SCALARS, } from "@aventara/core/internal";
2
2
  import { deriveRelationCapabilities, deriveScalarCapabilities, } from "./capability.deriver.js";
3
3
  import { mapPrismaEnum } from "./enum.mapper.js";
4
4
  import { crossCheckCreateOptional, projectPrismaField, } from "./field.mapper.js";
5
5
  import { mapPrismaIdentifiers } from "./identifier.mapper.js";
6
6
  import { deriveResourceOperations } from "./operations.deriver.js";
7
- export class PrismaModelCompositionError extends Error {
8
- name = "PrismaModelCompositionError";
7
+ export class AvPrismaModelCompositionError extends Error {
8
+ name = "AvPrismaModelCompositionError";
9
9
  diagnostics;
10
10
  constructor(diagnostics) {
11
11
  super([
12
- "discovery cannot compose an AdapterModel from this schema and client:",
12
+ "discovery cannot compose an AvAdapterModel from this schema and client:",
13
13
  ...diagnostics.map((diagnostic) => ` - ${diagnostic}`),
14
14
  ].join("\n"));
15
15
  this.diagnostics = diagnostics;
@@ -50,7 +50,14 @@ export function discoverPrismaModel(input) {
50
50
  referentialActions[name] = composed.referentialActions;
51
51
  }
52
52
  if (diagnostics.length > 0) {
53
- throw new PrismaModelCompositionError(diagnostics);
53
+ throw new AvPrismaModelCompositionError(diagnostics);
54
+ }
55
+ const requirements = composeCreateRequirements(declared, input.surface, resources);
56
+ for (const [name, stated] of Object.entries(requirements)) {
57
+ const resource = resources[name];
58
+ if (resource !== undefined) {
59
+ resources[name] = { ...resource, createRequirements: stated };
60
+ }
54
61
  }
55
62
  return {
56
63
  model: {
@@ -58,14 +65,16 @@ export function discoverPrismaModel(input) {
58
65
  enums,
59
66
  resources,
60
67
  transactions: input.transactions,
68
+ referenceWrites: PRISMA_REFERENCE_WRITES,
61
69
  },
62
70
  translation,
63
71
  referentialActions,
64
- createRequirements: composeCreateRequirements(declared, input.surface, resources),
65
72
  };
66
73
  }
74
+ const PRISMA_REFERENCE_WRITES = "uniform";
67
75
  function composeCreateRequirements(declared, surface, resources) {
68
- const table = {};
76
+ const groups = new Map();
77
+ const required = new Map();
69
78
  for (const [name, resource] of Object.entries(resources)) {
70
79
  const model = declared.get(name);
71
80
  const exposed = surface.resources[name];
@@ -81,8 +90,8 @@ function composeCreateRequirements(declared, surface, resources) {
81
90
  !scalar.createOptional);
82
91
  })
83
92
  .map(([field]) => field));
84
- const requirements = [];
85
93
  const references = new Set();
94
+ const resourceGroups = [];
86
95
  for (const field of model.fields) {
87
96
  const shape = resource.fields[field.name];
88
97
  if (shape?.kind !== "relation") {
@@ -95,23 +104,44 @@ function composeCreateRequirements(declared, surface, resources) {
95
104
  if (exposed.relationFields[field.name]?.createRequired !== true) {
96
105
  continue;
97
106
  }
98
- const orFields = owned.filter((scalar) => requiredScalars.has(scalar));
99
- if (orFields.length === 0) {
107
+ const [first, ...rest] = owned.filter((scalar) => requiredScalars.has(scalar));
108
+ if (first === undefined) {
100
109
  continue;
101
110
  }
102
- const inverse = inverseOf(declared, name, field);
103
- requirements.push({
104
- kind: "relation",
105
- relation: field.name,
106
- orFields,
107
- ...(inverse === undefined ? {} : { inverse }),
111
+ resourceGroups.push({
112
+ group: [field.name, first, ...rest],
113
+ inverse: inverseOf(declared, name, field),
108
114
  });
109
115
  }
110
- const fields = model.fields
116
+ groups.set(name, resourceGroups);
117
+ required.set(name, model.fields
111
118
  .map((field) => field.name)
112
- .filter((field) => requiredScalars.has(field) && !references.has(field))
113
- .map((field) => ({ kind: "field", field }));
114
- table[name] = [...fields, ...requirements];
119
+ .filter((field) => requiredScalars.has(field) && !references.has(field)));
120
+ }
121
+ const table = {};
122
+ for (const [name, resourceGroups] of groups) {
123
+ const [firstRequired, ...restRequired] = required.get(name) ?? [];
124
+ const [firstGroup, ...restGroups] = resourceGroups.map((entry) => entry.group);
125
+ const parentSupplies = {};
126
+ for (const { group, inverse } of resourceGroups) {
127
+ if (inverse !== undefined && resources[inverse.resource] !== undefined) {
128
+ const byRelation = parentSupplies[inverse.resource] ?? {};
129
+ byRelation[inverse.relation] = group;
130
+ parentSupplies[inverse.resource] = byRelation;
131
+ }
132
+ }
133
+ if (firstRequired === undefined && firstGroup === undefined) {
134
+ continue;
135
+ }
136
+ table[name] = {
137
+ ...(firstRequired === undefined
138
+ ? {}
139
+ : { required: [firstRequired, ...restRequired] }),
140
+ ...(firstGroup === undefined
141
+ ? {}
142
+ : { oneOf: [firstGroup, ...restGroups] }),
143
+ ...(Object.keys(parentSupplies).length === 0 ? {} : { parentSupplies }),
144
+ };
115
145
  }
116
146
  return table;
117
147
  }
@@ -217,6 +247,7 @@ function composeResource(input) {
217
247
  field: projection.edge.field,
218
248
  target: projection.edge.target,
219
249
  cardinality: projection.edge.cardinality,
250
+ references: [...(field.relation?.fields ?? [])],
220
251
  onDelete: projection.edge.onDelete,
221
252
  onUpdate: projection.edge.onUpdate,
222
253
  });
@@ -1,11 +1,12 @@
1
- import type { AdapterResource, ResourceOperations, TransactionCapability } from "@aventara/core";
2
- import type { PrismaAdapterModel } from "./discovery-artifact.interface.js";
3
- type DiscoveredIdentifiers = AdapterResource<PrismaAdapterModel>["identifiers"];
1
+ import type { AvResourceOperations, AvTransactionCapability } from "@aventara/core";
2
+ import type { AvAdapterResource } from "@aventara/core/internal";
3
+ import type { AvPrismaAdapterModel } from "./discovery-artifact.interface.js";
4
+ type DiscoveredIdentifiers = AvAdapterResource<AvPrismaAdapterModel>["identifiers"];
4
5
  export type ResourceOperationsInput = {
5
6
  readonly operations: readonly string[];
6
7
  /** The model's usable identifiers; empty means no unique addressing exists. */
7
8
  readonly identifiers: DiscoveredIdentifiers;
8
- readonly transactions: TransactionCapability;
9
+ readonly transactions: AvTransactionCapability;
9
10
  };
10
- export declare function deriveResourceOperations(input: ResourceOperationsInput): ResourceOperations;
11
+ export declare function deriveResourceOperations(input: ResourceOperationsInput): AvResourceOperations;
11
12
  export {};
@@ -1,4 +1,4 @@
1
- import type { PrismaReferentialAction } from "./discovery-artifact.interface.js";
1
+ import type { AvPrismaReferentialAction } from "./discovery-artifact.interface.js";
2
2
  /** Where a fact — or an unhandled construct — was found. One-based lines, as `prisma validate` reports them. */
3
3
  export type PrismaSchemaSite = {
4
4
  readonly file: string;
@@ -89,7 +89,7 @@ export type PrismaSchemaRelation = {
89
89
  * state, because an absent action and the explicitly-written default are one
90
90
  * fact about what a delete does.
91
91
  */
92
- readonly onDelete: PrismaReferentialAction | null;
92
+ readonly onDelete: AvPrismaReferentialAction | null;
93
93
  /** `@relation(onUpdate: …)`, resolved the same way. Read independently of `onDelete`. */
94
- readonly onUpdate: PrismaReferentialAction | null;
94
+ readonly onUpdate: AvPrismaReferentialAction | null;
95
95
  };
@@ -3,8 +3,8 @@ export type PrismaSchemaSource = {
3
3
  readonly file: string;
4
4
  readonly text: string;
5
5
  };
6
- export declare class PrismaSchemaReaderError extends Error {
7
- readonly name = "PrismaSchemaReaderError";
6
+ export declare class AvPrismaSchemaReaderError extends Error {
7
+ readonly name = "AvPrismaSchemaReaderError";
8
8
  }
9
9
  /**
10
10
  * Reads a schema file, or a schema **folder** (Prisma 7 accepts either).
@@ -1,7 +1,7 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- export class PrismaSchemaReaderError extends Error {
4
- name = "PrismaSchemaReaderError";
3
+ export class AvPrismaSchemaReaderError extends Error {
4
+ name = "AvPrismaSchemaReaderError";
5
5
  }
6
6
  const FIELD_ATTRIBUTES = new Set([
7
7
  "@id",
@@ -42,7 +42,7 @@ const BLOCK_KEYWORDS = new Set([
42
42
  ]);
43
43
  export async function readPrismaSchema(location) {
44
44
  const stats = await stat(location).catch((cause) => {
45
- throw new PrismaSchemaReaderError(`the Prisma schema at ${location} could not be read`, { cause });
45
+ throw new AvPrismaSchemaReaderError(`the Prisma schema at ${location} could not be read`, { cause });
46
46
  });
47
47
  const files = stats.isDirectory()
48
48
  ? (await readdir(location))
@@ -51,7 +51,7 @@ export async function readPrismaSchema(location) {
51
51
  .map((entry) => path.join(location, entry))
52
52
  : [location];
53
53
  if (files.length === 0) {
54
- throw new PrismaSchemaReaderError(`the Prisma schema folder at ${location} contains no .prisma file`);
54
+ throw new AvPrismaSchemaReaderError(`the Prisma schema folder at ${location} contains no .prisma file`);
55
55
  }
56
56
  const sources = [];
57
57
  for (const file of files) {
@@ -146,7 +146,7 @@ function readOneSource(source, enums, models, unhandled) {
146
146
  }
147
147
  }
148
148
  if (open !== null) {
149
- throw new PrismaSchemaReaderError(`${source.file} ends inside the block "${open.name}"`);
149
+ throw new AvPrismaSchemaReaderError(`${source.file} ends inside the block "${open.name}"`);
150
150
  }
151
151
  }
152
152
  function openBlock(line, site, record) {
@@ -5,8 +5,8 @@ export type PrismaTypesReadResult = {
5
5
  /** Every file under the client directory the reader actually opened. */
6
6
  readonly filesRead: readonly string[];
7
7
  };
8
- export declare class PrismaTypesReaderError extends Error {
9
- readonly name = "PrismaTypesReaderError";
8
+ export declare class AvPrismaTypesReaderError extends Error {
9
+ readonly name = "AvPrismaTypesReaderError";
10
10
  }
11
11
  export declare function readWrittenTypeArguments(checker: ts.TypeChecker, reference: ts.TypeReferenceNode): readonly string[];
12
12
  export declare function readPrismaCapabilitySurface(clientDirectory: string): PrismaTypesReadResult;
@@ -11,8 +11,8 @@ const NON_PAGINATION_EDGE_ARGUMENTS = new Set([
11
11
  "where",
12
12
  ]);
13
13
  const MANY_WRITE_OPERATION = /^(?:create|update|delete)Many(?:AndReturn)?$/;
14
- export class PrismaTypesReaderError extends Error {
15
- name = "PrismaTypesReaderError";
14
+ export class AvPrismaTypesReaderError extends Error {
15
+ name = "AvPrismaTypesReaderError";
16
16
  }
17
17
  export function readWrittenTypeArguments(checker, reference) {
18
18
  return (reference.typeArguments ?? []).map((argument) => checker.typeToString(checker.getTypeFromTypeNode(argument)));
@@ -21,7 +21,7 @@ export function readPrismaCapabilitySurface(clientDirectory) {
21
21
  const root = path.resolve(clientDirectory);
22
22
  const publicFiles = listPublicFiles(root);
23
23
  if (publicFiles.length === 0) {
24
- throw new PrismaTypesReaderError(`no generated Prisma client file was found under ${root}`);
24
+ throw new AvPrismaTypesReaderError(`no generated Prisma client file was found under ${root}`);
25
25
  }
26
26
  const filesRead = new Set();
27
27
  const host = createPublicOnlyHost(root, filesRead);
@@ -63,11 +63,11 @@ function createPublicOnlyHost(root, filesRead) {
63
63
  return undefined;
64
64
  }
65
65
  if (isPrivatePath(root, resolved)) {
66
- throw new PrismaTypesReaderError(`the types reader asked for ${path.relative(root, resolved)}, which is an internal file of the generated client that must not be imported`);
66
+ throw new AvPrismaTypesReaderError(`the types reader asked for ${path.relative(root, resolved)}, which is an internal file of the generated client that must not be imported`);
67
67
  }
68
68
  const text = readFileSync(resolved, "utf8");
69
69
  if (text.includes(RED_BANNER) || !text.includes(GREEN_BANNER)) {
70
- throw new PrismaTypesReaderError(`${path.relative(root, resolved)} does not carry Prisma's "${GREEN_BANNER}" banner`);
70
+ throw new AvPrismaTypesReaderError(`${path.relative(root, resolved)} does not carry Prisma's "${GREEN_BANNER}" banner`);
71
71
  }
72
72
  filesRead.add(resolved);
73
73
  return text;
@@ -100,7 +100,7 @@ function indexDeclarations(program, publicFiles) {
100
100
  for (const file of publicFiles) {
101
101
  const source = program.getSourceFile(file);
102
102
  if (source === undefined) {
103
- throw new PrismaTypesReaderError(`${file} did not enter the program`);
103
+ throw new AvPrismaTypesReaderError(`${file} did not enter the program`);
104
104
  }
105
105
  for (const statement of source.statements) {
106
106
  if (ts.isTypeAliasDeclaration(statement) ||
@@ -128,7 +128,7 @@ function projectionMembers(index, name) {
128
128
  ? written.typeArguments?.[0]
129
129
  : written;
130
130
  if (literal === undefined || !ts.isTypeLiteralNode(literal)) {
131
- throw new PrismaTypesReaderError(`${name} is declared by the generated client's types and is not a written object type, so its projection members cannot be read`);
131
+ throw new AvPrismaTypesReaderError(`${name} is declared by the generated client's types and is not a written object type, so its projection members cannot be read`);
132
132
  }
133
133
  return new Set(memberNames(literal.members.filter(ts.isPropertySignature)));
134
134
  }
@@ -197,14 +197,24 @@ function keysOfReferenced(index, node, accept) {
197
197
  }
198
198
  const members = membersOf(index, referencedName(reference));
199
199
  if (members === null) {
200
- throw new PrismaTypesReaderError(`${referencedName(reference)} is referenced by the generated client's types but declared nowhere in them`);
200
+ throw new AvPrismaTypesReaderError(`${referencedName(reference)} is referenced by the generated client's types but declared nowhere in them`);
201
201
  }
202
202
  return memberNames(members);
203
203
  }
204
+ function deleteManyTakesScalarWhere(index, node) {
205
+ const input = findReference(node, (n) => n.endsWith("NestedInput"));
206
+ if (input === null) {
207
+ return false;
208
+ }
209
+ const deleteMany = (membersOf(index, referencedName(input)) ?? []).find((member) => memberName(member) === "deleteMany");
210
+ return (deleteMany !== undefined &&
211
+ findReference(deleteMany.type, (n) => n.endsWith("ScalarWhereInput")) !==
212
+ null);
213
+ }
204
214
  function readEnums(program, root) {
205
215
  const source = program.getSourceFile(path.join(root, "enums.ts"));
206
216
  if (source === undefined) {
207
- throw new PrismaTypesReaderError(`enums.ts is absent from ${root}`);
217
+ throw new AvPrismaTypesReaderError(`enums.ts is absent from ${root}`);
208
218
  }
209
219
  const enums = {};
210
220
  for (const statement of source.statements) {
@@ -242,11 +252,11 @@ function readResources(checker, index) {
242
252
  function readResource(checker, index, model) {
243
253
  const payload = membersOf(index, `$${model}Payload`);
244
254
  if (payload === null) {
245
- throw new PrismaTypesReaderError(`$${model}Payload has no written members`);
255
+ throw new AvPrismaTypesReaderError(`$${model}Payload has no written members`);
246
256
  }
247
257
  const declaredName = payloadName(checker, payload);
248
258
  if (declaredName !== model) {
249
- throw new PrismaTypesReaderError(`$${model}Payload's own name literal is ${declaredName}`);
259
+ throw new AvPrismaTypesReaderError(`$${model}Payload's own name literal is ${declaredName}`);
250
260
  }
251
261
  const where = membersOf(index, `${model}WhereInput`) ?? [];
252
262
  const create = membersOf(index, `${model}CreateInput`) ?? [];
@@ -269,7 +279,7 @@ function readResource(checker, index, model) {
269
279
  function payloadName(checker, payload) {
270
280
  const member = payload.find((m) => memberName(m) === "name");
271
281
  if (member?.type === undefined) {
272
- throw new PrismaTypesReaderError("a payload carries no `name` member");
282
+ throw new AvPrismaTypesReaderError("a payload carries no `name` member");
273
283
  }
274
284
  return unquote(checker.typeToString(checker.getTypeFromTypeNode(member.type)));
275
285
  }
@@ -281,7 +291,7 @@ function readScalarFields(checker, index, model, payload, where, uncheckedCreate
281
291
  ? written.typeArguments?.[0]
282
292
  : undefined;
283
293
  if (literal === undefined || !ts.isTypeLiteralNode(literal)) {
284
- throw new PrismaTypesReaderError(`$${model}Payload.scalars is not a written object type`);
294
+ throw new AvPrismaTypesReaderError(`$${model}Payload.scalars is not a written object type`);
285
295
  }
286
296
  const names = [
287
297
  ...new Set([
@@ -293,7 +303,7 @@ function readScalarFields(checker, index, model, payload, where, uncheckedCreate
293
303
  for (const name of names) {
294
304
  const token = tokens.get(name);
295
305
  if (token === undefined) {
296
- throw new PrismaTypesReaderError(`${model}.${name} is a payload scalar with no ${model}FieldRefs entry`);
306
+ throw new AvPrismaTypesReaderError(`${model}.${name} is a payload scalar with no ${model}FieldRefs entry`);
297
307
  }
298
308
  const filter = findReference(where.get(name)?.type, (n) => n.endsWith("Filter"));
299
309
  const filterMembers = filter === null ? [] : (membersOf(index, referencedName(filter)) ?? []);
@@ -325,25 +335,25 @@ function readMutationOperations(index, model, stage, field, member) {
325
335
  }
326
336
  const members = membersOf(index, referencedName(reference));
327
337
  if (members === null) {
328
- throw new PrismaTypesReaderError(`${referencedName(reference)} is referenced by ${model}Unchecked${stage}Input.${field} and declared nowhere in the generated client's types`);
338
+ throw new AvPrismaTypesReaderError(`${referencedName(reference)} is referenced by ${model}Unchecked${stage}Input.${field} and declared nowhere in the generated client's types`);
329
339
  }
330
340
  return memberNames(members);
331
341
  }
332
342
  function readFieldRefTokens(checker, index, model) {
333
343
  const members = membersOf(index, `${model}FieldRefs`);
334
344
  if (members === null) {
335
- throw new PrismaTypesReaderError(`${model}FieldRefs is absent`);
345
+ throw new AvPrismaTypesReaderError(`${model}FieldRefs is absent`);
336
346
  }
337
347
  const tokens = new Map();
338
348
  for (const member of members) {
339
349
  const reference = findReference(member.type, (n) => n === "FieldRef");
340
350
  if (reference === null) {
341
- throw new PrismaTypesReaderError(`${model}FieldRefs.${memberName(member)} is not a FieldRef`);
351
+ throw new AvPrismaTypesReaderError(`${model}FieldRefs.${memberName(member)} is not a FieldRef`);
342
352
  }
343
353
  const written = readWrittenTypeArguments(checker, reference);
344
354
  const token = written[1];
345
355
  if (token === undefined) {
346
- throw new PrismaTypesReaderError(`${model}FieldRefs.${memberName(member)} carries no scalar token`);
356
+ throw new AvPrismaTypesReaderError(`${model}FieldRefs.${memberName(member)} carries no scalar token`);
347
357
  }
348
358
  tokens.set(memberName(member), unquote(token));
349
359
  }
@@ -367,11 +377,11 @@ function readRelationFields(checker, index, payload, where, create, update, incl
367
377
  part.literal.kind === ts.SyntaxKind.NullKeyword);
368
378
  const targetPayload = findReference(written, (n) => n.startsWith("$"));
369
379
  if (targetPayload === null) {
370
- throw new PrismaTypesReaderError(`a relation edge "${name}" references no payload`);
380
+ throw new AvPrismaTypesReaderError(`a relation edge "${name}" references no payload`);
371
381
  }
372
382
  const targetMembers = membersOf(index, referencedName(targetPayload));
373
383
  if (targetMembers === null) {
374
- throw new PrismaTypesReaderError(`${referencedName(targetPayload)} is declared nowhere in the generated client's types`);
384
+ throw new AvPrismaTypesReaderError(`${referencedName(targetPayload)} is declared nowhere in the generated client's types`);
375
385
  }
376
386
  const edge = findReference(include.get(name)?.type, (n) => n.endsWith("Args"));
377
387
  const edgeArguments = edge === null
@@ -386,6 +396,7 @@ function readRelationFields(checker, index, payload, where, create, update, incl
386
396
  createRequired: create.get(name) !== undefined &&
387
397
  create.get(name)?.questionToken === undefined,
388
398
  updateMutations: keysOfReferenced(index, update.get(name)?.type, (n) => n.endsWith("NestedInput")),
399
+ scalarNestedWriteFilter: deleteManyTakesScalarWhere(index, update.get(name)?.type),
389
400
  edgeArguments,
390
401
  pagination: edgeArguments.filter((argument) => !NON_PAGINATION_EDGE_ARGUMENTS.has(argument)),
391
402
  orderable: orderBy.has(name),
@@ -416,7 +427,7 @@ function readUniqueKeys(checker, index, model) {
416
427
  function readOperations(index, model) {
417
428
  const declaration = index.get(`${model}Delegate`);
418
429
  if (declaration === undefined || !ts.isInterfaceDeclaration(declaration)) {
419
- throw new PrismaTypesReaderError(`${model}Delegate is absent`);
430
+ throw new AvPrismaTypesReaderError(`${model}Delegate is absent`);
420
431
  }
421
432
  return declaration.members
422
433
  .filter(ts.isMethodSignature)
@@ -431,7 +442,7 @@ function readManyWriteArguments(index, model, operations) {
431
442
  const capitalised = operation[0]?.toUpperCase() + operation.slice(1);
432
443
  const members = membersOf(index, `${model}${capitalised}Args`);
433
444
  if (members === null) {
434
- throw new PrismaTypesReaderError(`${model}${capitalised}Args is absent although ${model}Delegate declares ${operation}`);
445
+ throw new AvPrismaTypesReaderError(`${model}${capitalised}Args is absent although ${model}Delegate declares ${operation}`);
435
446
  }
436
447
  arguments_[operation] = memberNames(members);
437
448
  }
@@ -1,4 +1,5 @@
1
- import type { AdapterLifecycleTrait, BuiltInScalar, PaginationCapability, RelationFilterCapability, RelationMutationDirective, ScalarFilterOperator, ScalarFormat, ScalarMutationDirective } from "@aventara/core";
1
+ import type { AvBuiltInScalar, AvPaginationCapability, AvRelationFilterCapability, AvRelationMutationDirective, AvScalarFilterOperator, AvScalarFormat, AvScalarMutationDirective } from "@aventara/core";
2
+ import type { AvAdapterLifecycleTrait } from "@aventara/core/internal";
2
3
  export type VocabularySource = "PSL" | "TYPE" | "RUN" | "DRIVER" | "CFG";
3
4
  export type VocabularyEntry = {
4
5
  readonly fact: string;
@@ -14,8 +15,8 @@ export type PrismaDiscoveryDiagnostic = {
14
15
  readonly message: string;
15
16
  };
16
17
  export type PrismaScalarMapping = {
17
- readonly scalar: BuiltInScalar;
18
- readonly format?: ScalarFormat;
18
+ readonly scalar: AvBuiltInScalar;
19
+ readonly format?: AvScalarFormat;
19
20
  };
20
21
  export type PrismaScalarTable = Readonly<Record<string, PrismaScalarMapping>>;
21
22
  /** Total and 1:1 over `BUILT_IN_SCALARS` **[CORE]**. */
@@ -24,7 +25,7 @@ export declare const PRISMA_SCALAR_TABLE: PrismaScalarTable;
24
25
  * The only `@db.*` spellings that **prove** a format, matched by exact written
25
26
  * spelling and never parsed.
26
27
  */
27
- export declare const PRISMA_NATIVE_FORMATS: Readonly<Record<string, ScalarFormat>>;
28
+ export declare const PRISMA_NATIVE_FORMATS: Readonly<Record<string, AvScalarFormat>>;
28
29
  export type PrismaEvidence = "RUN8" | "UNVERIFIED";
29
30
  export type PrismaDefaultRow = {
30
31
  /**
@@ -37,7 +38,7 @@ export type PrismaDefaultRow = {
37
38
  } | {
38
39
  readonly pattern: RegExp;
39
40
  };
40
- readonly traits: readonly AdapterLifecycleTrait[];
41
+ readonly traits: readonly AvAdapterLifecycleTrait[];
41
42
  readonly evidence: PrismaEvidence;
42
43
  };
43
44
  export declare const PRISMA_DEFAULT_TABLE: readonly PrismaDefaultRow[];
@@ -48,28 +49,28 @@ export declare const PRISMA_DEFAULT_TABLE: readonly PrismaDefaultRow[];
48
49
  * function is a build stop rather than a column Aventara quietly thinks the
49
50
  * client must supply.
50
51
  */
51
- export declare const PRISMA_UNMATCHED_DEFAULT_TRAITS: readonly AdapterLifecycleTrait[];
52
+ export declare const PRISMA_UNMATCHED_DEFAULT_TRAITS: readonly AvAdapterLifecycleTrait[];
52
53
  /**
53
54
  * The dictionary's other half: the point at which Prisma's spelling stops and
54
55
  * Aventara's begins.
55
56
  */
56
57
  /** `<Kind>Filter` / `<Kind>NullableFilter` / `Json[Nullable]Filter` keys. */
57
- export declare const PRISMA_FILTER_OPERATORS: Readonly<Record<string, ScalarFilterOperator>>;
58
+ export declare const PRISMA_FILTER_OPERATORS: Readonly<Record<string, AvScalarFilterOperator>>;
58
59
  /** `[Nullable]ScalarRelationFilter` and `ListRelationFilter` keys. */
59
- export declare const PRISMA_RELATION_FILTERS: Readonly<Record<string, RelationFilterCapability>>;
60
+ export declare const PRISMA_RELATION_FILTERS: Readonly<Record<string, AvRelationFilterCapability>>;
60
61
  /** `<Kind>FieldUpdateOperationsInput` and `<M><Stage><field>Input` keys. */
61
- export declare const PRISMA_SCALAR_DIRECTIVES: Readonly<Record<string, ScalarMutationDirective | null>>;
62
+ export declare const PRISMA_SCALAR_DIRECTIVES: Readonly<Record<string, AvScalarMutationDirective | null>>;
62
63
  /**
63
64
  * `<M>Update<edge>Without<M>NestedInput` / `<M>Create<edge>…NestedInput` keys.
64
65
  *
65
66
  * `createMany`, `updateMany` and `deleteMany` are `null`: they are nested BULK
66
- * writes, and `RelationMutationDirective` models per-row intent only **[CORE]**.
67
+ * writes, and `AvRelationMutationDirective` models per-row intent only **[CORE]**.
67
68
  * Aventara expresses the same effect by addressing the target Resource, so
68
69
  * advertising them would promise an argument no directive could carry.
69
70
  */
70
- export declare const PRISMA_RELATION_DIRECTIVES: Readonly<Record<string, RelationMutationDirective | null>>;
71
+ export declare const PRISMA_RELATION_DIRECTIVES: Readonly<Record<string, AvRelationMutationDirective | null>>;
71
72
  /**
72
- * `<M>$<edge>Args` keys, valued in `PaginationCapability`.
73
+ * `<M>$<edge>Args` keys, valued in `AvPaginationCapability`.
73
74
  *
74
75
  * `null` means the argument is read for something else, or for nothing:
75
76
  * `orderBy` answers `order`, `where` answers the `nested` filter capability,
@@ -77,7 +78,7 @@ export declare const PRISMA_RELATION_DIRECTIVES: Readonly<Record<string, Relatio
77
78
  * Aventara has no word for. The table is total over the keys both clients write,
78
79
  * so a new edge argument at 7.11 is an unrecognised key rather than a silent drop.
79
80
  */
80
- export declare const PRISMA_EDGE_ARGUMENTS: Readonly<Record<string, PaginationCapability | null>>;
81
+ export declare const PRISMA_EDGE_ARGUMENTS: Readonly<Record<string, AvPaginationCapability | null>>;
81
82
  /** `_count` on `<M>Include` / `<M>CountOutputType`. */
82
83
  export declare const PRISMA_REDUCERS: Readonly<Record<string, "$count">>;
83
84
  export type ObservedValueShape = {
@@ -67,7 +67,7 @@ export const VOCABULARY = [
67
67
  {
68
68
  fact: "COMPUTED_* / VIRTUAL",
69
69
  sources: ["CFG"],
70
- rule: "Outside `AdapterLifecycleTrait` by construction [CORE]; the adapter cannot emit them.",
70
+ rule: "Outside `AvAdapterLifecycleTrait` by construction [CORE]; the adapter cannot emit them.",
71
71
  },
72
72
  ];
73
73
  export const PRISMA_SCALAR_TABLE = {
@@ -1,11 +1,11 @@
1
- import { FrameworkError, type OperationErrorCode, type OperationIdentity } from "@aventara/core";
1
+ import { AvError, type AvOperationErrorCode, type AvOperationIdentity } from "@aventara/core";
2
2
  import { type PrismaConstraintSubject } from "./prisma-error.reader.js";
3
3
  /** The three answers a Prisma failure can get. */
4
4
  export type PrismaErrorClassification = {
5
5
  readonly kind: "absence";
6
6
  } | {
7
7
  readonly kind: "outcome";
8
- readonly code: OperationErrorCode;
8
+ readonly code: AvOperationErrorCode;
9
9
  } | {
10
10
  readonly kind: "unclassified";
11
11
  };
@@ -15,7 +15,7 @@ type PrismaAbsenceRule = {
15
15
  };
16
16
  type PrismaErrorRule = {
17
17
  /** The outcome this code answers. */
18
- readonly outcome: OperationErrorCode;
18
+ readonly outcome: AvOperationErrorCode;
19
19
  readonly absence?: PrismaAbsenceRule;
20
20
  };
21
21
  export type PrismaErrorTable = Readonly<Record<string, PrismaErrorRule>>;
@@ -24,9 +24,15 @@ export declare const PRISMA_ERROR_TABLE_MAJOR = "7";
24
24
  /** Every code here was induced above. */
25
25
  export declare const PRISMA_ERROR_TABLE: PrismaErrorTable;
26
26
  /** Classifies one failed Prisma call. */
27
- export declare function classifyPrismaError(error: unknown, operation: Pick<OperationIdentity, "family" | "variant">): PrismaErrorClassification;
27
+ export declare function classifyPrismaError(error: unknown, operation: Pick<AvOperationIdentity, "family" | "variant">): PrismaErrorClassification;
28
+ /**
29
+ * Classifies one failed `appTx.$sql` statement: a `P2010` by its driver-adapter
30
+ * kind, any other P-code by the table, never forgiven as an absence (a statement
31
+ * selects no record a strict-unique variant could miss).
32
+ */
33
+ export declare function classifyPrismaStatementError(error: unknown): PrismaErrorClassification;
28
34
  /** The deliberate failure an `outcome` classification stands for. */
29
- export declare function prismaOutcomeFailure(code: OperationErrorCode): FrameworkError;
35
+ export declare function prismaOutcomeFailure(code: AvOperationErrorCode): AvError;
30
36
  export type PrismaConflictSubject = {
31
37
  readonly code: string;
32
38
  readonly model: string | undefined;
@@ -1,4 +1,4 @@
1
- import { FrameworkError, } from "@aventara/core";
1
+ import { AvError, } from "@aventara/core";
2
2
  import { readPrismaError, } from "./prisma-error.reader.js";
3
3
  export const PRISMA_ERROR_TABLE_MAJOR = "7";
4
4
  export const PRISMA_ERROR_TABLE = {
@@ -6,9 +6,9 @@ export const PRISMA_ERROR_TABLE = {
6
6
  P2003: { outcome: "A2008" },
7
7
  P2014: { outcome: "A2008" },
8
8
  P2034: { outcome: "A2013" },
9
- P2018: { outcome: "A2004" },
9
+ P2018: { outcome: "A2003" },
10
10
  P2025: {
11
- outcome: "A2004",
11
+ outcome: "A2003",
12
12
  absence: {
13
13
  variants: ["update.unique", "delete.unique"],
14
14
  subject: "root-record",
@@ -18,7 +18,7 @@ export const PRISMA_ERROR_TABLE = {
18
18
  const OUTCOME_MESSAGES = {
19
19
  A2008: "The operation conflicts with the current state of the resource.",
20
20
  A2013: "Another operation modified the same state concurrently, so this operation was not applied and nothing was written.",
21
- A2004: "The operation's arguments referenced a record that does not exist.",
21
+ A2003: "The operation's arguments referenced a record that does not exist.",
22
22
  };
23
23
  function matchesAbsenceSubject(subject, facts) {
24
24
  switch (subject) {
@@ -47,8 +47,30 @@ export function classifyPrismaError(error, operation) {
47
47
  ? { kind: "absence" }
48
48
  : { kind: "outcome", code: rule.outcome };
49
49
  }
50
+ const PRISMA_RAW_QUERY_KINDS = {
51
+ UniqueConstraintViolation: "A2008",
52
+ ForeignKeyConstraintViolation: "A2008",
53
+ };
54
+ export function classifyPrismaStatementError(error) {
55
+ const facts = readPrismaError(error);
56
+ if (facts.code === "P2010") {
57
+ const kind = facts.driverAdapterKind;
58
+ const code = kind !== undefined && Object.hasOwn(PRISMA_RAW_QUERY_KINDS, kind)
59
+ ? PRISMA_RAW_QUERY_KINDS[kind]
60
+ : undefined;
61
+ return code === undefined
62
+ ? { kind: "unclassified" }
63
+ : { kind: "outcome", code };
64
+ }
65
+ const rule = facts.code !== undefined && Object.hasOwn(PRISMA_ERROR_TABLE, facts.code)
66
+ ? PRISMA_ERROR_TABLE[facts.code]
67
+ : undefined;
68
+ return rule === undefined
69
+ ? { kind: "unclassified" }
70
+ : { kind: "outcome", code: rule.outcome };
71
+ }
50
72
  export function prismaOutcomeFailure(code) {
51
- return new FrameworkError(code, {
73
+ return new AvError(code, {
52
74
  message: OUTCOME_MESSAGES[code] ?? "The operation could not be completed.",
53
75
  });
54
76
  }
@@ -24,6 +24,8 @@ export type PrismaErrorFacts = {
24
24
  readonly relatedModel: string | undefined;
25
25
  /** `meta.driverAdapterError.cause.constraint`, read structurally. */
26
26
  readonly constraint: PrismaConstraintSubject | undefined;
27
+ /** `meta.driverAdapterError.cause.kind`, e.g. `"UniqueConstraintViolation"`. */
28
+ readonly driverAdapterKind: string | undefined;
27
29
  readonly legacyTarget: readonly string[] | undefined;
28
30
  };
29
31
  /**
@@ -71,6 +71,7 @@ export function readPrismaError(error) {
71
71
  relation: ownString(meta, "relation"),
72
72
  relatedModel: ownString(meta, "model"),
73
73
  constraint: readConstraint(meta),
74
+ driverAdapterKind: ownString(ownValue(ownValue(meta, "driverAdapterError"), "cause"), "kind"),
74
75
  legacyTarget: ownStringList(meta, "target"),
75
76
  };
76
77
  }
@@ -1,11 +1,11 @@
1
- import { FrameworkError } from "@aventara/core";
1
+ import { AvError } from "@aventara/core";
2
2
  import type { PrismaIdentifierAddress } from "../discovery/discovery-artifact.interface.js";
3
3
  import type { PrismaCall } from "../translation/operation.translator.js";
4
4
  /**
5
5
  * The lost-row conflict: the read selected a row and the re-asserted write
6
6
  * matched none, so **nothing was written** and a retry may succeed.
7
7
  */
8
- export declare function lostRowConflict(): FrameworkError;
8
+ export declare function lostRowConflict(): AvError;
9
9
  /** Issues one of the emulation's two statements. */
10
10
  export type FirstVariantIssuer = (call: PrismaCall, step: "read" | "write") => Promise<unknown>;
11
11
  /** How the emulation's two statements are issued, and against which client. */
@@ -17,8 +17,8 @@ export type FirstVariantEmulation = {
17
17
  readonly inUnit: <T>(work: (issue: FirstVariantIssuer) => Promise<T>) => Promise<T>;
18
18
  };
19
19
  /** A plan that is not the two-step shape this module manufactures. */
20
- export declare class PrismaEmulationError extends Error {
21
- readonly name = "PrismaEmulationError";
20
+ export declare class AvPrismaEmulationError extends Error {
21
+ readonly name = "AvPrismaEmulationError";
22
22
  }
23
23
  /**
24
24
  * Runs one first-style variant.