@corpdk/dal-codegen 2026.10.0-alpha.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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cli.d.ts +2 -0
  3. package/dist/cli.js +26 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/comments.d.ts +5 -0
  6. package/dist/comments.js +124 -0
  7. package/dist/comments.js.map +1 -0
  8. package/dist/config.d.ts +25 -0
  9. package/dist/config.js +18 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/constraint-infer.d.ts +11 -0
  12. package/dist/constraint-infer.js +79 -0
  13. package/dist/constraint-infer.js.map +1 -0
  14. package/dist/entity-lint.d.ts +14 -0
  15. package/dist/entity-lint.js +134 -0
  16. package/dist/entity-lint.js.map +1 -0
  17. package/dist/filter-index-lint.d.ts +9 -0
  18. package/dist/filter-index-lint.js +57 -0
  19. package/dist/filter-index-lint.js.map +1 -0
  20. package/dist/generate.d.ts +8 -0
  21. package/dist/generate.js +122 -0
  22. package/dist/generate.js.map +1 -0
  23. package/dist/generated/entity-records.d.ts +25 -0
  24. package/dist/generated/entity-records.js +2 -0
  25. package/dist/generated/entity-records.js.map +1 -0
  26. package/dist/generated/graphql-codegen.mappers.d.ts +6 -0
  27. package/dist/generated/graphql-codegen.mappers.js +8 -0
  28. package/dist/generated/graphql-codegen.mappers.js.map +1 -0
  29. package/dist/generators/app-bootstrap.d.ts +6 -0
  30. package/dist/generators/app-bootstrap.js +74 -0
  31. package/dist/generators/app-bootstrap.js.map +1 -0
  32. package/dist/generators/bootstrap-schema.d.ts +9 -0
  33. package/dist/generators/bootstrap-schema.js +73 -0
  34. package/dist/generators/bootstrap-schema.js.map +1 -0
  35. package/dist/generators/entity-records.d.ts +3 -0
  36. package/dist/generators/entity-records.js +16 -0
  37. package/dist/generators/entity-records.js.map +1 -0
  38. package/dist/generators/entity-schema.d.ts +12 -0
  39. package/dist/generators/entity-schema.js +440 -0
  40. package/dist/generators/entity-schema.js.map +1 -0
  41. package/dist/generators/graphql-mappers.d.ts +3 -0
  42. package/dist/generators/graphql-mappers.js +13 -0
  43. package/dist/generators/graphql-mappers.js.map +1 -0
  44. package/dist/generators/pubsub.d.ts +3 -0
  45. package/dist/generators/pubsub.js +26 -0
  46. package/dist/generators/pubsub.js.map +1 -0
  47. package/dist/generators/repository-scalars.d.ts +12 -0
  48. package/dist/generators/repository-scalars.js +222 -0
  49. package/dist/generators/repository-scalars.js.map +1 -0
  50. package/dist/generators/repository.d.ts +7 -0
  51. package/dist/generators/repository.js +717 -0
  52. package/dist/generators/repository.js.map +1 -0
  53. package/dist/generators/resolvers.d.ts +2 -0
  54. package/dist/generators/resolvers.js +361 -0
  55. package/dist/generators/resolvers.js.map +1 -0
  56. package/dist/generators/schema-builder.d.ts +4 -0
  57. package/dist/generators/schema-builder.js +83 -0
  58. package/dist/generators/schema-builder.js.map +1 -0
  59. package/dist/generators/schema-registry.d.ts +19 -0
  60. package/dist/generators/schema-registry.js +488 -0
  61. package/dist/generators/schema-registry.js.map +1 -0
  62. package/dist/generators/schema-utils.d.ts +9 -0
  63. package/dist/generators/schema-utils.js +94 -0
  64. package/dist/generators/schema-utils.js.map +1 -0
  65. package/dist/generators/sdl.d.ts +7 -0
  66. package/dist/generators/sdl.js +24 -0
  67. package/dist/generators/sdl.js.map +1 -0
  68. package/dist/index-coverage.d.ts +10 -0
  69. package/dist/index-coverage.js +38 -0
  70. package/dist/index-coverage.js.map +1 -0
  71. package/dist/index.d.ts +5 -0
  72. package/dist/index.js +4 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/lint-cli.d.ts +2 -0
  75. package/dist/lint-cli.js +25 -0
  76. package/dist/lint-cli.js.map +1 -0
  77. package/dist/lint-types.d.ts +8 -0
  78. package/dist/lint-types.js +2 -0
  79. package/dist/lint-types.js.map +1 -0
  80. package/dist/model.d.ts +56 -0
  81. package/dist/model.js +209 -0
  82. package/dist/model.js.map +1 -0
  83. package/dist/parse-mode.d.ts +3 -0
  84. package/dist/parse-mode.js +21 -0
  85. package/dist/parse-mode.js.map +1 -0
  86. package/dist/relations.d.ts +2 -0
  87. package/dist/relations.js +167 -0
  88. package/dist/relations.js.map +1 -0
  89. package/dist/schema-loader.d.ts +1 -0
  90. package/dist/schema-loader.js +16 -0
  91. package/dist/schema-loader.js.map +1 -0
  92. package/package.json +43 -0
@@ -0,0 +1,717 @@
1
+ import { internalRecordColumns } from "./schema-utils.js";
2
+ import { assignCreateValue, assignUpdateValue, constraintMetadataBlock, cursorDeserializeBody, cursorSerializeBody, dalCoreImportBlock, mapRowFieldLine, tsTypeForColumn, } from "./repository-scalars.js";
3
+ function collectRelationTableImports(entity, entities) {
4
+ const imports = new Set();
5
+ for (const rel of entity.relations) {
6
+ if (rel.targetExportName)
7
+ imports.add(rel.targetExportName);
8
+ if (rel.joinTableExportName)
9
+ imports.add(rel.joinTableExportName);
10
+ if (rel.kind === "one-to-many" || rel.kind === "many-to-many") {
11
+ const child = entities.find((e) => e.exportName === (rel.joinTableExportName ?? rel.targetExportName));
12
+ if (child)
13
+ imports.add(child.exportName);
14
+ }
15
+ if (rel.kind === "many-to-many") {
16
+ imports.add(rel.targetExportName);
17
+ }
18
+ }
19
+ return imports;
20
+ }
21
+ function columnDescriptorLines(entityExport, entity) {
22
+ return entity.columns
23
+ .filter((c) => c.drizzleKey !== "deletedAt" && c.drizzleKey !== "deletedBy")
24
+ .map((c) => `{ graphqlName: "${c.graphqlName}", drizzleKey: "${c.drizzleKey}", kind: "${c.kind}" as const, column: ${entityExport}.${c.drizzleKey} }`)
25
+ .join(",\n ");
26
+ }
27
+ function relationsVarName(exportName) {
28
+ return `${exportName}Relations`;
29
+ }
30
+ function relVarName(exportName, fieldName) {
31
+ return `${exportName}_${fieldName}Rel`;
32
+ }
33
+ function resolveRelationTargets(rel, entities) {
34
+ const entityByExport = new Map(entities.map((e) => [e.exportName, e]));
35
+ const target = entityByExport.get(rel.targetExportName);
36
+ let child;
37
+ if (rel.kind === "one-to-many") {
38
+ child = target;
39
+ }
40
+ else if (rel.kind === "many-to-many" && rel.joinTableExportName) {
41
+ child = entityByExport.get(rel.joinTableExportName);
42
+ }
43
+ const m2mTarget = rel.kind === "many-to-many" ? target : undefined;
44
+ const targetExport = rel.kind === "many-to-many" ? (m2mTarget?.exportName ?? rel.targetExportName) : rel.targetExportName;
45
+ const targetEntity = entityByExport.get(targetExport) ?? target;
46
+ return { targetEntity, childEntity: child };
47
+ }
48
+ function relationDescriptorWiringLines(rel, entity, varName, targetEntity, childEntity) {
49
+ const lines = [];
50
+ if ((rel.kind === "many-to-one" ||
51
+ rel.kind === "many-to-many" ||
52
+ (rel.kind === "one-to-one" && rel.ownerFkDrizzleKey)) &&
53
+ targetEntity) {
54
+ lines.push(`${varName}.targetRelations = ${relationsVarName(targetEntity.exportName)};`);
55
+ }
56
+ if (rel.kind === "one-to-many" && childEntity) {
57
+ lines.push(`${varName}.childRelations = ${relationsVarName(childEntity.exportName)};`);
58
+ }
59
+ if (rel.kind === "one-to-one" && rel.childFkDrizzleKey && targetEntity) {
60
+ lines.push(`${varName}.targetRelations = ${relationsVarName(targetEntity.exportName)};`);
61
+ }
62
+ return lines;
63
+ }
64
+ function buildRelationDescriptorObject(rel, entities) {
65
+ const { targetEntity, childEntity } = resolveRelationTargets(rel, entities);
66
+ return `{
67
+ fieldName: "${rel.fieldName}",
68
+ kind: "${rel.kind}" as const,
69
+ ownerFkDrizzleKey: ${rel.ownerFkDrizzleKey ? `"${rel.ownerFkDrizzleKey}"` : "undefined"},
70
+ childFkDrizzleKey: ${rel.childFkDrizzleKey ? `"${rel.childFkDrizzleKey}"` : "undefined"},
71
+ joinOwnerFkDrizzleKey: ${rel.joinOwnerFkDrizzleKey ? `"${rel.joinOwnerFkDrizzleKey}"` : "undefined"},
72
+ joinTargetFkDrizzleKey: ${rel.joinTargetFkDrizzleKey ? `"${rel.joinTargetFkDrizzleKey}"` : "undefined"},
73
+ targetTable: ${targetEntity?.exportName ?? rel.targetExportName},
74
+ targetColumns: [
75
+ ${targetEntity ? columnDescriptorLines(targetEntity.exportName, targetEntity) : ""}
76
+ ],
77
+ childTable: ${childEntity ? childEntity.exportName : "undefined"},
78
+ childColumns: ${childEntity ? `[\n ${columnDescriptorLines(childEntity.exportName, childEntity)}\n ]` : "undefined"},
79
+ joinTable: ${rel.joinTableExportName ?? "undefined"},
80
+ joinColumns: undefined,
81
+ targetSoftDelete: ${targetEntity?.deleteStrategy === "soft"},
82
+ childSoftDelete: ${childEntity?.deleteStrategy === "soft"},
83
+ filterable: true,
84
+ }`;
85
+ }
86
+ export function generateRelationDescriptorsModule(entities) {
87
+ const schemaImports = new Set();
88
+ for (const entity of entities) {
89
+ schemaImports.add(entity.exportName);
90
+ for (const rel of entity.relations) {
91
+ if (rel.targetExportName)
92
+ schemaImports.add(rel.targetExportName);
93
+ if (rel.joinTableExportName)
94
+ schemaImports.add(rel.joinTableExportName);
95
+ }
96
+ }
97
+ const relDecls = [];
98
+ const arrayDecls = [];
99
+ const wiring = [];
100
+ const mapEntries = [];
101
+ for (const entity of entities) {
102
+ const filterable = entity.relations.filter((r) => r.filterable);
103
+ const relVars = [];
104
+ for (const rel of filterable) {
105
+ const varName = relVarName(entity.exportName, rel.fieldName);
106
+ relDecls.push(`const ${varName}: RelationDescriptor = ${buildRelationDescriptorObject(rel, entities)};`);
107
+ relVars.push(varName);
108
+ const { targetEntity, childEntity } = resolveRelationTargets(rel, entities);
109
+ wiring.push(...relationDescriptorWiringLines(rel, entity, varName, targetEntity, childEntity));
110
+ }
111
+ const arrayName = relationsVarName(entity.exportName);
112
+ if (relVars.length === 0) {
113
+ arrayDecls.push(`const ${arrayName}: RelationDescriptor[] = [];`);
114
+ }
115
+ else {
116
+ arrayDecls.push(`const ${arrayName}: RelationDescriptor[] = [\n ${relVars.join(",\n ")},\n];`);
117
+ }
118
+ mapEntries.push(` [${entity.exportName}, ${arrayName}],`);
119
+ }
120
+ return `// AUTO-GENERATED by @corpdk/dal-codegen — do not edit
121
+ import type { RelationDescriptor } from "@corpdk/dal-core";
122
+ import type { Table } from "drizzle-orm";
123
+ import { ${[...schemaImports].sort((a, b) => a.localeCompare(b)).join(", ")} } from "../../../db/schema/index.js";
124
+
125
+ ${relDecls.join("\n\n")}
126
+
127
+ ${arrayDecls.join("\n\n")}
128
+
129
+ ${wiring.join("\n")}
130
+
131
+ export const RELATION_DESCRIPTORS_BY_TABLE = new Map<Table, RelationDescriptor[]>([
132
+ ${mapEntries.join("\n")}
133
+ ]);
134
+ `;
135
+ }
136
+ function hasParentBatchMethods(entity, entities) {
137
+ for (const parent of entities) {
138
+ for (const rel of parent.relations) {
139
+ if (rel.targetExportName !== entity.exportName || !rel.childFkDrizzleKey)
140
+ continue;
141
+ if (rel.kind === "one-to-many" || (rel.kind === "one-to-one" && !rel.ownerFkDrizzleKey)) {
142
+ return true;
143
+ }
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+ function drizzleImportLine(entity, entities) {
149
+ const soft = entity.deleteStrategy === "soft";
150
+ const hasM2m = entity.relations.some((r) => r.kind === "many-to-many");
151
+ const m2mTargetSoft = entity.relations.some((r) => {
152
+ if (r.kind !== "many-to-many")
153
+ return false;
154
+ const target = entities.find((e) => e.exportName === r.targetExportName);
155
+ return target?.deleteStrategy === "soft";
156
+ });
157
+ const m2mJoinSoft = entity.relations.some((r) => {
158
+ if (r.kind !== "many-to-many" || !r.joinTableExportName)
159
+ return false;
160
+ const join = entities.find((e) => e.exportName === r.joinTableExportName);
161
+ return join?.deleteStrategy === "soft";
162
+ });
163
+ const parts = ["eq", "inArray"];
164
+ if (soft || m2mTargetSoft || m2mJoinSoft || hasM2m)
165
+ parts.push("and");
166
+ if (soft || m2mTargetSoft || m2mJoinSoft)
167
+ parts.push("isNull");
168
+ return `import { ${parts.join(", ")} } from "drizzle-orm";`;
169
+ }
170
+ function manyToManyTargetRecordImports(entity, entities) {
171
+ const typeNames = new Set([`${entity.graphqlType}Record`]);
172
+ for (const rel of entity.relations) {
173
+ if (rel.kind !== "many-to-many")
174
+ continue;
175
+ const target = entities.find((e) => e.exportName === rel.targetExportName);
176
+ if (!target)
177
+ continue;
178
+ typeNames.add(`${target.graphqlType}Record`);
179
+ }
180
+ const sorted = [...typeNames].sort((a, b) => a.localeCompare(b));
181
+ return `import type { ${sorted.join(", ")} } from "../../entity-records.js";`;
182
+ }
183
+ function activeRowWhere(idExpr, soft) {
184
+ return soft ? `and(eq(table.id, ${idExpr}), isNull(table.deletedAt))!` : `eq(table.id, ${idExpr})`;
185
+ }
186
+ function buildRelationProjectionHints(entity) {
187
+ const hints = entity.relations
188
+ .filter((r) => r.ownerFkDrizzleKey)
189
+ .map((r) => ` { fieldName: "${r.fieldName}", ownerFkDrizzleKey: "${r.ownerFkDrizzleKey}" },`);
190
+ if (hints.length === 0)
191
+ return "[]";
192
+ return `[\n${hints.join("\n")}\n]`;
193
+ }
194
+ function parentBatchMethods(entity, entities) {
195
+ const soft = entity.deleteStrategy === "soft";
196
+ const batchWhere = (fk) => soft
197
+ ? `and(inArray(table.${fk}, unique), isNull(table.deletedAt))!`
198
+ : `inArray(table.${fk}, unique)`;
199
+ const methods = [];
200
+ for (const parent of entities) {
201
+ for (const rel of parent.relations) {
202
+ if (rel.targetExportName !== entity.exportName || !rel.childFkDrizzleKey)
203
+ continue;
204
+ const parentType = parent.graphqlType;
205
+ const fk = rel.childFkDrizzleKey;
206
+ if (rel.kind === "one-to-many") {
207
+ methods.push(` async findBy${parentType}Ids(${parent.fieldBasename}Ids: string[]): Promise<Map<string, ${entity.graphqlType}Record[]>> {
208
+ if (${parent.fieldBasename}Ids.length === 0) return new Map();
209
+ const unique = [...new Set(${parent.fieldBasename}Ids)];
210
+ const rows = await db.select().from(table).where(${batchWhere(fk)});
211
+ const map = new Map<string, ${entity.graphqlType}Record[]>();
212
+ for (const id of unique) map.set(id, []);
213
+ for (const row of rows) {
214
+ const key = row.${fk} as string;
215
+ map.get(key)?.push(mapRow(row));
216
+ }
217
+ return map;
218
+ }`);
219
+ }
220
+ if (rel.kind === "one-to-one" && !rel.ownerFkDrizzleKey) {
221
+ methods.push(` async findOneBy${parentType}Ids(${parent.fieldBasename}Ids: string[]): Promise<Map<string, ${entity.graphqlType}Record | undefined>> {
222
+ if (${parent.fieldBasename}Ids.length === 0) return new Map();
223
+ const unique = [...new Set(${parent.fieldBasename}Ids)];
224
+ const rows = await db.select().from(table).where(${batchWhere(fk)});
225
+ const map = new Map<string, ${entity.graphqlType}Record | undefined>();
226
+ for (const id of unique) map.set(id, undefined);
227
+ for (const row of rows) {
228
+ map.set(row.${fk} as string, mapRow(row));
229
+ }
230
+ return map;
231
+ }`);
232
+ }
233
+ }
234
+ }
235
+ return methods.join("\n\n");
236
+ }
237
+ function manyToManyBatchMethods(entity, entities) {
238
+ const methods = [];
239
+ for (const rel of entity.relations) {
240
+ if (rel.kind !== "many-to-many")
241
+ continue;
242
+ if (!rel.joinTableExportName ||
243
+ !rel.joinOwnerFkDrizzleKey ||
244
+ !rel.joinTargetFkDrizzleKey) {
245
+ continue;
246
+ }
247
+ const targetEntity = entities.find((e) => e.exportName === rel.targetExportName);
248
+ if (!targetEntity)
249
+ continue;
250
+ const joinEntity = entities.find((e) => e.exportName === rel.joinTableExportName);
251
+ const joinTable = rel.joinTableExportName;
252
+ const targetExport = rel.targetExportName;
253
+ const ownerFk = rel.joinOwnerFkDrizzleKey;
254
+ const targetFk = rel.joinTargetFkDrizzleKey;
255
+ const targetType = rel.targetGraphqlType;
256
+ const targetSoft = targetEntity.deleteStrategy === "soft";
257
+ const joinSoft = joinEntity?.deleteStrategy === "soft";
258
+ const targetCols = internalRecordColumns(targetEntity);
259
+ const selectFields = [
260
+ `ownerId: ${joinTable}.${ownerFk}`,
261
+ ...targetCols.map((c) => `${c.drizzleKey}: ${targetExport}.${c.drizzleKey}`),
262
+ ].join(",\n ");
263
+ const mapFields = targetCols.map((c) => mapRowFieldLine(c)).join("\n");
264
+ const whereParts = [`inArray(${joinTable}.${ownerFk}, unique)`];
265
+ if (joinSoft)
266
+ whereParts.push(`isNull(${joinTable}.deletedAt)`);
267
+ if (targetSoft)
268
+ whereParts.push(`isNull(${targetExport}.deletedAt)`);
269
+ const whereClause = whereParts.length === 1 ? whereParts[0] : `and(${whereParts.join(", ")})!`;
270
+ methods.push(` async find${targetType}sBy${entity.graphqlType}Ids(${entity.fieldBasename}Ids: string[]): Promise<Map<string, ${targetType}Record[]>> {
271
+ if (${entity.fieldBasename}Ids.length === 0) return new Map();
272
+ const unique = [...new Set(${entity.fieldBasename}Ids)];
273
+ const rows = await db
274
+ .select({
275
+ ${selectFields}
276
+ })
277
+ .from(${joinTable})
278
+ .innerJoin(${targetExport}, eq(${joinTable}.${targetFk}, ${targetExport}.id))
279
+ .where(${whereClause});
280
+ const map = new Map<string, ${targetType}Record[]>();
281
+ for (const id of unique) map.set(id, []);
282
+ for (const row of rows) {
283
+ const ownerId = row.ownerId as string;
284
+ map.get(ownerId)?.push({
285
+ ${mapFields}
286
+ });
287
+ }
288
+ return map;
289
+ }`);
290
+ }
291
+ return methods.join("\n\n");
292
+ }
293
+ export function generateRepository(entity, entities, config) {
294
+ const E = entity.graphqlType;
295
+ const e = entity.fieldBasename;
296
+ const exportName = entity.exportName;
297
+ const soft = entity.deleteStrategy === "soft";
298
+ const full = entity.auditProfile === "full";
299
+ const businessCols = entity.columns.filter((c) => c.isBusiness);
300
+ const recordCols = internalRecordColumns(entity);
301
+ const sortCols = recordCols;
302
+ const extraTableImports = collectRelationTableImports(entity, entities);
303
+ extraTableImports.delete(exportName);
304
+ const mapRowFields = recordCols.map((col) => mapRowFieldLine(col)).join("\n");
305
+ const columnDescriptors = recordCols
306
+ .map((c) => ` { graphqlName: "${c.graphqlName}", drizzleKey: "${c.drizzleKey}", kind: "${c.kind}" as const, column: table.${c.drizzleKey} },`)
307
+ .join("\n");
308
+ const createValues = businessCols.map((col) => assignCreateValue(col)).join("\n");
309
+ const updateSet = full ? businessCols.map((col) => assignUpdateValue(col)).join("\n") : "";
310
+ const activeIdWhere = activeRowWhere("id", soft);
311
+ const cursorSerializeFn = cursorSerializeBody(entity, sortCols);
312
+ const cursorDeserializeFn = cursorDeserializeBody(entity, sortCols);
313
+ const constraintsBlock = constraintMetadataBlock(entity);
314
+ const schemaImports = [exportName, ...extraTableImports]
315
+ .sort((a, b) => a.localeCompare(b))
316
+ .join(", ");
317
+ const bulkFilterBlock = full
318
+ ? `
319
+ assertFilterBulkConfirm(filter, confirmUpdateAll, "confirmUpdateAll");
320
+ const where = queryEngine.buildWhere(filter);
321
+ if (!where) throw new ValidationError("Filter required", ["filter"]);
322
+ const actor = resolveActorId(ctx.actorId);
323
+ const set: Partial<typeof table.$inferInsert> = {
324
+ updatedAt: new Date(),
325
+ updatedBy: actor,
326
+ };
327
+ ${updateSet}
328
+ return db.transaction(async (tx) => {
329
+ const matched = await tx.select({ id: table.id }).from(table).where(where).for("update");
330
+ assertFilterBulkCap(matched.length, BULK_FILTER_MAX);
331
+ const ids = matched.map((row) => row.id);
332
+ if (ids.length === 0) {
333
+ return { successCount: 0, failureCount: 0, userErrors: [], matchedIds: [] };
334
+ }
335
+ const updated = await tx.update(table).set(set).where(inArray(table.id, ids)).returning({ id: table.id });
336
+ return { successCount: updated.length, failureCount: 0, userErrors: [], matchedIds: ids };
337
+ });`
338
+ : "";
339
+ const bulkDeleteByFilterBlock = `
340
+ assertFilterBulkConfirm(filter, confirmDeleteAll, "confirmDeleteAll");
341
+ const where = queryEngine.buildWhere(filter);
342
+ if (!where) throw new ValidationError("Filter required", ["filter"]);
343
+ return db.transaction(async (tx) => {
344
+ const matched = await tx.select({ id: table.id }).from(table).where(where).for("update");
345
+ assertFilterBulkCap(matched.length, BULK_FILTER_MAX);
346
+ const ids = matched.map((row) => row.id);
347
+ if (ids.length === 0) {
348
+ return { successCount: 0, failureCount: 0, userErrors: [], matchedIds: [] };
349
+ }
350
+ ${soft ? `const actor = resolveActorId(ctx.actorId);
351
+ const updated = await tx.update(table).set({ deletedAt: new Date(), deletedBy: actor }).where(inArray(table.id, ids)).returning({ id: table.id });` : `const deleted = await tx.delete(table).where(inArray(table.id, ids)).returning({ id: table.id });`}
352
+ return { successCount: ${soft ? "updated" : "deleted"}.length, failureCount: 0, userErrors: [], matchedIds: ids };
353
+ });`;
354
+ const m2mRecordImports = manyToManyTargetRecordImports(entity, entities);
355
+ return `// AUTO-GENERATED by @corpdk/dal-codegen — do not edit
356
+ ${drizzleImportLine(entity, entities)}
357
+ ${dalCoreImportBlock(entity)}
358
+ import type { GraphQLResolveInfo } from "graphql";
359
+ import { db } from "../../../db/index.js";
360
+ import { ${schemaImports} } from "../../../db/schema/index.js";
361
+ import { RELATION_DESCRIPTORS_BY_TABLE } from "./generated-relation-descriptors.js";
362
+ ${m2mRecordImports}
363
+
364
+ type DbTransaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
365
+ type DbConn = typeof db | DbTransaction;
366
+
367
+ const table = ${exportName};
368
+ const FILTER_BUDGET = resolveFilterBudget({ maxDepth: ${config.filterMaxDepth}, maxNodes: ${config.filterMaxNodes} });
369
+ const BULK_FILTER_MAX = resolveBulkFilterMax();
370
+
371
+ const COLUMN_DESCRIPTORS: ColumnDescriptor[] = [
372
+ ${columnDescriptors}
373
+ ];
374
+
375
+ const RELATION_DESCRIPTORS = RELATION_DESCRIPTORS_BY_TABLE.get(table)!;
376
+
377
+ const RELATION_PROJECTION_HINTS: RelationProjectionHint[] = ${buildRelationProjectionHints(entity)};
378
+
379
+ const queryEngine = new QueryEngine<typeof table.$inferSelect>(
380
+ {
381
+ db,
382
+ table,
383
+ columns: COLUMN_DESCRIPTORS,
384
+ relations: RELATION_DESCRIPTORS,
385
+ softDelete: ${soft},
386
+ filterBudget: FILTER_BUDGET,
387
+ entityGraphqlName: "${E}",
388
+ cursorVersion: CURSOR_VERSION,
389
+ },
390
+ db,
391
+ {
392
+ ${sortCols
393
+ .map((c) => ` ${c.graphqlName.replace(/([A-Z])/g, "_$1").toUpperCase()}: "${c.drizzleKey}",`)
394
+ .join("\n")}
395
+ },
396
+ );
397
+
398
+ export type ${E}CreateInput = {
399
+ ${businessCols.map((c) => ` ${c.graphqlName}${c.notNull && !c.hasDefault ? "" : "?"}: ${tsTypeForColumn(c)}${!c.notNull ? " | null" : ""};`).join("\n")}
400
+ };
401
+
402
+ ${full ? `export type ${E}UpdateInput = Partial<${E}CreateInput>;` : ""}
403
+
404
+ export type ${E}Filter = FilterAST;
405
+
406
+ ${constraintsBlock}
407
+
408
+ function validateCreateInput(input: ${E}CreateInput) {
409
+ validateColumnConstraints(input as Record<string, unknown>, COLUMN_CONSTRAINTS, "create");
410
+ }
411
+
412
+ ${full ? `function validateUpdateInput(input: ${E}UpdateInput) {
413
+ validateColumnConstraints(input as Record<string, unknown>, COLUMN_CONSTRAINTS, "update");
414
+ }
415
+ ` : ""}
416
+
417
+ function mapRow(row: typeof table.$inferSelect): ${E}Record {
418
+ return {
419
+ ${mapRowFields}
420
+ };
421
+ }
422
+
423
+ function cursorValuesFromRow(row: typeof table.$inferSelect, resolvedSort: ResolvedSortKey[]): unknown[] {
424
+ ${cursorSerializeFn}
425
+ }
426
+
427
+ function cursorValuesToDb(values: unknown[], resolvedSort: ResolvedSortKey[]): unknown[] {
428
+ ${cursorDeserializeFn}
429
+ }
430
+
431
+ function columnProjectionFromInfo(
432
+ info: GraphQLResolveInfo | undefined,
433
+ sortDrizzleKeys?: string[],
434
+ ) {
435
+ if (!info) return null;
436
+ return resolveColumnProjectionFromInfo(
437
+ info,
438
+ "${E}",
439
+ COLUMN_DESCRIPTORS,
440
+ ${soft},
441
+ RELATION_PROJECTION_HINTS,
442
+ sortDrizzleKeys,
443
+ );
444
+ }
445
+
446
+ export class Generated${E}Repository {
447
+ mapRow = mapRow;
448
+
449
+ async findById(
450
+ id: string,
451
+ opts?: { includeDeleted?: boolean | null },
452
+ info?: GraphQLResolveInfo,
453
+ ): Promise<${E}Record | null> {
454
+ assertValidUuid(id);
455
+ const projection = columnProjectionFromInfo(info);
456
+ const rows = await queryEngine.findByIds([id], opts?.includeDeleted, projection);
457
+ if (rows.length === 0) return null;
458
+ return mapRow(rows[0]);
459
+ }
460
+
461
+ async findByIds(ids: string[], opts?: { includeDeleted?: boolean | null }): Promise<${E}Record[]> {
462
+ const rows = await queryEngine.findByIds(ids, opts?.includeDeleted);
463
+ return rows.map(mapRow);
464
+ }
465
+
466
+ ${parentBatchMethods(entity, entities)}
467
+
468
+ ${manyToManyBatchMethods(entity, entities)}
469
+
470
+ async list(
471
+ args: {
472
+ filter?: ${E}Filter | null;
473
+ sort?: SortInput[] | null;
474
+ limit?: number | null;
475
+ includeDeleted?: boolean | null;
476
+ },
477
+ info?: GraphQLResolveInfo,
478
+ ): Promise<${E}Record[]> {
479
+ const resolvedSort = queryEngine.resolveSort(args.sort);
480
+ const projection = columnProjectionFromInfo(
481
+ info,
482
+ resolvedSort.map((s) => s.drizzleKey),
483
+ );
484
+ return (await queryEngine.list(args, mapRow, projection)) as ${E}Record[];
485
+ }
486
+
487
+ async count(args: {
488
+ filter?: ${E}Filter | null;
489
+ includeDeleted?: boolean | null;
490
+ }): Promise<number> {
491
+ return queryEngine.count(args);
492
+ }
493
+
494
+ async listConnection(
495
+ args: {
496
+ filter?: ${E}Filter | null;
497
+ sort?: SortInput[] | null;
498
+ first?: number | null;
499
+ after?: string | null;
500
+ last?: number | null;
501
+ before?: string | null;
502
+ includeDeleted?: boolean | null;
503
+ },
504
+ info?: GraphQLResolveInfo,
505
+ ) {
506
+ const resolvedSort = queryEngine.resolveSort(args.sort);
507
+ const projection = columnProjectionFromInfo(
508
+ info,
509
+ resolvedSort.map((s) => s.drizzleKey),
510
+ );
511
+ return queryEngine.listConnection(
512
+ args,
513
+ mapRow,
514
+ cursorValuesFromRow,
515
+ cursorValuesToDb,
516
+ projection,
517
+ );
518
+ }
519
+
520
+ async create(input: ${E}CreateInput, ctx: RepositoryContext, conn: DbConn = db) {
521
+ try {
522
+ validateCreateInput(input);
523
+ const actor = resolveActorId(ctx.actorId);
524
+ const now = new Date();
525
+ const values = {
526
+ ${createValues}
527
+ createdAt: now,
528
+ ${full ? "updatedAt: now," : ""}
529
+ createdBy: actor,
530
+ ${full ? "updatedBy: actor," : ""}
531
+ };
532
+ const inserted = await conn.insert(table).values(values).returning();
533
+ const row = mapRow(inserted[0]);
534
+ return successPayload({ ${e}: row });
535
+ } catch (err) {
536
+ if (err instanceof ValidationError) {
537
+ return errorPayload({ ${e}: null }, [createUserError("VALIDATION_FAILED", err.message, { field: err.field })]);
538
+ }
539
+ return errorPayload({ ${e}: null }, [mapDriverError(err, "postgresql")]);
540
+ }
541
+ }
542
+
543
+ ${full ? `async update(id: string, input: ${E}UpdateInput, ctx: RepositoryContext, conn: DbConn = db) {
544
+ try {
545
+ assertValidUuid(id);
546
+ validateUpdateInput(input);
547
+ const actor = resolveActorId(ctx.actorId);
548
+ const set: Partial<typeof table.$inferInsert> = {
549
+ updatedAt: new Date(),
550
+ updatedBy: actor,
551
+ };
552
+ ${updateSet}
553
+ const updated = await conn.update(table).set(set).where(${activeIdWhere}).returning();
554
+ if (updated.length === 0) {
555
+ return errorPayload({ ${e}: null }, [createUserError("NOT_FOUND", "${E} not found", { id })]);
556
+ }
557
+ return successPayload({ ${e}: mapRow(updated[0]) });
558
+ } catch (err) {
559
+ if (err instanceof ValidationError) {
560
+ return errorPayload({ ${e}: null }, [createUserError("VALIDATION_FAILED", err.message, { field: err.field })]);
561
+ }
562
+ return errorPayload({ ${e}: null }, [mapDriverError(err, "postgresql")]);
563
+ }
564
+ }` : ""}
565
+
566
+ async delete(id: string, ctx: RepositoryContext, conn: DbConn = db) {
567
+ try {
568
+ assertValidUuid(id);
569
+ ${soft ? `const actor = resolveActorId(ctx.actorId);
570
+ const updated = await conn.update(table).set({ deletedAt: new Date(), deletedBy: actor }).where(${activeIdWhere}).returning({ id: table.id });` : `const deleted = await conn.delete(table).where(${activeIdWhere}).returning({ id: table.id });`}
571
+ if (${soft ? "updated" : "deleted"}.length === 0) {
572
+ return errorPayload({ success: false }, [createUserError("NOT_FOUND", "${E} not found", { id })]);
573
+ }
574
+ return successPayload({ success: true });
575
+ } catch (err) {
576
+ return errorPayload({ success: false }, [mapDriverError(err, "postgresql")]);
577
+ }
578
+ }
579
+
580
+ async bulkCreate(inputs: ${E}CreateInput[], ctx: RepositoryContext, atomic?: boolean | null) {
581
+ const isAtomic = resolveBulkAtomic(inputs.length, atomic);
582
+ if (isAtomic) {
583
+ return db.transaction(async (tx) => {
584
+ const items: ${E}Record[] = [];
585
+ for (const input of inputs) {
586
+ const result = await this.create(input, ctx, tx);
587
+ if (result.userErrors.length > 0) throw new ValidationError(result.userErrors[0]!.message);
588
+ if (result.${e}) items.push(result.${e});
589
+ }
590
+ return { items, userErrors: [] as const };
591
+ }).catch((err) => {
592
+ if (err instanceof ValidationError) {
593
+ return { successCount: 0, failureCount: inputs.length, userErrors: [createUserError("VALIDATION_FAILED", err.message)] } satisfies BulkMutationResult;
594
+ }
595
+ throw err;
596
+ });
597
+ }
598
+ const userErrors: BulkMutationResult["userErrors"] = [];
599
+ const matchedIds: string[] = [];
600
+ let successCount = 0;
601
+ for (const input of inputs) {
602
+ const result = await this.create(input, ctx);
603
+ if (result.${e} && result.userErrors.length === 0) {
604
+ successCount += 1;
605
+ matchedIds.push(result.${e}.id);
606
+ } else {
607
+ userErrors.push(...result.userErrors);
608
+ }
609
+ }
610
+ return { successCount, failureCount: inputs.length - successCount, userErrors, matchedIds };
611
+ }
612
+
613
+ ${full ? `async bulkUpdate(
614
+ updates: Array<{ id: string; input: ${E}UpdateInput }>,
615
+ ctx: RepositoryContext,
616
+ atomic?: boolean | null,
617
+ ) {
618
+ const isAtomic = resolveBulkAtomic(updates.length, atomic);
619
+ if (isAtomic) {
620
+ return db.transaction(async (tx) => {
621
+ const items: ${E}Record[] = [];
622
+ for (const entry of updates) {
623
+ const result = await this.update(entry.id, entry.input, ctx, tx);
624
+ if (result.userErrors.length > 0) throw new ValidationError(result.userErrors[0]!.message);
625
+ if (result.${e}) items.push(result.${e});
626
+ }
627
+ return { items, userErrors: [] as const };
628
+ }).catch((err) => {
629
+ if (err instanceof ValidationError) {
630
+ return { successCount: 0, failureCount: updates.length, userErrors: [createUserError("VALIDATION_FAILED", err.message)] } satisfies BulkMutationResult;
631
+ }
632
+ throw err;
633
+ });
634
+ }
635
+ const userErrors: BulkMutationResult["userErrors"] = [];
636
+ const matchedIds: string[] = [];
637
+ let successCount = 0;
638
+ for (const entry of updates) {
639
+ const result = await this.update(entry.id, entry.input, ctx);
640
+ if (result.${e} && result.userErrors.length === 0) {
641
+ successCount += 1;
642
+ matchedIds.push(result.${e}.id);
643
+ } else {
644
+ userErrors.push(...result.userErrors.map((e) => ({ ...e, id: e.id ?? entry.id })));
645
+ }
646
+ }
647
+ return { successCount, failureCount: updates.length - successCount, userErrors, matchedIds };
648
+ }
649
+
650
+ async bulkUpdateByFilter(
651
+ filter: ${E}Filter,
652
+ input: ${E}UpdateInput,
653
+ ctx: RepositoryContext,
654
+ confirmUpdateAll?: boolean | null,
655
+ ): Promise<BulkMutationResult> {${bulkFilterBlock}
656
+ }` : ""}
657
+
658
+ async bulkDelete(ids: string[], ctx: RepositoryContext, atomic?: boolean | null) {
659
+ const isAtomic = resolveBulkAtomic(ids.length, atomic);
660
+ if (isAtomic) {
661
+ return db.transaction(async (tx) => {
662
+ let count = 0;
663
+ for (const id of ids) {
664
+ const result = await this.delete(id, ctx, tx);
665
+ if (!result.success) throw new ValidationError(result.userErrors[0]?.message ?? "Delete failed");
666
+ count += 1;
667
+ }
668
+ return { count, userErrors: [] as const };
669
+ }).catch((err) => {
670
+ if (err instanceof ValidationError) {
671
+ return { successCount: 0, failureCount: ids.length, userErrors: [createUserError("VALIDATION_FAILED", err.message)] } satisfies BulkMutationResult;
672
+ }
673
+ throw err;
674
+ });
675
+ }
676
+ const userErrors: BulkMutationResult["userErrors"] = [];
677
+ const matchedIds: string[] = [];
678
+ let successCount = 0;
679
+ for (const id of ids) {
680
+ const result = await this.delete(id, ctx);
681
+ if (result.success) {
682
+ successCount += 1;
683
+ matchedIds.push(id);
684
+ } else userErrors.push(...result.userErrors.map((e) => ({ ...e, id: e.id ?? id })));
685
+ }
686
+ return { successCount, failureCount: ids.length - successCount, userErrors, matchedIds };
687
+ }
688
+
689
+ async bulkDeleteByFilter(
690
+ filter: ${E}Filter,
691
+ ctx: RepositoryContext,
692
+ confirmDeleteAll?: boolean | null,
693
+ ): Promise<BulkMutationResult> {${bulkDeleteByFilterBlock}
694
+ }
695
+
696
+ toChangeEvent(operation: EntityChangeEventPayload["operation"], ids: string[]): EntityChangeEventPayload {
697
+ const count = ids.length;
698
+ const isTruncated = count > CHANGE_EVENT_ID_CAP;
699
+ return {
700
+ operation,
701
+ ids: isTruncated ? [] : ids,
702
+ isTruncated,
703
+ count,
704
+ };
705
+ }
706
+ }
707
+ `;
708
+ }
709
+ export function generateRepositoryIndex(entities) {
710
+ const imports = entities
711
+ .map((e) => `export { Generated${e.graphqlType}Repository } from "./generated-${e.fieldBasename}.repository.js";`)
712
+ .join("\n");
713
+ return `// AUTO-GENERATED by @corpdk/dal-codegen — do not edit
714
+ ${imports}
715
+ `;
716
+ }
717
+ //# sourceMappingURL=repository.js.map