express-file-cluster 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/index.cjs +5 -5
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +4 -4
  6. package/dist/{chunk-VYHJX54R.js → chunk-277BSYVH.js} +2 -1
  7. package/dist/chunk-277BSYVH.js.map +1 -0
  8. package/dist/{chunk-RTFJ32T5.js → chunk-6OGOVV57.js} +1344 -132
  9. package/dist/chunk-6OGOVV57.js.map +1 -0
  10. package/dist/{chunk-QTRGJ2EN.cjs → chunk-AZYXQU3Z.cjs} +1378 -166
  11. package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
  12. package/dist/chunk-BUBXO7WU.js +170 -0
  13. package/dist/chunk-BUBXO7WU.js.map +1 -0
  14. package/dist/chunk-MGH4VDV3.cjs +170 -0
  15. package/dist/chunk-MGH4VDV3.cjs.map +1 -0
  16. package/dist/{chunk-ULQXD4YZ.cjs → chunk-R34R7QPD.cjs} +3 -3
  17. package/dist/{chunk-ULQXD4YZ.cjs.map → chunk-R34R7QPD.cjs.map} +1 -1
  18. package/dist/{chunk-M7MUPWCE.js → chunk-RS4MXCPW.js} +2 -2
  19. package/dist/{chunk-SZT36SGB.cjs → chunk-T4OHFU5T.cjs} +8 -8
  20. package/dist/{chunk-SZT36SGB.cjs.map → chunk-T4OHFU5T.cjs.map} +1 -1
  21. package/dist/{chunk-5PDAWMGF.js → chunk-TRC4DUZB.js} +4 -4
  22. package/dist/{chunk-47K2532L.cjs → chunk-TYR2GZZE.cjs} +7 -7
  23. package/dist/{chunk-47K2532L.cjs.map → chunk-TYR2GZZE.cjs.map} +1 -1
  24. package/dist/{chunk-PMF4GMHD.js → chunk-UBQYQPBU.js} +2 -2
  25. package/dist/{chunk-JJJJTACK.js → chunk-UTM4PEVG.js} +2 -2
  26. package/dist/{chunk-RSBW2B3D.cjs → chunk-YL37D6KM.cjs} +3 -2
  27. package/dist/chunk-YL37D6KM.cjs.map +1 -0
  28. package/dist/{chunk-SFVEQ2T5.cjs → chunk-ZDM5JHVK.cjs} +11 -11
  29. package/dist/{chunk-SFVEQ2T5.cjs.map → chunk-ZDM5JHVK.cjs.map} +1 -1
  30. package/dist/cli/db-runner.cjs +10 -10
  31. package/dist/cli/db-runner.js +3 -3
  32. package/dist/cli/index.cjs +6 -6
  33. package/dist/cli/index.js +4 -4
  34. package/dist/docs/api-reference/ignite.md +3 -0
  35. package/dist/docs/api-reference/table.md +210 -2
  36. package/dist/docs/guides/logging.md +38 -0
  37. package/dist/docs/index.md +1 -1
  38. package/dist/docs/skills/SKILL.md +2 -2
  39. package/dist/docs/skills/api-surface.md +2 -1
  40. package/dist/docs/skills/what-not-to-invent.md +1 -1
  41. package/dist/index.cjs +44 -69
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.cts +248 -21
  44. package/dist/index.d.ts +248 -21
  45. package/dist/index.js +12 -37
  46. package/dist/index.js.map +1 -1
  47. package/dist/{pgboss-backend-UUJOVEYK.js → pgboss-backend-QKBXVJ6B.js} +3 -3
  48. package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
  49. package/dist/{pgboss-backend-3E6ATY42.cjs.map → pgboss-backend-TCHI7CHM.cjs.map} +1 -1
  50. package/dist/tasks/index.d.cts +1 -1
  51. package/dist/tasks/index.d.ts +1 -1
  52. package/dist/{types-DJCPAsM4.d.cts → types-B6lVw4bj.d.cts} +49 -2
  53. package/dist/{types-DJCPAsM4.d.ts → types-B6lVw4bj.d.ts} +49 -2
  54. package/package.json +1 -1
  55. package/dist/chunk-3VWD2ZED.js +0 -60
  56. package/dist/chunk-3VWD2ZED.js.map +0 -1
  57. package/dist/chunk-ALBDM5R3.cjs +0 -60
  58. package/dist/chunk-ALBDM5R3.cjs.map +0 -1
  59. package/dist/chunk-QTRGJ2EN.cjs.map +0 -1
  60. package/dist/chunk-RSBW2B3D.cjs.map +0 -1
  61. package/dist/chunk-RTFJ32T5.js.map +0 -1
  62. package/dist/chunk-VYHJX54R.js.map +0 -1
  63. package/dist/pgboss-backend-3E6ATY42.cjs +0 -14
  64. /package/dist/{chunk-M7MUPWCE.js.map → chunk-RS4MXCPW.js.map} +0 -0
  65. /package/dist/{chunk-5PDAWMGF.js.map → chunk-TRC4DUZB.js.map} +0 -0
  66. /package/dist/{chunk-PMF4GMHD.js.map → chunk-UBQYQPBU.js.map} +0 -0
  67. /package/dist/{chunk-JJJJTACK.js.map → chunk-UTM4PEVG.js.map} +0 -0
  68. /package/dist/{pgboss-backend-UUJOVEYK.js.map → pgboss-backend-QKBXVJ6B.js.map} +0 -0
@@ -1,12 +1,16 @@
1
1
  import {
2
+ countStatement,
2
3
  getOrm,
3
4
  getPool,
4
- notInstalled
5
- } from "./chunk-3VWD2ZED.js";
5
+ notInstalled,
6
+ traceOps,
7
+ untracked,
8
+ whenQueryTracking
9
+ } from "./chunk-BUBXO7WU.js";
6
10
  import {
7
11
  getCurrentUser,
8
12
  getLogger
9
- } from "./chunk-VYHJX54R.js";
13
+ } from "./chunk-277BSYVH.js";
10
14
 
11
15
  // src/errors.ts
12
16
  var HttpError = class _HttpError extends Error {
@@ -49,7 +53,9 @@ function isHttpError(value) {
49
53
  import { randomBytes, randomUUID } from "crypto";
50
54
  var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
51
55
  var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
52
- var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column"];
56
+ var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column", "onDelete"];
57
+ var REFERENTIAL_ACTIONS = /* @__PURE__ */ new Set(["restrict", "cascade", "setNull"]);
58
+ var FOREIGN_KEY_TYPES = /* @__PURE__ */ new Set(["objectId", "uuid", "integer", "bigint"]);
53
59
  function isFieldDefinition(value) {
54
60
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
55
61
  const type = value.type;
@@ -91,6 +97,34 @@ var SchemaBuilder = class {
91
97
  if (def.column !== void 0 && !topLevel) {
92
98
  this.fail(path, `'column' only applies to top-level fields`);
93
99
  }
100
+ if (def.onDelete !== void 0) {
101
+ if (def.ref === void 0) this.fail(path, `'onDelete' needs 'ref'`);
102
+ if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {
103
+ this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);
104
+ }
105
+ if (def.onDelete === "setNull" && def.required) {
106
+ this.fail(path, `onDelete: 'setNull' can't clear a required field`);
107
+ }
108
+ }
109
+ if (def.ref !== void 0) {
110
+ const many = def.type === "array";
111
+ if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);
112
+ if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {
113
+ this.fail(
114
+ path,
115
+ many ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint` : `'ref' needs an id type: objectId, uuid, integer or bigint`
116
+ );
117
+ }
118
+ if (many && def.onDelete !== void 0) {
119
+ this.fail(
120
+ path,
121
+ `'onDelete' doesn't apply to many-to-many refs \u2014 links are always removed with either record`
122
+ );
123
+ }
124
+ if (many && (def.unique || def.index)) {
125
+ this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);
126
+ }
127
+ }
94
128
  }
95
129
  item(of, parent, path) {
96
130
  if (of === void 0) return untyped();
@@ -417,7 +451,10 @@ function runInTx(handle, fn) {
417
451
  // src/db/mongo-model.ts
418
452
  var mongoosePromise;
419
453
  function loadMongoose() {
420
- mongoosePromise ??= import("mongoose").then((mod) => mod.default ?? mod).catch((err) => {
454
+ mongoosePromise ??= import("mongoose").then((mod) => mod.default ?? mod).then((mg) => {
455
+ whenQueryTracking(() => mg.set("debug", countStatement));
456
+ return mg;
457
+ }).catch((err) => {
421
458
  mongoosePromise = void 0;
422
459
  throw notInstalled(err, "mongoose", "npm install mongoose");
423
460
  });
@@ -563,44 +600,46 @@ function mapSort(sort) {
563
600
  }
564
601
  function mongoModel(name, tree, options) {
565
602
  let compiled;
566
- const model = () => compiled ??= loadMongoose().then(async (mg) => {
567
- if (mg.models[name]) return mg.models[name];
568
- const schema = new mg.Schema(buildTree(tree, mg), {
569
- timestamps: options.timestamps ?? true,
570
- // autoSync: false hands collection and index creation to migrations, on MongoDB too.
571
- autoIndex: isAutoSync(),
572
- autoCreate: isAutoSync(),
573
- ...options.collection !== void 0 && { collection: options.collection }
574
- });
575
- for (const idx of options.indexes ?? []) {
576
- schema.index(idx.fields, {
577
- ...idx.unique !== void 0 && { unique: idx.unique },
578
- ...idx.expireAfterSeconds !== void 0 && {
579
- expireAfterSeconds: idx.expireAfterSeconds
580
- },
581
- ...idx.name !== void 0 && { name: idx.name }
582
- });
583
- }
584
- const sequences = sequenceFields(name, tree);
585
- if (sequences.length > 0) {
586
- schema.pre("validate", async function() {
587
- if (!this.isNew) return;
588
- for (const { path, key } of sequences) {
589
- if (this.get(path) == null) this.set(path, await nextSequence(mg, key));
590
- }
591
- });
592
- }
593
- const M = mg.model(name, schema);
594
- if (isAutoSync()) {
595
- await M.init().catch((err) => {
596
- getLogger().warn(
597
- { model: name, err: err.message },
598
- `${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
599
- );
603
+ const model = () => compiled ??= untracked(
604
+ () => loadMongoose().then(async (mg) => {
605
+ if (mg.models[name]) return mg.models[name];
606
+ const schema = new mg.Schema(buildTree(tree, mg), {
607
+ timestamps: options.timestamps ?? true,
608
+ // autoSync: false hands collection and index creation to migrations, on MongoDB too.
609
+ autoIndex: isAutoSync(),
610
+ autoCreate: isAutoSync(),
611
+ ...options.collection !== void 0 && { collection: options.collection }
600
612
  });
601
- }
602
- return M;
603
- });
613
+ for (const idx of options.indexes ?? []) {
614
+ schema.index(idx.fields, {
615
+ ...idx.unique !== void 0 && { unique: idx.unique },
616
+ ...idx.expireAfterSeconds !== void 0 && {
617
+ expireAfterSeconds: idx.expireAfterSeconds
618
+ },
619
+ ...idx.name !== void 0 && { name: idx.name }
620
+ });
621
+ }
622
+ const sequences = sequenceFields(name, tree);
623
+ if (sequences.length > 0) {
624
+ schema.pre("validate", async function() {
625
+ if (!this.isNew) return;
626
+ for (const { path, key } of sequences) {
627
+ if (this.get(path) == null) this.set(path, await nextSequence(mg, key));
628
+ }
629
+ });
630
+ }
631
+ const M = mg.model(name, schema);
632
+ if (isAutoSync()) {
633
+ await M.init().catch((err) => {
634
+ getLogger().warn(
635
+ { model: name, err: err.message },
636
+ `${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
637
+ );
638
+ });
639
+ }
640
+ return M;
641
+ })
642
+ );
604
643
  const session = () => {
605
644
  const tx = currentTx();
606
645
  return tx?.engine === "mongodb" ? { session: tx.session } : {};
@@ -789,6 +828,29 @@ var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])
789
828
  var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
790
829
  var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
791
830
  var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
831
+ var syncing = /* @__PURE__ */ new Map();
832
+ var ACTION_SQL = {
833
+ restrict: "RESTRICT",
834
+ cascade: "CASCADE",
835
+ setNull: "SET NULL"
836
+ };
837
+ var ACTION_CODE = {
838
+ restrict: "r",
839
+ cascade: "c",
840
+ setNull: "n"
841
+ };
842
+ var ID_COLUMN = {
843
+ uuid: { kind: "uuid", type: "uuid" },
844
+ serial: { kind: "integer", type: "integer" },
845
+ bigserial: { kind: "bigint", type: "bigint" }
846
+ };
847
+ var modelOfTable = (table) => registeredModels().find((m) => {
848
+ try {
849
+ return m.pgTarget?.().table === table;
850
+ } catch {
851
+ return false;
852
+ }
853
+ })?.name ?? table;
792
854
  function scalarSpec(type, def, native) {
793
855
  switch (type) {
794
856
  case "string":
@@ -839,6 +901,7 @@ function pgTable(name, tree, options, config) {
839
901
  const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
840
902
  const refs = refFields(tree);
841
903
  const columns = /* @__PURE__ */ new Map();
904
+ const joins = /* @__PURE__ */ new Map();
842
905
  const idSpec = idKind === "uuid" ? { field: "id", column: "id", kind: "uuid", ddl: "uuid", formatted: "uuid" } : idKind === "serial" ? { field: "id", column: "id", kind: "integer", ddl: "integer", formatted: "integer" } : {
843
906
  field: "id",
844
907
  column: "id",
@@ -873,6 +936,17 @@ function pgTable(name, tree, options, config) {
873
936
  } else {
874
937
  columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
875
938
  }
939
+ } else if (config.native && node.kind === "array" && node.item.kind === "scalar" && node.def.ref !== void 0) {
940
+ const item = scalarSpec(node.item.type, node.item.def, false).kind;
941
+ joins.set(field, {
942
+ field,
943
+ table: `${table}_${column}`,
944
+ legacyColumn: column,
945
+ target: node.def.ref,
946
+ item,
947
+ ddl: `${item}[]`,
948
+ node
949
+ });
876
950
  } else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
877
951
  const item = scalarSpec(node.item.type, node.item.def, false);
878
952
  columns.set(field, {
@@ -1038,7 +1112,12 @@ function pgTable(name, tree, options, config) {
1038
1112
  await validateTree(checkTree, data, issues, partial);
1039
1113
  if (issues.length) throw new ModelValidationError(name, issues);
1040
1114
  };
1041
- const known = (data) => Object.fromEntries(Object.entries(data).filter(([k]) => columns.has(k.split(".")[0])));
1115
+ const known = (data) => Object.fromEntries(
1116
+ Object.entries(data).filter(([k]) => {
1117
+ const top = k.split(".")[0];
1118
+ return columns.has(top) || joins.has(top);
1119
+ })
1120
+ );
1042
1121
  const prepareInsert = async (input) => {
1043
1122
  const { id, ...rest } = known(input);
1044
1123
  for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
@@ -1067,6 +1146,25 @@ function pgTable(name, tree, options, config) {
1067
1146
  const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
1068
1147
  throw new HttpError(409, `${name} with this ${fields} already exists`);
1069
1148
  }
1149
+ if (e?.code === "23503" || e?.code === "23001") {
1150
+ const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
1151
+ e.detail ?? ""
1152
+ );
1153
+ if (ref) {
1154
+ throw new ModelValidationError(name, [
1155
+ {
1156
+ // In a join table: the many-to-many field it backs.
1157
+ path: joinByTable.get(e.table ?? "") ?? fieldOfColumn(ref[1].replace(/"/g, "")),
1158
+ message: `${modelOfTable(ref[2])} not found`
1159
+ }
1160
+ ]);
1161
+ }
1162
+ const by = /is (?:still )?referenced from table "([^"]+)"/.exec(e.detail ?? "")?.[1];
1163
+ throw new HttpError(
1164
+ 409,
1165
+ `${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ""} \u2014 delete or reassign those records first`
1166
+ );
1167
+ }
1070
1168
  if (e?.code === "23502")
1071
1169
  throw new ModelValidationError(name, [
1072
1170
  { path: fieldOfColumn(e.column ?? ""), message: "is required" }
@@ -1103,6 +1201,63 @@ function pgTable(name, tree, options, config) {
1103
1201
  return true;
1104
1202
  };
1105
1203
  const enumCheck = (column) => `${table}_${column}_enum`;
1204
+ const fkName = (column) => `${table}_${column}_fkey`;
1205
+ const isForeignKey = (spec) => config.native && spec.node?.kind === "scalar" && spec.node.def.ref !== void 0;
1206
+ function resolveTarget(field, targetName, kind, many) {
1207
+ const target = targetName === name ? { table, idKind } : getRegisteredModel(targetName)?.pgTarget?.();
1208
+ if (!target) {
1209
+ throw new Error(
1210
+ `[EFC] ${name}.${field} references "${targetName}", which is not defined \u2014 import that model before using ${name}`
1211
+ );
1212
+ }
1213
+ const want = ID_COLUMN[target.idKind];
1214
+ if (kind !== want.kind) {
1215
+ const hint = many ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }` : `{ type: '${want.type}', ref: '${targetName}' }`;
1216
+ throw new Error(
1217
+ `[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') \u2014 declare it ${hint}`
1218
+ );
1219
+ }
1220
+ return target;
1221
+ }
1222
+ function foreignKeys() {
1223
+ const out = [];
1224
+ for (const spec of columns.values()) {
1225
+ if (!isForeignKey(spec)) continue;
1226
+ const def = spec.node.def;
1227
+ const target = resolveTarget(spec.field, def.ref, spec.kind, false);
1228
+ out.push({
1229
+ field: spec.field,
1230
+ onTable: table,
1231
+ column: spec.column,
1232
+ name: fkName(spec.column),
1233
+ target: def.ref,
1234
+ targetTable: target.table,
1235
+ action: def.onDelete ?? "restrict"
1236
+ });
1237
+ }
1238
+ for (const join of joins.values()) {
1239
+ const target = resolveTarget(join.field, join.target, join.item, true);
1240
+ const base = { field: join.field, onTable: join.table, action: "cascade" };
1241
+ out.push(
1242
+ {
1243
+ ...base,
1244
+ column: "owner_id",
1245
+ name: `${join.table}_owner_id_fkey`,
1246
+ target: name,
1247
+ targetTable: table
1248
+ },
1249
+ {
1250
+ ...base,
1251
+ column: "ref_id",
1252
+ name: `${join.table}_ref_id_fkey`,
1253
+ target: join.target,
1254
+ targetTable: target.table
1255
+ }
1256
+ );
1257
+ }
1258
+ return out;
1259
+ }
1260
+ const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));
1106
1261
  const managedIndexName = /_(key|idx)$/;
1107
1262
  function desiredIndexes() {
1108
1263
  const out = /* @__PURE__ */ new Map();
@@ -1115,7 +1270,7 @@ function pgTable(name, tree, options, config) {
1115
1270
  `${table}_${col}_key`,
1116
1271
  `CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
1117
1272
  );
1118
- } else if (def.index) {
1273
+ } else if (def.index || isForeignKey(spec) && def.index !== false) {
1119
1274
  out.set(
1120
1275
  `${table}_${col}_idx`,
1121
1276
  `CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
@@ -1146,7 +1301,52 @@ function pgTable(name, tree, options, config) {
1146
1301
  }
1147
1302
  return out;
1148
1303
  }
1304
+ const tableExists = async (t) => (await getPool().query(
1305
+ `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1306
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1307
+ [t]
1308
+ )).rowCount > 0;
1149
1309
  async function reconcile(dryRun) {
1310
+ const fks = foreignKeys();
1311
+ if (dryRun) return reconcileTable(true, fks, /* @__PURE__ */ new Set());
1312
+ let release;
1313
+ const mine = new Promise((resolve) => release = resolve);
1314
+ const prev = syncing.get(table);
1315
+ syncing.set(table, mine);
1316
+ try {
1317
+ const deferred = /* @__PURE__ */ new Set();
1318
+ const tx = currentTx();
1319
+ if (tx?.engine === "postgresql" && fks.length) {
1320
+ for (const fk of fks) deferred.add(fk.name);
1321
+ tx.afterCommit.push(() => {
1322
+ reconcile(false).catch(
1323
+ (err) => getLogger().error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1324
+ );
1325
+ });
1326
+ }
1327
+ for (const fk of fks) {
1328
+ if (deferred.has(fk.name)) continue;
1329
+ if (fk.targetTable === table || await tableExists(fk.targetTable)) continue;
1330
+ const running = syncing.get(fk.targetTable);
1331
+ if (running) {
1332
+ deferred.add(fk.name);
1333
+ void running.then(() => reconcile(false)).catch(
1334
+ (err) => getLogger().error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1335
+ );
1336
+ } else {
1337
+ await getRegisteredModel(fk.target).sync();
1338
+ }
1339
+ }
1340
+ return await reconcileTable(false, fks, deferred);
1341
+ } finally {
1342
+ release();
1343
+ if (syncing.get(table) === mine) {
1344
+ if (prev) syncing.set(table, prev);
1345
+ else syncing.delete(table);
1346
+ }
1347
+ }
1348
+ }
1349
+ async function reconcileTable(dryRun, fks, deferred) {
1150
1350
  const pool = getPool();
1151
1351
  const conn = await pool.connect();
1152
1352
  try {
@@ -1174,7 +1374,33 @@ function pgTable(name, tree, options, config) {
1174
1374
  [table]
1175
1375
  )).rows.map((r) => r.name)
1176
1376
  );
1377
+ const liveFks = new Map(
1378
+ (await conn.query(
1379
+ `SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid
1380
+ FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1381
+ JOIN pg_class ft ON ft.oid = con.confrelid
1382
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,
1383
+ [[table, ...joinByTable.keys()]]
1384
+ )).rows.map((r) => [r.name, r])
1385
+ );
1386
+ const liveJoinTables = new Set(
1387
+ (await conn.query(
1388
+ `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1389
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1390
+ [[...joinByTable.keys()]]
1391
+ )).rows.map((r) => r.name)
1392
+ );
1177
1393
  const plan = [];
1394
+ const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));
1395
+ for (const [con, live] of liveFks) {
1396
+ const want = wantedFks.get(con);
1397
+ const ours = [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) || [...columns.values()].some((c) => c.field !== "id" && fkName(c.column) === con);
1398
+ if (ours && (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])) {
1399
+ const on = [...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)) ?? table;
1400
+ plan.push(`ALTER TABLE ${q(on)} DROP CONSTRAINT ${q(con)}`);
1401
+ liveFks.delete(con);
1402
+ }
1403
+ }
1178
1404
  for (const { key } of sequences) {
1179
1405
  const seq = sequenceName(key);
1180
1406
  const found = await conn.query(
@@ -1278,6 +1504,43 @@ function pgTable(name, tree, options, config) {
1278
1504
  }
1279
1505
  }
1280
1506
  for (const [idx, create] of wantedIndexes) if (!indexes.has(idx)) plan.push(create);
1507
+ const ownerDdl = idSpec.ddl;
1508
+ for (const join of joins.values()) {
1509
+ if (liveJoinTables.has(join.table)) continue;
1510
+ const refDdl = join.item;
1511
+ plan.push(
1512
+ `CREATE TABLE IF NOT EXISTS ${q(join.table)} (
1513
+ ${q("owner_id")} ${ownerDdl} NOT NULL,
1514
+ ${q("ref_id")} ${refDdl} NOT NULL,
1515
+ ${q("position")} integer NOT NULL DEFAULT 0,
1516
+ PRIMARY KEY (${q("owner_id")}, ${q("ref_id")})
1517
+ )`,
1518
+ `CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q("ref_id")})`
1519
+ );
1520
+ const legacy = existing.get(join.legacyColumn)?.type;
1521
+ if (legacy === "jsonb" || legacy?.endsWith("[]")) {
1522
+ const c = `o.${q(join.legacyColumn)}`;
1523
+ const items = legacy === "jsonb" ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)` : `unnest(${c}::text[])`;
1524
+ const valid = join.item === "uuid" ? `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'` : `'^-?[0-9]{1,18}$'`;
1525
+ plan.push(
1526
+ `INSERT INTO ${q(join.table)} (${q("owner_id")}, ${q("ref_id")}, ${q("position")}) SELECT o.${q("id")}, x.v::${refDdl}, x.n FROM ${q(table)} o, ${items} WITH ORDINALITY AS x(v, n) WHERE x.v ~ ${valid} ON CONFLICT DO NOTHING`
1527
+ );
1528
+ }
1529
+ }
1530
+ const toValidate = [];
1531
+ for (const fk of fks) {
1532
+ if (deferred.has(fk.name)) continue;
1533
+ const live = liveFks.get(fk.name);
1534
+ if (!live) {
1535
+ plan.push(
1536
+ `ALTER TABLE ${q(fk.onTable)} ADD CONSTRAINT ${q(fk.name)} FOREIGN KEY (${q(fk.column)}) REFERENCES ${q(fk.targetTable)} (${q("id")}) ON DELETE ${ACTION_SQL[fk.action]} NOT VALID`
1537
+ );
1538
+ }
1539
+ if (!live?.valid) toValidate.push(fk);
1540
+ }
1541
+ const validations = toValidate.map(
1542
+ (fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`
1543
+ );
1281
1544
  if (!dryRun) {
1282
1545
  for (const stmt of plan) {
1283
1546
  try {
@@ -1291,7 +1554,23 @@ function pgTable(name, tree, options, config) {
1291
1554
  }
1292
1555
  }
1293
1556
  await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
1294
- return plan;
1557
+ if (!dryRun) {
1558
+ for (const [i, fk] of toValidate.entries()) {
1559
+ try {
1560
+ await conn.query(validations[i]);
1561
+ } catch {
1562
+ const orphans = await conn.query(
1563
+ `SELECT count(*) AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL
1564
+ AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q("id")} = r.${q(fk.column)})`
1565
+ ).then((r) => r.rows[0]?.n ?? "?").catch(() => "?");
1566
+ getLogger().warn(
1567
+ { table, constraint: fk.name, orphans: Number(orphans) },
1568
+ `${name}.${fk.field}: ${orphans} row(s) reference a missing ${fk.target} \u2014 the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`
1569
+ );
1570
+ }
1571
+ }
1572
+ }
1573
+ return [...plan, ...validations];
1295
1574
  } catch (err) {
1296
1575
  await conn.query("ROLLBACK").catch(() => {
1297
1576
  });
@@ -1310,6 +1589,7 @@ function pgTable(name, tree, options, config) {
1310
1589
  tree,
1311
1590
  idKind,
1312
1591
  columns,
1592
+ joins,
1313
1593
  ts,
1314
1594
  sequenceKeys,
1315
1595
  refs,
@@ -1727,6 +2007,24 @@ function distinctFields(tree, options) {
1727
2007
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
1728
2008
  return fields;
1729
2009
  }
2010
+ var MODEL_OPS = [
2011
+ "find",
2012
+ "findById",
2013
+ "findOne",
2014
+ "exists",
2015
+ "distinct",
2016
+ "create",
2017
+ "createMany",
2018
+ "update",
2019
+ "updateOne",
2020
+ "updateMany",
2021
+ "upsert",
2022
+ "delete",
2023
+ "deleteOne",
2024
+ "deleteMany",
2025
+ "count",
2026
+ "aggregate"
2027
+ ];
1730
2028
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
1731
2029
  function createModel(name, schema, options, native) {
1732
2030
  const tree = normalizeSchema(schema, "model", name);
@@ -1791,20 +2089,76 @@ function createModel(name, schema, options, native) {
1791
2089
  sync: (opts) => call((m) => m.sync(opts)),
1792
2090
  drop: () => call((m) => m.drop())
1793
2091
  };
2092
+ traceOps(name, model, MODEL_OPS);
1794
2093
  registerModel({
1795
2094
  name,
1796
2095
  sync: model.sync,
1797
2096
  drop: model.drop,
1798
- findByIds: (ids) => model.find({ id: { $in: ids } })
2097
+ findByIds: (ids) => model.find({ id: { $in: ids } }),
2098
+ pgTarget: () => ({ table: options.collection ?? tableNameFor(name), idKind: "uuid" })
1799
2099
  });
1800
2100
  return model;
1801
2101
  }
1802
2102
 
2103
+ // src/db/transaction.ts
2104
+ async function transaction(fn) {
2105
+ if (currentTx()) return fn();
2106
+ if (getDbEngine() === "postgresql") {
2107
+ let result;
2108
+ const afterCommit = [];
2109
+ await getOrm().transaction(async (tx) => {
2110
+ result = await runInTx({ engine: "postgresql", tx, afterCommit }, fn);
2111
+ });
2112
+ for (const run of afterCommit) run();
2113
+ return result;
2114
+ }
2115
+ const mg = await loadMongoose();
2116
+ const session = await mg.connection.startSession();
2117
+ try {
2118
+ let result;
2119
+ await session.withTransaction(async () => {
2120
+ result = await runInTx({ engine: "mongodb", session }, fn);
2121
+ });
2122
+ return result;
2123
+ } finally {
2124
+ await session.endSession();
2125
+ }
2126
+ }
2127
+
1803
2128
  // src/db/table-model.ts
2129
+ import { randomUUID as randomUUID3 } from "crypto";
1804
2130
  var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
1805
2131
  var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
1806
2132
  var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
1807
2133
  var likeEscape = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
2134
+ var relAlias = (field) => `efc_rel_${field}`;
2135
+ var incAlias = (name) => `efc_inc_${name}`;
2136
+ var ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "connectOrCreate", "disconnect"]);
2137
+ var JOIN_OPS = /* @__PURE__ */ new Set([
2138
+ "connect",
2139
+ "create",
2140
+ "connectOrCreate",
2141
+ "disconnect",
2142
+ "set",
2143
+ "push",
2144
+ "pull"
2145
+ ]);
2146
+ var BACK_ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "delete"]);
2147
+ var BACK_MANY_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "set", "delete", "deleteMany"]);
2148
+ var idJson = (_k, v) => typeof v === "bigint" ? String(v) : v;
2149
+ var aliasSeq = 0;
2150
+ var literal2 = (s) => `'${s.replace(/'/g, "''")}'`;
2151
+ var JSON_PAIRS_PER_CALL = 50;
2152
+ var idText = (v) => v == null ? v : String(v);
2153
+ var dedupe = (items) => {
2154
+ const seen = /* @__PURE__ */ new Set();
2155
+ return items.filter((v) => {
2156
+ const k = String(v);
2157
+ if (seen.has(k)) return false;
2158
+ seen.add(k);
2159
+ return true;
2160
+ });
2161
+ };
1808
2162
  var TableRuntime = class {
1809
2163
  constructor(name, schema, options) {
1810
2164
  this.name = name;
@@ -1818,23 +2172,72 @@ var TableRuntime = class {
1818
2172
  for (const idx of options.indexes ?? []) {
1819
2173
  if (idx.unique) this.uniqueSets.push(Object.keys(idx.fields));
1820
2174
  }
2175
+ for (const j of this.tbl.joins.values()) {
2176
+ this.joinSpecs.set(j.field, {
2177
+ field: j.field,
2178
+ column: j.field,
2179
+ kind: "array",
2180
+ item: j.item,
2181
+ ddl: j.ddl,
2182
+ formatted: j.ddl,
2183
+ node: j.node
2184
+ });
2185
+ }
1821
2186
  }
1822
2187
  name;
1823
2188
  options;
1824
2189
  tbl;
1825
2190
  uniqueSets;
2191
+ /** Many-to-many fields as list columns, so filters and projections treat them alike. */
2192
+ joinSpecs = /* @__PURE__ */ new Map();
1826
2193
  fail(path, message) {
1827
2194
  throw new ModelValidationError(this.name, [{ path, message }]);
1828
2195
  }
1829
2196
  spec(field) {
1830
- return this.tbl.columns.get(field);
2197
+ return this.tbl.columns.get(field) ?? this.joinSpecs.get(field);
2198
+ }
2199
+ join(field) {
2200
+ return this.tbl.joins.get(field);
2201
+ }
2202
+ /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
2203
+ joinExpr(sql, join, owner) {
2204
+ return sql.raw(
2205
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${q(join.table)} efc_j where efc_j.owner_id = ${owner}.${q("id")}), '{}'::${join.ddl})`
2206
+ );
1831
2207
  }
1832
2208
  col(sql, field, alias) {
2209
+ const join = this.join(field);
2210
+ if (join) return this.joinExpr(sql, join, alias ?? q(this.tbl.table));
1833
2211
  const spec = this.spec(field);
1834
2212
  return sql.raw(alias ? `${alias}.${q(spec.column)}` : q(spec.column));
1835
2213
  }
2214
+ /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
2215
+ joinColumns(sql, fields, owner) {
2216
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(q(relAlias(f)))}`);
2217
+ }
2218
+ /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
2219
+ selectCols(sql, fields, owner) {
2220
+ return sql.join(
2221
+ [
2222
+ ...fields.filter((f) => !this.join(f)).map((f) => this.col(sql, f, owner)),
2223
+ ...this.joinColumns(sql, fields, owner)
2224
+ ],
2225
+ sql`, `
2226
+ );
2227
+ }
2228
+ /** Ids as stored text → the record's type (string uuids, numbers, bigints). */
2229
+ joinValues(join, items) {
2230
+ return items.map(
2231
+ (v) => v == null ? v : join.item === "bigint" ? BigInt(String(v)) : join.item === "integer" ? Number(v) : String(v)
2232
+ );
2233
+ }
1836
2234
  /** A value for `field`, encoded the way its Drizzle column does it. */
1837
2235
  val(sql, t, field, value) {
2236
+ const join = this.join(field);
2237
+ if (join) {
2238
+ const items = Array.isArray(value) ? value.map(idText) : value;
2239
+ return sql`${sql.param(items)}::${sql.raw(join.ddl)}`;
2240
+ }
1838
2241
  return sql`${sql.param(this.tbl.toDb(field, value), t[field])}`;
1839
2242
  }
1840
2243
  /** One array element / scalar compared against an array column's items. */
@@ -1845,6 +2248,10 @@ var TableRuntime = class {
1845
2248
  }
1846
2249
  fromRaw(t, row) {
1847
2250
  const keyed = {};
2251
+ for (const join of this.tbl.joins.values()) {
2252
+ const v = row[relAlias(join.field)];
2253
+ if (Array.isArray(v)) keyed[join.field] = this.joinValues(join, v);
2254
+ }
1848
2255
  for (const spec of this.tbl.columns.values()) {
1849
2256
  if (!(spec.column in row)) continue;
1850
2257
  const v = row[spec.column];
@@ -1853,14 +2260,15 @@ var TableRuntime = class {
1853
2260
  return this.tbl.fromRow(keyed);
1854
2261
  }
1855
2262
  // ── where ──────────────────────────────────────────────────────────────────
1856
- where(sql, t, where) {
2263
+ /** WHERE for `where`; `alias` qualifies the columns (subqueries, e.g. inside `include`). */
2264
+ where(sql, t, where, alias) {
1857
2265
  if (!where) return void 0;
1858
2266
  const parts = [];
1859
2267
  for (const [key, value] of Object.entries(where)) {
1860
2268
  if (value === void 0) continue;
1861
2269
  if (key === "AND" || key === "OR" || key === "NOT") {
1862
2270
  const list = Array.isArray(value) ? value : [value];
1863
- const subs = list.map((w) => this.where(sql, t, w) ?? sql`true`);
2271
+ const subs = list.map((w) => this.where(sql, t, w, alias) ?? sql`true`);
1864
2272
  if (key === "AND")
1865
2273
  parts.push(subs.length ? sql`(${sql.join(subs, sql` and `)})` : sql`true`);
1866
2274
  else if (key === "OR")
@@ -1868,22 +2276,27 @@ var TableRuntime = class {
1868
2276
  else parts.push(subs.length ? sql`not (${sql.join(subs, sql` or `)})` : sql`true`);
1869
2277
  continue;
1870
2278
  }
2279
+ const rel = this.relationFilterOf(key, value);
2280
+ if (rel) {
2281
+ parts.push(this.relationFilter(sql, rel, value, alias));
2282
+ continue;
2283
+ }
1871
2284
  const spec = this.spec(key);
1872
2285
  if (!spec) {
1873
2286
  const isNull = value === null || isPlainObject(value) && value["equals"] === null;
1874
2287
  parts.push(isNull ? sql`true` : sql`false`);
1875
2288
  continue;
1876
2289
  }
1877
- parts.push(this.fieldFilter(sql, t, spec, value));
2290
+ parts.push(this.fieldFilter(sql, t, spec, value, alias));
1878
2291
  }
1879
2292
  if (parts.length === 0) return void 0;
1880
2293
  return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
1881
2294
  }
1882
- fieldFilter(sql, t, spec, filter) {
1883
- const c = this.col(sql, spec.field);
2295
+ fieldFilter(sql, t, spec, filter, alias) {
2296
+ const c = this.col(sql, spec.field, alias);
1884
2297
  if (filter === null) return sql`${c} is null`;
1885
- if (spec.kind === "jsonb") return this.jsonFilter(sql, t, spec, filter);
1886
- if (spec.kind === "array") return this.listFilter(sql, t, spec, filter);
2298
+ if (spec.kind === "jsonb") return this.jsonFilter(sql, t, spec, filter, alias);
2299
+ if (spec.kind === "array") return this.listFilter(sql, t, spec, filter, alias);
1887
2300
  if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
1888
2301
  const insensitive = filter["mode"] === "insensitive";
1889
2302
  const text = spec.kind === "enum" || insensitive ? sql`${c}::text` : c;
@@ -1898,7 +2311,7 @@ var TableRuntime = class {
1898
2311
  break;
1899
2312
  case "not":
1900
2313
  parts.push(
1901
- v === null ? sql`${c} is not null` : isPlainObject(v) ? sql`not (${this.fieldFilter(sql, t, spec, { ...v, ...insensitive && { mode: "insensitive" } })})` : sql`not (${eq(v)})`
2314
+ v === null ? sql`${c} is not null` : isPlainObject(v) ? sql`not (${this.fieldFilter(sql, t, spec, { ...v, ...insensitive && { mode: "insensitive" } }, alias)})` : sql`not (${eq(v)})`
1902
2315
  );
1903
2316
  break;
1904
2317
  case "in":
@@ -1944,8 +2357,8 @@ var TableRuntime = class {
1944
2357
  return parts.length === 0 ? sql`true` : parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
1945
2358
  }
1946
2359
  /** Scalar lists (native arrays): has, hasEvery, hasSome, isEmpty, equals. */
1947
- listFilter(sql, t, spec, filter) {
1948
- const c = this.col(sql, spec.field);
2360
+ listFilter(sql, t, spec, filter, alias) {
2361
+ const c = this.col(sql, spec.field, alias);
1949
2362
  if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
1950
2363
  const parts = [];
1951
2364
  for (const [op, v] of Object.entries(filter)) {
@@ -1977,8 +2390,8 @@ var TableRuntime = class {
1977
2390
  return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
1978
2391
  }
1979
2392
  /** jsonb fields (embedded objects / arrays of objects / json): Prisma's JSON filters. */
1980
- jsonFilter(sql, t, spec, filter) {
1981
- const c = this.col(sql, spec.field);
2393
+ jsonFilter(sql, t, spec, filter, alias) {
2394
+ const c = this.col(sql, spec.field, alias);
1982
2395
  const json = (v) => sql`${sql.param(JSON.stringify(v))}::jsonb`;
1983
2396
  if (!isPlainObject(filter) || !Object.keys(filter).some((k) => JSON_OPS.has(k))) {
1984
2397
  return sql`${c} = ${json(filter)}`;
@@ -2035,6 +2448,7 @@ var TableRuntime = class {
2035
2448
  for (const entry of list) {
2036
2449
  for (const [field, dir] of Object.entries(entry)) {
2037
2450
  if (dir === void 0 || !this.spec(field)) continue;
2451
+ if (this.join(field)) this.fail(`orderBy.${field}`, "can't order by a many-to-many field");
2038
2452
  if (isPlainObject(dir))
2039
2453
  out.push({ field, desc: dir["sort"] === "desc", nulls: dir["nulls"] });
2040
2454
  else out.push({ field, desc: dir === "desc" });
@@ -2042,17 +2456,17 @@ var TableRuntime = class {
2042
2456
  }
2043
2457
  return out;
2044
2458
  }
2045
- orderSql(sql, list) {
2459
+ orderSql(sql, list, alias) {
2046
2460
  return sql.join(
2047
2461
  list.map(
2048
- (o) => sql`${this.col(sql, o.field)} ${sql.raw(o.desc ? "desc" : "asc")}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql``}`
2462
+ (o) => sql`${this.col(sql, o.field, alias)} ${sql.raw(o.desc ? "desc" : "asc")}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql``}`
2049
2463
  ),
2050
2464
  sql`, `
2051
2465
  );
2052
2466
  }
2053
2467
  /** The fields a result keeps, from `select` / `omit`. */
2054
2468
  projection(args) {
2055
- const all = [...this.tbl.columns.keys()];
2469
+ const all = [...this.tbl.columns.keys(), ...this.tbl.joins.keys()];
2056
2470
  if (args["select"] && args["omit"]) this.fail("select", "use either select or omit, not both");
2057
2471
  if (args["select"]) {
2058
2472
  const keep = Object.entries(args["select"]).filter(([f, on]) => on && this.spec(f)).map(([f]) => f);
@@ -2149,20 +2563,556 @@ var TableRuntime = class {
2149
2563
  }
2150
2564
  // ── reads ──────────────────────────────────────────────────────────────────
2151
2565
  async findMany(args = {}) {
2152
- const { t, sql } = await this.tbl.ready();
2566
+ const { t, sql } = await this.ready(args["where"], args["cursor"]);
2153
2567
  return this.tbl.guard(async () => {
2154
2568
  const fields = this.projection(args);
2155
- const cols = sql.join(
2156
- [.../* @__PURE__ */ new Set(["id", ...fields])].map((f) => this.col(sql, f)),
2157
- sql`, `
2569
+ const distinct = args["distinct"]?.some((f) => this.spec(f));
2570
+ const cols = this.selectCols(
2571
+ sql,
2572
+ [.../* @__PURE__ */ new Set(["id", ...fields])],
2573
+ distinct ? "efc_distinct" : void 0
2158
2574
  );
2159
- const { query, reversed } = this.readQuery(sql, t, args, cols);
2160
- const rows = (await this.tbl.client().execute(query)).rows.map(
2161
- (r) => this.project(this.fromRaw(t, r), fields)
2575
+ const include = this.includeArg(args);
2576
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : q(this.tbl.table), 1) : [];
2577
+ const { query, reversed } = this.readQuery(
2578
+ sql,
2579
+ t,
2580
+ args,
2581
+ included.length ? sql`${cols}, ${sql.join(included, sql`, `)}` : cols
2162
2582
  );
2583
+ const rows = (await this.tbl.client().execute(query)).rows.map((r) => {
2584
+ const record = this.project(this.fromRaw(t, r), fields);
2585
+ if (include) this.attachIncludes(record, r, include);
2586
+ return record;
2587
+ });
2163
2588
  return reversed ? rows.reverse() : rows;
2164
2589
  });
2165
2590
  }
2591
+ // ── include ────────────────────────────────────────────────────────────────
2592
+ relationCache;
2593
+ /** What `include` can name on this model. */
2594
+ relations() {
2595
+ if (this.relationCache) return this.relationCache;
2596
+ const out = /* @__PURE__ */ new Map();
2597
+ for (const spec of this.tbl.columns.values()) {
2598
+ const ref = spec.node?.kind === "scalar" ? spec.node.def.ref : void 0;
2599
+ if (ref)
2600
+ out.set(spec.field, {
2601
+ name: spec.field,
2602
+ kind: "one",
2603
+ via: "fk",
2604
+ target: ref,
2605
+ column: spec.column
2606
+ });
2607
+ }
2608
+ for (const join of this.tbl.joins.values()) {
2609
+ out.set(join.field, {
2610
+ name: join.field,
2611
+ kind: "many",
2612
+ via: "join",
2613
+ target: join.target,
2614
+ join
2615
+ });
2616
+ }
2617
+ for (const [name, def] of Object.entries(this.options.relations ?? {})) {
2618
+ out.set(name, {
2619
+ name,
2620
+ kind: def.hasOne ? "one" : "many",
2621
+ via: "back",
2622
+ target: def.hasOne ?? def.hasMany,
2623
+ foreignKey: def.foreignKey
2624
+ });
2625
+ }
2626
+ return this.relationCache = out;
2627
+ }
2628
+ relation(name) {
2629
+ const rel = this.relations().get(name);
2630
+ if (!rel) {
2631
+ const known = [...this.relations().keys()];
2632
+ this.fail(
2633
+ `include.${name}`,
2634
+ known.length ? `not a relation of ${this.name} (relations: ${known.join(", ")})` : `${this.name} has no relations \u2014 add a ref field or options.relations`
2635
+ );
2636
+ }
2637
+ return rel;
2638
+ }
2639
+ includeArg(args) {
2640
+ const include = args["include"];
2641
+ if (include === void 0) return void 0;
2642
+ if (!isPlainObject(include)) this.fail("include", "must be an object");
2643
+ return Object.values(include).some(Boolean) ? include : void 0;
2644
+ }
2645
+ /** SELECT items loading `include` for rows of this table aliased `owner`. */
2646
+ async includeColumns(sql, include, owner, depth) {
2647
+ const out = [];
2648
+ for (const [name, arg] of Object.entries(include)) {
2649
+ if (!arg) continue;
2650
+ const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
2651
+ out.push(sql`${expr} as ${sql.raw(q(incAlias(name)))}`);
2652
+ }
2653
+ return out;
2654
+ }
2655
+ /**
2656
+ * One relation as a correlated subquery yielding jsonb: a record (or null) for one, an
2657
+ * array of records for many. Nested includes nest inside it, so a read is one statement.
2658
+ */
2659
+ async relationExpr(sql, rel, args, owner, depth) {
2660
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2661
+ const { t } = await T.ready(args["where"]);
2662
+ const a = `efc_r${depth}`;
2663
+ const obj = await T.jsonRecord(sql, t, args, a, depth + 1);
2664
+ const { from, cond, defaultOrder } = this.relationSource(rel, owner, a, `efc_j${depth}`);
2665
+ if (rel.via === "fk") return sql`(select ${obj} from ${sql.raw(from)} where ${sql.raw(cond)})`;
2666
+ if (rel.kind === "one") {
2667
+ return sql`(select ${obj} from ${sql.raw(from)} where ${sql.raw(cond)} limit 1)`;
2668
+ }
2669
+ const where = T.where(sql, t, args["where"], a);
2670
+ const order = args["orderBy"] ? T.orderSql(sql, T.orderList(args["orderBy"]), a) : sql.raw(defaultOrder);
2671
+ const take = args["take"];
2672
+ if (take !== void 0 && (!Number.isInteger(take) || take < 0)) {
2673
+ this.fail(`include.${rel.name}.take`, "must be a whole number \u2265 0 inside include");
2674
+ }
2675
+ const s = `efc_s${depth}`;
2676
+ return sql`coalesce((select jsonb_agg(${sql.raw(`${s}.o order by ${s}.n`)}) from (select ${obj} as o, row_number() over (order by ${order}) as n from ${sql.raw(from)} where ${sql.raw(cond)}${where ? sql` and ${where}` : sql``} order by ${order}${take !== void 0 ? sql` limit ${sql.param(take)}` : sql``}${args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``}) ${sql.raw(s)}), '[]'::jsonb)`;
2677
+ }
2678
+ /**
2679
+ * Where a relation's records come from, for rows of this table aliased `owner`: the FROM
2680
+ * (target aliased `a`, plus its join table aliased `j` when there is one) and the
2681
+ * condition tying them to the owner row.
2682
+ */
2683
+ relationSource(rel, owner, a, j) {
2684
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2685
+ const target = `${q(T.tbl.table)} ${a}`;
2686
+ const ownerId = `${owner}.${q("id")}`;
2687
+ if (rel.via === "fk") {
2688
+ return {
2689
+ T,
2690
+ from: target,
2691
+ cond: `${a}.${q("id")} = ${owner}.${q(rel.column)}`,
2692
+ defaultOrder: `${a}.${q("id")}`
2693
+ };
2694
+ }
2695
+ let from;
2696
+ let cond;
2697
+ let defaultOrder;
2698
+ if (rel.via === "join") {
2699
+ from = `${q(rel.join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.ref_id`;
2700
+ cond = `${j}.owner_id = ${ownerId}`;
2701
+ defaultOrder = `${j}.position`;
2702
+ } else {
2703
+ const join = T.tbl.joins.get(rel.foreignKey);
2704
+ const column = T.tbl.columns.get(rel.foreignKey);
2705
+ const refs = join ? join.target : column?.node?.kind === "scalar" && column.node.def.ref;
2706
+ if (refs !== this.name) {
2707
+ throw new Error(
2708
+ `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} must be a ref to ${this.name}`
2709
+ );
2710
+ }
2711
+ if (join) {
2712
+ if (rel.kind === "one") {
2713
+ throw new Error(
2714
+ `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
2715
+ );
2716
+ }
2717
+ from = `${q(join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.owner_id`;
2718
+ cond = `${j}.ref_id = ${ownerId}`;
2719
+ } else {
2720
+ if (rel.kind === "one" && !column.node.def.unique) {
2721
+ throw new Error(
2722
+ `[EFC] ${this.name}.${rel.name}: hasOne needs ${rel.target}.${rel.foreignKey} to be unique (one ${rel.target} per ${this.name}) \u2014 or use hasMany`
2723
+ );
2724
+ }
2725
+ from = target;
2726
+ cond = `${a}.${q(column.column)} = ${ownerId}`;
2727
+ }
2728
+ defaultOrder = `${a}.${q("id")}`;
2729
+ }
2730
+ return { T, from, cond, defaultOrder };
2731
+ }
2732
+ // ── nested writes ──────────────────────────────────────────────────────────
2733
+ /** Whether `data` writes related records (connect / create / … on a relation). */
2734
+ hasNested(data) {
2735
+ if (!isPlainObject(data)) return false;
2736
+ return Object.entries(data).some(([key, v]) => {
2737
+ const rel = this.relations().get(key);
2738
+ if (!rel || v === void 0) return false;
2739
+ if (rel.via === "back") return true;
2740
+ if (!isPlainObject(v)) return false;
2741
+ if (rel.via === "fk") return true;
2742
+ const keys = Object.keys(v);
2743
+ if (keys.some((k) => !["set", "push", "pull"].includes(k))) return true;
2744
+ return rel.via === "join" && Array.isArray(v["set"]) && v["set"].some(isPlainObject);
2745
+ });
2746
+ }
2747
+ /** The id of the `rel` record a unique where (or a bare id) names; 400 when none does. */
2748
+ async connectId(rel, w, path) {
2749
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2750
+ const where = isPlainObject(w) ? w : { id: w };
2751
+ const found = await T.findUnique({ where, select: { id: true } });
2752
+ if (!found) {
2753
+ throw new ModelValidationError(this.name, [
2754
+ { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
2755
+ ]);
2756
+ }
2757
+ return found["id"];
2758
+ }
2759
+ async connectOrCreateId(rel, arg, path) {
2760
+ if (!isPlainObject(arg) || !isPlainObject(arg["where"]) || !isPlainObject(arg["create"])) {
2761
+ this.fail(path, "connectOrCreate needs { where, create }");
2762
+ }
2763
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2764
+ const found = await T.findUnique({ where: arg["where"], select: { id: true } });
2765
+ return found ? found["id"] : (await T.createNested({ data: arg["create"] }))["id"];
2766
+ }
2767
+ /**
2768
+ * Splits nested relation writes out of `data`: own refs and many-to-many fields are
2769
+ * resolved to ids before the row is written; back-relations become steps to run with
2770
+ * the owner's id afterwards. Runs inside the caller's transaction.
2771
+ */
2772
+ async resolveNested(data, mode) {
2773
+ const out = { ...data };
2774
+ const after = [];
2775
+ const list = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
2776
+ for (const [key, v] of Object.entries(data)) {
2777
+ const rel = this.relations().get(key);
2778
+ if (!rel || v === void 0) continue;
2779
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2780
+ const ops = isPlainObject(v) ? v : void 0;
2781
+ for (const op of Object.keys(ops ?? {})) {
2782
+ const allowed = rel.via === "fk" ? ONE_OPS : rel.via === "join" ? JOIN_OPS : rel.kind === "one" ? BACK_ONE_OPS : BACK_MANY_OPS;
2783
+ if (!allowed.has(op)) {
2784
+ this.fail(key, `"${op}" isn't a nested write here (use ${[...allowed].join(", ")})`);
2785
+ }
2786
+ }
2787
+ if (rel.via === "fk") {
2788
+ if (!ops) continue;
2789
+ if (ops["disconnect"]) {
2790
+ if (mode === "create") this.fail(key, "disconnect only applies to updates");
2791
+ out[key] = null;
2792
+ } else if (ops["connect"] !== void 0) {
2793
+ out[key] = await this.connectId(rel, ops["connect"], key);
2794
+ } else if (ops["connectOrCreate"] !== void 0) {
2795
+ out[key] = await this.connectOrCreateId(rel, ops["connectOrCreate"], key);
2796
+ } else if (ops["create"] !== void 0) {
2797
+ out[key] = (await T.createNested({ data: ops["create"] }))["id"];
2798
+ }
2799
+ continue;
2800
+ }
2801
+ if (rel.via === "join") {
2802
+ if (!ops || !this.hasNested({ [key]: v })) continue;
2803
+ const ids = async (items) => {
2804
+ const got = [];
2805
+ for (const w of items) got.push(await this.connectId(rel, w, key));
2806
+ return got;
2807
+ };
2808
+ const added = await ids(list(ops["connect"]));
2809
+ for (const a of list(ops["connectOrCreate"])) {
2810
+ added.push(await this.connectOrCreateId(rel, a, key));
2811
+ }
2812
+ for (const c of list(ops["create"])) added.push((await T.createNested({ data: c }))["id"]);
2813
+ const removed = [];
2814
+ for (const w of list(ops["disconnect"])) {
2815
+ const where = isPlainObject(w) ? w : { id: w };
2816
+ const found = await T.findUnique({ where, select: { id: true } });
2817
+ if (found) removed.push(found["id"]);
2818
+ }
2819
+ const gone = new Set(removed.map(String));
2820
+ if (ops["set"] !== void 0 || mode === "create") {
2821
+ const base = ops["set"] === void 0 ? [] : await ids(list(ops["set"]));
2822
+ const all = dedupe([...base, ...added]).filter((x) => !gone.has(String(x)));
2823
+ out[key] = mode === "create" ? all : { set: all };
2824
+ } else {
2825
+ out[key] = {
2826
+ ...added.length && { push: added },
2827
+ ...removed.length && { pull: removed }
2828
+ };
2829
+ }
2830
+ continue;
2831
+ }
2832
+ delete out[key];
2833
+ const fk = rel.foreignKey;
2834
+ const many = T.tbl.joins.has(fk);
2835
+ const mine = (owner) => many ? { [fk]: { has: owner } } : { [fk]: owner };
2836
+ const whereOf = (w) => isPlainObject(w) ? w : { id: w };
2837
+ const link = async (owner, w) => {
2838
+ if (many) {
2839
+ const id = await this.connectId(rel, w, key);
2840
+ await T.updateNested({ where: { id }, data: { [fk]: { push: owner } } });
2841
+ } else {
2842
+ try {
2843
+ await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
2844
+ } catch (err) {
2845
+ if (isHttpError(err) && err.statusCode === 404) {
2846
+ throw new ModelValidationError(this.name, [
2847
+ {
2848
+ path: key,
2849
+ message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
2850
+ }
2851
+ ]);
2852
+ }
2853
+ throw err;
2854
+ }
2855
+ }
2856
+ };
2857
+ const unlink = (owner, where) => many ? T.updateManyLinks(fk, owner, where) : T.updateMany(
2858
+ { where: { AND: [mine(owner), ...where ? [where] : []] }, data: { [fk]: null } },
2859
+ false
2860
+ );
2861
+ const createChild = (owner, c) => {
2862
+ if (!isPlainObject(c)) this.fail(key, "create needs record data");
2863
+ return T.createNested({ data: { ...c, [fk]: many ? [owner] : owner } });
2864
+ };
2865
+ after.push(async (owner) => {
2866
+ if (rel.kind === "one") {
2867
+ if (mode === "update" && (ops?.["create"] || ops?.["connect"] || ops?.["disconnect"])) {
2868
+ await unlink(owner);
2869
+ }
2870
+ if (ops?.["delete"]) await T.deleteMany({ where: mine(owner) });
2871
+ if (ops?.["connect"] !== void 0) await link(owner, ops["connect"]);
2872
+ if (ops?.["create"] !== void 0) await createChild(owner, ops["create"]);
2873
+ return;
2874
+ }
2875
+ if (ops?.["set"] !== void 0) {
2876
+ const keep = list(ops["set"]).map(whereOf);
2877
+ await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
2878
+ for (const w of keep) await link(owner, w);
2879
+ }
2880
+ for (const w of list(ops?.["disconnect"])) await unlink(owner, whereOf(w));
2881
+ for (const w of list(ops?.["delete"]))
2882
+ await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
2883
+ if (ops?.["deleteMany"] !== void 0) {
2884
+ for (const w of list(ops["deleteMany"])) {
2885
+ await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
2886
+ }
2887
+ }
2888
+ for (const w of list(ops?.["connect"])) await link(owner, w);
2889
+ for (const c of list(ops?.["create"])) await createChild(owner, c);
2890
+ });
2891
+ }
2892
+ return { data: out, after };
2893
+ }
2894
+ /** Removes `owner` from the many-to-many field `fk` of the records `where` matches. */
2895
+ async updateManyLinks(fk, owner, where) {
2896
+ const matches = await this.findMany({
2897
+ where: { AND: [{ [fk]: { has: owner } }, ...where ? [where] : []] },
2898
+ select: { id: true }
2899
+ });
2900
+ const { sql } = await this.ready();
2901
+ await this.applyJoins(
2902
+ sql,
2903
+ matches.map((m) => ({ id: m["id"], ops: [{ field: fk, mode: "pull", items: [owner] }] }))
2904
+ );
2905
+ }
2906
+ /** Runs a write whose data may hold nested writes, all in one transaction. */
2907
+ withNested(data, mode, write) {
2908
+ if (!this.hasNested(data)) return write(data);
2909
+ return transaction(async () => {
2910
+ const { data: plain, after } = await this.resolveNested(data, mode);
2911
+ const record = await write(plain);
2912
+ for (const step of after) await step(record["id"]);
2913
+ return record;
2914
+ });
2915
+ }
2916
+ createNested(args) {
2917
+ return this.withNested(args["data"], "create", (data) => this.create({ ...args, data }));
2918
+ }
2919
+ updateNested(args) {
2920
+ return this.withNested(args["data"], "update", (data) => this.update({ ...args, data }));
2921
+ }
2922
+ /** upsert with nested writes: find, then update or create — in one transaction. */
2923
+ async upsertNested(args) {
2924
+ if (!this.hasNested(args["create"]) && !this.hasNested(args["update"]))
2925
+ return this.upsert(args);
2926
+ this.uniqueKey(args["where"], "upsert");
2927
+ return transaction(async () => {
2928
+ const found = await this.findUnique({ where: args["where"], select: { id: true } });
2929
+ const { create, update, where, ...rest } = args;
2930
+ if (found)
2931
+ return this.updateNested({ ...rest, where: { id: found["id"] }, data: update ?? {} });
2932
+ const key = this.uniqueKey(where, "upsert");
2933
+ const data = { ...create };
2934
+ for (const f of key) if (data[f] === void 0) data[f] = where[f];
2935
+ return this.createNested({ ...rest, data });
2936
+ });
2937
+ }
2938
+ /** createMany / updateMany write rows only, as in Prisma. */
2939
+ noNested(data, op) {
2940
+ for (const d of Array.isArray(data) ? data : [data]) {
2941
+ if (this.hasNested(d))
2942
+ this.fail(
2943
+ "data",
2944
+ `${op} doesn't take nested writes \u2014 use ${op === "updateMany" ? "update" : "create"}`
2945
+ );
2946
+ }
2947
+ }
2948
+ // ── relation filters ───────────────────────────────────────────────────────
2949
+ /** The compiled Drizzle table, once `ready()` has run (relation filters need it sync). */
2950
+ t;
2951
+ /**
2952
+ * Compiles (and auto-syncs) this table, and every table a relation filter in `wheres`
2953
+ * reaches, so `where()` can build those filters synchronously.
2954
+ */
2955
+ async ready(...wheres) {
2956
+ const out = await this.tbl.ready();
2957
+ this.t = out.t;
2958
+ for (const w of wheres) await this.prepareWhere(w);
2959
+ return out;
2960
+ }
2961
+ async prepareWhere(where) {
2962
+ if (!isPlainObject(where)) return;
2963
+ for (const [key, value] of Object.entries(where)) {
2964
+ if (key === "AND" || key === "OR" || key === "NOT") {
2965
+ for (const w of Array.isArray(value) ? value : [value]) await this.prepareWhere(w);
2966
+ continue;
2967
+ }
2968
+ const rel = this.relationFilterOf(key, value);
2969
+ if (!rel) continue;
2970
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2971
+ for (const sub of Object.values(value)) await T.ready(sub);
2972
+ }
2973
+ }
2974
+ /** The relation `where.key` filters on, when `value` is a relation filter. */
2975
+ relationFilterOf(key, value) {
2976
+ const rel = this.relations().get(key);
2977
+ if (!rel) return void 0;
2978
+ const ops = rel.kind === "many" ? ["some", "every", "none"] : ["is", "isNot"];
2979
+ const keys = isPlainObject(value) ? Object.keys(value) : [];
2980
+ const isFilter = keys.length > 0 && keys.every((k) => ops.includes(k));
2981
+ if (!isFilter && rel.via === "back") {
2982
+ this.fail(`where.${key}`, `filter a relation with ${ops.join(" / ")}`);
2983
+ }
2984
+ return isFilter ? rel : void 0;
2985
+ }
2986
+ /** some / every / none, is / isNot → EXISTS subqueries on the related table. */
2987
+ relationFilter(sql, rel, filter, owner) {
2988
+ const a = `efc_f${++aliasSeq}`;
2989
+ const { T, from, cond } = this.relationSource(
2990
+ rel,
2991
+ owner ?? q(this.tbl.table),
2992
+ a,
2993
+ `efc_fj${aliasSeq}`
2994
+ );
2995
+ if (T.t === void 0) {
2996
+ throw new Error(
2997
+ `[EFC] ${this.name}: relation filter on ${rel.name} before its table was ready`
2998
+ );
2999
+ }
3000
+ const exists = (w, negate = false) => {
3001
+ const inner = isPlainObject(w) ? T.where(sql, T.t, w, a) : void 0;
3002
+ const extra = inner ? negate ? sql` and not (${inner})` : sql` and ${inner}` : negate ? sql` and false` : sql``;
3003
+ return sql`exists (select 1 from ${sql.raw(from)} where ${sql.raw(cond)}${extra})`;
3004
+ };
3005
+ const parts = [];
3006
+ for (const [op, w] of Object.entries(filter)) {
3007
+ if (w === void 0) continue;
3008
+ switch (op) {
3009
+ case "some":
3010
+ parts.push(exists(w));
3011
+ break;
3012
+ case "none":
3013
+ parts.push(sql`not ${exists(w)}`);
3014
+ break;
3015
+ case "every":
3016
+ parts.push(sql`not ${exists(w, true)}`);
3017
+ break;
3018
+ case "is":
3019
+ parts.push(w === null ? sql`not ${exists(void 0)}` : exists(w));
3020
+ break;
3021
+ case "isNot":
3022
+ parts.push(w === null ? exists(void 0) : sql`not ${exists(w)}`);
3023
+ break;
3024
+ }
3025
+ }
3026
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
3027
+ }
3028
+ /** A record of this table (aliased `alias`) as jsonb, with its own includes. */
3029
+ async jsonRecord(sql, t, args, alias, depth) {
3030
+ const include = this.includeArg(args);
3031
+ const pairs = [];
3032
+ for (const f of this.projection(args)) {
3033
+ if (include?.[f]) continue;
3034
+ pairs.push(sql`${sql.raw(literal2(f))}, ${this.jsonValue(sql, f, alias)}`);
3035
+ }
3036
+ for (const [name, arg] of Object.entries(include ?? {})) {
3037
+ if (!arg) continue;
3038
+ const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), alias, depth);
3039
+ pairs.push(sql`${sql.raw(literal2(name))}, ${expr}`);
3040
+ }
3041
+ if (pairs.length === 0) return sql`'{}'::jsonb`;
3042
+ const chunks = [];
3043
+ for (let i = 0; i < pairs.length; i += JSON_PAIRS_PER_CALL) {
3044
+ chunks.push(
3045
+ sql`jsonb_build_object(${sql.join(pairs.slice(i, i + JSON_PAIRS_PER_CALL), sql`, `)})`
3046
+ );
3047
+ }
3048
+ return sql.join(chunks, sql` || `);
3049
+ }
3050
+ // JSON can't hold bigints exactly, NaN/Infinity or decimals verbatim: send those as text.
3051
+ jsonValue(sql, field, alias) {
3052
+ const c = this.col(sql, field, alias);
3053
+ const spec = this.spec(field);
3054
+ if (this.join(field)) return sql`${c}::text[]`;
3055
+ const textual = (k) => k === "bigint" || k === "double" || k === "numeric";
3056
+ if (spec.kind === "array") return textual(spec.item) ? sql`${c}::text[]` : c;
3057
+ return textual(spec.kind) ? sql`${c}::text` : c;
3058
+ }
3059
+ /** A record from `jsonRecord` → the same record a direct read returns. */
3060
+ fromJson(json, args) {
3061
+ const include = this.includeArg(args);
3062
+ const keyed = {};
3063
+ for (const f of this.projection(args)) {
3064
+ if (include?.[f]) continue;
3065
+ const v = json[f];
3066
+ const join = this.join(f);
3067
+ if (v == null || join) {
3068
+ keyed[f] = join && Array.isArray(v) ? this.joinValues(join, v) : v;
3069
+ continue;
3070
+ }
3071
+ const spec = this.spec(f);
3072
+ const one = (kind, x) => x == null ? x : kind === "timestamptz" ? new Date(x) : kind === "double" ? Number(x) : kind === "bigint" && spec.bigintAs === "number" ? Number(x) : x;
3073
+ keyed[f] = spec.kind === "array" && Array.isArray(v) ? v.map((x) => one(spec.item, x)) : spec.kind === "array" ? v : one(spec.kind, v);
3074
+ }
3075
+ const record = this.tbl.fromRow(keyed);
3076
+ for (const [name, arg] of Object.entries(include ?? {})) {
3077
+ if (arg) record[name] = this.decodeRelation(this.relation(name), json[name], relArgs(arg));
3078
+ }
3079
+ return record;
3080
+ }
3081
+ decodeRelation(rel, value, args) {
3082
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
3083
+ if (rel.kind === "one") return value == null ? null : T.fromJson(value, args);
3084
+ return (value ?? []).map((v) => T.fromJson(v, args));
3085
+ }
3086
+ attachIncludes(record, row, include) {
3087
+ for (const [name, arg] of Object.entries(include)) {
3088
+ if (!arg) continue;
3089
+ record[name] = this.decodeRelation(this.relation(name), row[incAlias(name)], relArgs(arg));
3090
+ }
3091
+ }
3092
+ /** A write with `include`: write, then read the record back with its relations. */
3093
+ async withInclude(args, write) {
3094
+ if (!this.includeArg(args ?? {})) return write(args);
3095
+ const { include, select, omit, ...rest } = args;
3096
+ const record = await write(rest);
3097
+ const [full] = await this.findMany({ where: { id: record["id"] }, select, omit, include });
3098
+ return full ?? record;
3099
+ }
3100
+ /** `delete` with `include`: read the record and its relations, then delete it. */
3101
+ async deleteWithInclude(args) {
3102
+ if (!this.includeArg(args)) return this.delete(args);
3103
+ this.uniqueKey(args["where"], "delete");
3104
+ return transaction(async () => {
3105
+ const [found] = await this.findMany({
3106
+ where: args["where"],
3107
+ select: args["select"],
3108
+ omit: args["omit"],
3109
+ include: args["include"],
3110
+ take: 1
3111
+ });
3112
+ await this.delete({ where: args["where"] });
3113
+ return found;
3114
+ });
3115
+ }
2166
3116
  async findFirst(args = {}) {
2167
3117
  const take = args["take"];
2168
3118
  const rows = await this.findMany({ ...args, take: take !== void 0 && take < 0 ? -1 : 1 });
@@ -2170,7 +3120,12 @@ var TableRuntime = class {
2170
3120
  }
2171
3121
  async findUnique(args) {
2172
3122
  this.uniqueKey(args["where"], "findUnique");
2173
- return this.findFirst({ where: args["where"], select: args["select"], omit: args["omit"] });
3123
+ return this.findFirst({
3124
+ where: args["where"],
3125
+ select: args["select"],
3126
+ omit: args["omit"],
3127
+ include: args["include"]
3128
+ });
2174
3129
  }
2175
3130
  async orThrow(p) {
2176
3131
  const r = await p;
@@ -2178,7 +3133,7 @@ var TableRuntime = class {
2178
3133
  return r;
2179
3134
  }
2180
3135
  async count(args = {}) {
2181
- const { t, sql } = await this.tbl.ready();
3136
+ const { t, sql } = await this.ready(args["where"]);
2182
3137
  return this.tbl.guard(async () => {
2183
3138
  const select = args["select"];
2184
3139
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
@@ -2217,6 +3172,9 @@ var TableRuntime = class {
2217
3172
  }
2218
3173
  const spec = this.spec(field);
2219
3174
  if (!spec) this.fail(`${agg}.${field}`, "unknown field");
3175
+ if (agg !== "_count" && this.join(field)) {
3176
+ this.fail(`${agg}.${field}`, `${agg} doesn't apply to a many-to-many field`);
3177
+ }
2220
3178
  if ((agg === "_sum" || agg === "_avg") && !NUMERIC_KINDS.has(spec.kind)) {
2221
3179
  this.fail(`${agg}.${field}`, `${agg} needs a numeric field`);
2222
3180
  }
@@ -2251,7 +3209,7 @@ var TableRuntime = class {
2251
3209
  return out;
2252
3210
  }
2253
3211
  async aggregate(args = {}) {
2254
- const { t, sql } = await this.tbl.ready();
3212
+ const { t, sql } = await this.ready(args["where"]);
2255
3213
  return this.tbl.guard(async () => {
2256
3214
  const specs = this.aggregateSpec(args);
2257
3215
  if (specs.length === 0) return {};
@@ -2301,11 +3259,14 @@ var TableRuntime = class {
2301
3259
  return parts.length ? sql.join(parts, sql` and `) : void 0;
2302
3260
  }
2303
3261
  async groupBy(args) {
2304
- const { t, sql } = await this.tbl.ready();
3262
+ const { t, sql } = await this.ready(args["where"]);
2305
3263
  return this.tbl.guard(async () => {
2306
3264
  const by = Array.isArray(args["by"]) ? args["by"] : [args["by"]];
2307
3265
  if (by.length === 0) this.fail("by", "groupBy needs at least one field");
2308
- for (const f of by) if (!this.spec(f)) this.fail(`by.${f}`, "unknown field");
3266
+ for (const f of by) {
3267
+ if (!this.spec(f)) this.fail(`by.${f}`, "unknown field");
3268
+ if (this.join(f)) this.fail(`by.${f}`, "can't group by a many-to-many field");
3269
+ }
2309
3270
  const specs = this.aggregateSpec(args);
2310
3271
  const select = sql.join(
2311
3272
  [
@@ -2353,9 +3314,10 @@ var TableRuntime = class {
2353
3314
  });
2354
3315
  }
2355
3316
  // ── writes ─────────────────────────────────────────────────────────────────
2356
- /** Prisma update data → SET expressions, validated. */
3317
+ /** Prisma update data → SET expressions and many-to-many changes, validated. */
2357
3318
  async setList(sql, t, data, alias) {
2358
3319
  const sets = [];
3320
+ const joinOps = [];
2359
3321
  const plain = {};
2360
3322
  const issues = [];
2361
3323
  const ref = (f) => this.col(sql, f, alias);
@@ -2365,6 +3327,20 @@ var TableRuntime = class {
2365
3327
  if (!spec || field === "id" || field === this.tbl.ts.createdAt || field === this.tbl.ts.updatedAt) {
2366
3328
  continue;
2367
3329
  }
3330
+ if (this.join(field)) {
3331
+ const entries = isPlainObject(value) ? Object.entries(value) : [["set", value]];
3332
+ for (const [op, v] of entries) {
3333
+ if (v === void 0) continue;
3334
+ if (op !== "set" && op !== "push" && op !== "pull") {
3335
+ issues.push({ path: field, message: `unknown update operation "${op}"` });
3336
+ continue;
3337
+ }
3338
+ const items = v === null ? [] : Array.isArray(v) ? v : op !== "set" ? [v] : v;
3339
+ await this.tbl.validate({ [field]: items }, true);
3340
+ joinOps.push({ field, mode: op, items });
3341
+ }
3342
+ continue;
3343
+ }
2368
3344
  const ops = isPlainObject(value) && spec.kind !== "jsonb" ? value : void 0;
2369
3345
  if (!ops) {
2370
3346
  plain[field] = value;
@@ -2405,12 +3381,107 @@ var TableRuntime = class {
2405
3381
  sql`${this.col(sql, field)} = ${v === null ? sql`null` : this.val(sql, t, field, v)}`
2406
3382
  );
2407
3383
  }
2408
- if (this.tbl.ts.updatedAt && sets.length) {
3384
+ if (this.tbl.ts.updatedAt && (sets.length || joinOps.length)) {
2409
3385
  sets.push(
2410
3386
  sql`${this.col(sql, this.tbl.ts.updatedAt)} = ${this.val(sql, t, this.tbl.ts.updatedAt, /* @__PURE__ */ new Date())}`
2411
3387
  );
2412
3388
  }
2413
- return sets;
3389
+ return { sets, joinOps };
3390
+ }
3391
+ // ── many-to-many links ─────────────────────────────────────────────────────
3392
+ /** Splits an insert row into its columns and the `set` ops for its many-to-many fields. */
3393
+ splitJoins(row) {
3394
+ if (this.tbl.joins.size === 0) return { row, ops: [] };
3395
+ const out = {};
3396
+ const ops = [];
3397
+ for (const [k, v] of Object.entries(row)) {
3398
+ if (this.join(k)) ops.push({ field: k, mode: "set", items: v ?? [] });
3399
+ else out[k] = v;
3400
+ }
3401
+ return { row: out, ops };
3402
+ }
3403
+ exec(query) {
3404
+ return this.tbl.client().execute(query);
3405
+ }
3406
+ /** Applies many-to-many changes for each owner id, in the current transaction. */
3407
+ async applyJoins(sql, ops) {
3408
+ const idDdl = this.tbl.columns.get("id").ddl;
3409
+ const byField = /* @__PURE__ */ new Map();
3410
+ for (const { id, ops: list } of ops) {
3411
+ for (const op of list) {
3412
+ const entry = byField.get(op.field) ?? [];
3413
+ entry.push({ id, op });
3414
+ byField.set(op.field, entry);
3415
+ }
3416
+ }
3417
+ for (const [field, entries] of byField) {
3418
+ const join = this.join(field);
3419
+ const jt = sql.raw(q(join.table));
3420
+ const sets = entries.filter((e) => e.op.mode === "set");
3421
+ if (sets.length) {
3422
+ const owners2 = sets.map((e) => idText(e.id));
3423
+ const lists = sets.map((e) => `{${dedupe(e.op.items).map(idText).join(",")}}`);
3424
+ await this.exec(
3425
+ sql`delete from ${jt} as efc_j using unnest(${sql.param(owners2)}::${sql.raw(idDdl)}[], ${sql.param(lists)}::text[]) as w(owner, ids) where efc_j.owner_id = w.owner and not (efc_j.ref_id = any(w.ids::${sql.raw(join.ddl)}))`
3426
+ );
3427
+ }
3428
+ const pulls = entries.filter((e) => e.op.mode === "pull");
3429
+ if (pulls.length) {
3430
+ const pairs = pulls.flatMap((e) => dedupe(e.op.items).map((ref) => [e.id, ref]));
3431
+ if (pairs.length) {
3432
+ await this.exec(
3433
+ sql`delete from ${jt} as efc_j using unnest(${sql.param(pairs.map((p) => idText(p[0])))}::${sql.raw(idDdl)}[], ${sql.param(pairs.map((p) => idText(p[1])))}::${sql.raw(join.ddl)}) as d(o, r) where efc_j.owner_id = d.o and efc_j.ref_id = d.r`
3434
+ );
3435
+ }
3436
+ }
3437
+ const adds = entries.filter((e) => e.op.mode !== "pull");
3438
+ const links = [];
3439
+ for (const { id, op } of adds) {
3440
+ dedupe(op.items).forEach((ref, i) => links.push([id, ref, i + 1]));
3441
+ }
3442
+ if (links.length === 0) continue;
3443
+ const pushes = new Set(adds.filter((e) => e.op.mode === "push").map((e) => idText(e.id)));
3444
+ const owners = sql`${sql.param(links.map((l) => idText(l[0])))}::${sql.raw(idDdl)}[]`;
3445
+ const refs = sql`${sql.param(links.map((l) => idText(l[1])))}::${sql.raw(join.ddl)}`;
3446
+ const pos = sql`${sql.param(links.map((l) => l[2]))}::integer[]`;
3447
+ if (pushes.size === 0) {
3448
+ await this.exec(
3449
+ sql`insert into ${jt} (owner_id, ref_id, position) select * from unnest(${owners}, ${refs}, ${pos}) on conflict (owner_id, ref_id) do update set position = excluded.position`
3450
+ );
3451
+ } else {
3452
+ await this.exec(
3453
+ sql`insert into ${jt} (owner_id, ref_id, position) select l.o, l.r, coalesce((select max(efc_j.position) from ${jt} efc_j where efc_j.owner_id = l.o), 0) + l.p from unnest(${owners}, ${refs}, ${pos}) as l(o, r, p) on conflict (owner_id, ref_id) do nothing`
3454
+ );
3455
+ }
3456
+ }
3457
+ }
3458
+ /** The current links of `fields` for these owners, read in one statement. */
3459
+ async loadJoins(sql, ids, fields) {
3460
+ const out = /* @__PURE__ */ new Map();
3461
+ const joins = fields.map((f) => this.join(f)).filter(Boolean);
3462
+ if (joins.length === 0 || ids.length === 0) return out;
3463
+ const idDdl = this.tbl.columns.get("id").ddl;
3464
+ const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
3465
+ const parts = joins.map(
3466
+ (j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(q(j.table))} where owner_id = any(${owners}) group by owner_id`
3467
+ );
3468
+ const { rows } = await this.exec(sql.join(parts, sql` union all `));
3469
+ for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
3470
+ for (const r of rows) {
3471
+ const join = this.join(r["f"]);
3472
+ out.get(join.field).set(r["o"], this.joinValues(join, r["ids"]));
3473
+ }
3474
+ return out;
3475
+ }
3476
+ /** Writes the loaded links into records (owners without any get an empty list). */
3477
+ attachJoins(records, loaded) {
3478
+ for (const [field, byOwner] of loaded) {
3479
+ for (const r of records) r[field] = byOwner.get(String(r["id"])) ?? [];
3480
+ }
3481
+ }
3482
+ /** Runs `fn` in a transaction when it changes links (main statement + link statements). */
3483
+ withLinks(changesLinks, fn) {
3484
+ return changesLinks ? transaction(fn) : fn();
2414
3485
  }
2415
3486
  insertSql(sql, t, rows) {
2416
3487
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
@@ -2434,67 +3505,163 @@ var TableRuntime = class {
2434
3505
  return this.tbl.prepareInsert(data);
2435
3506
  }
2436
3507
  async create(args) {
2437
- const { t, sql } = await this.tbl.ready();
3508
+ const { t, sql } = await this.ready();
2438
3509
  return this.tbl.guard(async () => {
2439
- const row = await this.prepare(args["data"]);
2440
- const { head, values } = this.insertSql(sql, t, [row]);
2441
- const [inserted] = (await this.tbl.client().execute(sql`${head} values ${values} returning *`)).rows;
2442
- return this.project(this.fromRaw(t, inserted), this.projection(args));
3510
+ const { row, ops } = this.splitJoins(await this.prepare(args["data"]));
3511
+ return this.withLinks(
3512
+ ops.some((o) => o.items.length),
3513
+ async () => {
3514
+ const { head, values } = this.insertSql(sql, t, [row]);
3515
+ const [inserted] = (await this.exec(sql`${head} values ${values} returning *`)).rows;
3516
+ const record = this.fromRaw(t, inserted);
3517
+ await this.applyJoins(sql, [
3518
+ { id: record["id"], ops: ops.filter((o) => o.items.length) }
3519
+ ]);
3520
+ for (const join of this.tbl.joins.values()) {
3521
+ const op = ops.find((o) => o.field === join.field);
3522
+ record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
3523
+ }
3524
+ return this.project(record, this.projection(args));
3525
+ }
3526
+ );
2443
3527
  });
2444
3528
  }
2445
3529
  async createMany(args, returning) {
2446
- const { t, sql } = await this.tbl.ready();
3530
+ const { t, sql } = await this.ready();
2447
3531
  return this.tbl.guard(async () => {
2448
3532
  const data = Array.isArray(args["data"]) ? args["data"] : [args["data"]];
2449
3533
  if (data.length === 0) return returning ? [] : { count: 0 };
2450
- const rows = await Promise.all(data.map((d) => this.prepare(d)));
2451
- const { head, values } = this.insertSql(sql, t, rows);
2452
- const conflict = args["skipDuplicates"] ? sql` on conflict do nothing` : sql``;
2453
- const result = await this.tbl.client().execute(sql`${head} values ${values}${conflict}${returning ? sql` returning *` : sql``}`);
2454
- if (!returning) return { count: result.rowCount ?? 0 };
2455
- const fields = this.projection(args);
2456
- return result.rows.map((r) => this.project(this.fromRaw(t, r), fields));
3534
+ const split = (await Promise.all(data.map((d) => this.prepare(d)))).map(
3535
+ (r) => this.splitJoins(r)
3536
+ );
3537
+ const linked = split.some((x) => x.ops.some((o) => o.items.length));
3538
+ return this.withLinks(linked, async () => {
3539
+ if (linked)
3540
+ await this.assignIds(
3541
+ sql,
3542
+ split.map((x) => x.row)
3543
+ );
3544
+ const { head, values } = this.insertSql(
3545
+ sql,
3546
+ t,
3547
+ split.map((x) => x.row)
3548
+ );
3549
+ const conflict = args["skipDuplicates"] ? sql` on conflict do nothing` : sql``;
3550
+ const result = await this.exec(
3551
+ sql`${head} values ${values}${conflict}${returning ? sql` returning *` : linked ? sql` returning ${this.col(sql, "id")}` : sql``}`
3552
+ );
3553
+ if (linked) {
3554
+ const inserted = new Set(result.rows.map((r) => String(r["id"])));
3555
+ await this.applyJoins(
3556
+ sql,
3557
+ split.filter((x) => inserted.has(String(x.row["id"]))).map((x) => ({ id: x.row["id"], ops: x.ops.filter((o) => o.items.length) }))
3558
+ );
3559
+ }
3560
+ if (!returning) return { count: linked ? result.rows.length : result.rowCount ?? 0 };
3561
+ const fields = this.projection(args);
3562
+ const records = result.rows.map((r) => this.fromRaw(t, r));
3563
+ if (this.tbl.joins.size) {
3564
+ const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
3565
+ for (const record of records) {
3566
+ for (const join of this.tbl.joins.values()) {
3567
+ const op = ops.get(String(record["id"]))?.find((o) => o.field === join.field);
3568
+ record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
3569
+ }
3570
+ }
3571
+ }
3572
+ return records.map((r) => this.project(r, fields));
3573
+ });
2457
3574
  });
2458
3575
  }
3576
+ /** Gives rows without an id one up front, so their links can name their owner. */
3577
+ async assignIds(sql, rows) {
3578
+ const missing = rows.filter((r) => r["id"] === void 0);
3579
+ if (missing.length === 0) return;
3580
+ if (this.tbl.idKind === "uuid") {
3581
+ for (const r of missing) r["id"] = randomUUID3();
3582
+ return;
3583
+ }
3584
+ const { rows: ids } = await this.exec(
3585
+ sql`select nextval(pg_get_serial_sequence(${sql.param(q(this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
3586
+ );
3587
+ missing.forEach((r, i) => {
3588
+ const id = ids[i]["id"];
3589
+ r["id"] = this.tbl.idKind === "bigserial" ? BigInt(id) : Number(id);
3590
+ });
3591
+ }
3592
+ /** Reloads the links of the fields `ops` changed into `records`. */
3593
+ async refreshJoins(sql, records, ops) {
3594
+ const fields = [...new Set(ops.map((o) => o.field))];
3595
+ if (fields.length === 0 || records.length === 0) return;
3596
+ this.attachJoins(
3597
+ records,
3598
+ await this.loadJoins(
3599
+ sql,
3600
+ records.map((r) => r["id"]),
3601
+ fields
3602
+ )
3603
+ );
3604
+ }
2459
3605
  async update(args) {
2460
3606
  this.uniqueKey(args["where"], "update");
2461
- const { t, sql } = await this.tbl.ready();
3607
+ const { t, sql } = await this.ready(args["where"]);
2462
3608
  return this.tbl.guard(async () => {
2463
- const sets = await this.setList(sql, t, args["data"] ?? {});
2464
- const where = this.where(sql, t, args["where"]);
2465
- const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *` : sql`select * from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
2466
- const [row] = (await this.tbl.client().execute(query)).rows;
2467
- if (!row) throw new HttpError(404, `${this.name} not found`);
2468
- return this.project(this.fromRaw(t, row), this.projection(args));
3609
+ const { sets, joinOps } = await this.setList(sql, t, args["data"] ?? {});
3610
+ return this.withLinks(joinOps.length > 0, async () => {
3611
+ const where = this.where(sql, t, args["where"]);
3612
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3613
+ const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
3614
+ const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
3615
+ const [row] = (await this.exec(query)).rows;
3616
+ if (!row) throw new HttpError(404, `${this.name} not found`);
3617
+ const record = this.fromRaw(t, row);
3618
+ await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
3619
+ await this.refreshJoins(sql, [record], joinOps);
3620
+ return this.project(record, this.projection(args));
3621
+ });
2469
3622
  });
2470
3623
  }
2471
3624
  async updateMany(args, returning) {
2472
- const { t, sql } = await this.tbl.ready();
3625
+ const { t, sql } = await this.ready(args["where"]);
2473
3626
  return this.tbl.guard(async () => {
2474
- const sets = await this.setList(sql, t, args["data"] ?? {});
2475
- if (sets.length === 0) {
3627
+ const { sets, joinOps } = await this.setList(sql, t, args["data"] ?? {});
3628
+ if (sets.length === 0 && joinOps.length === 0) {
2476
3629
  if (!returning) return { count: 0 };
2477
3630
  return this.findMany({ where: args["where"], select: args["select"], omit: args["omit"] });
2478
3631
  }
2479
- const where = this.where(sql, t, args["where"]) ?? sql`true`;
2480
- const result = await this.tbl.client().execute(
2481
- sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${returning ? sql` returning *` : sql``}`
2482
- );
2483
- if (!returning) return { count: result.rowCount ?? 0 };
2484
- const fields = this.projection(args);
2485
- return result.rows.map((r) => this.project(this.fromRaw(t, r), fields));
3632
+ return this.withLinks(joinOps.length > 0, async () => {
3633
+ const where = this.where(sql, t, args["where"]) ?? sql`true`;
3634
+ const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
3635
+ const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
3636
+ const result = await this.exec(
3637
+ sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(q(this.tbl.table))} where ${where}`
3638
+ );
3639
+ const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
3640
+ await this.applyJoins(
3641
+ sql,
3642
+ records.map((r) => ({ id: r["id"], ops: joinOps }))
3643
+ );
3644
+ if (!returning)
3645
+ return { count: joinOps.length ? result.rows.length : result.rowCount ?? 0 };
3646
+ await this.refreshJoins(sql, records, joinOps);
3647
+ const fields = this.projection(args);
3648
+ return records.map((r) => this.project(r, fields));
3649
+ });
2486
3650
  });
2487
3651
  }
2488
3652
  async upsert(args) {
2489
3653
  const key = this.uniqueKey(args["where"], "upsert");
2490
- const { t, sql } = await this.tbl.ready();
3654
+ const { t, sql } = await this.ready(args["where"]);
2491
3655
  return this.tbl.guard(async () => {
2492
- const row = await this.prepare(args["create"]);
3656
+ const { row, ops: createOps } = this.splitJoins(await this.prepare(args["create"]));
2493
3657
  for (const f of key) {
2494
3658
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
2495
3659
  }
2496
3660
  const { head, values } = this.insertSql(sql, t, [row]);
2497
- let sets = await this.setList(sql, t, args["update"] ?? {}, q(this.tbl.table));
3661
+ const table = q(this.tbl.table);
3662
+ const update = await this.setList(sql, t, args["update"] ?? {}, table);
3663
+ const { joinOps } = update;
3664
+ let { sets } = update;
2498
3665
  if (sets.length === 0)
2499
3666
  sets = [sql`${this.col(sql, key[0])} = excluded.${this.col(sql, key[0])}`];
2500
3667
  const target = sql.join(
@@ -2503,25 +3670,42 @@ var TableRuntime = class {
2503
3670
  );
2504
3671
  const extra = Object.keys(args["where"]).filter((f) => !key.includes(f));
2505
3672
  const cond = extra.length ? sql` where ${this.where(sql, t, Object.fromEntries(extra.map((f) => [f, args["where"][f]])))}` : sql``;
2506
- const [out] = (await this.tbl.client().execute(
2507
- sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond} returning *`
2508
- )).rows;
2509
- if (!out) throw new HttpError(404, `${this.name} not found`);
2510
- return this.project(this.fromRaw(t, out), this.projection(args));
3673
+ const linked = this.tbl.joins.size > 0;
3674
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()], table);
3675
+ const returning = linked ? sql` returning *, (${sql.raw(table)}.xmax = 0) as efc_inserted, ${sql.join(links, sql`, `)}` : sql` returning *`;
3676
+ return this.withLinks(
3677
+ createOps.some((o) => o.items.length) || joinOps.length > 0,
3678
+ async () => {
3679
+ const [out] = (await this.exec(
3680
+ sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
3681
+ )).rows;
3682
+ if (!out) throw new HttpError(404, `${this.name} not found`);
3683
+ const record = this.fromRaw(t, out);
3684
+ if (linked) {
3685
+ const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
3686
+ await this.applyJoins(sql, [{ id: record["id"], ops }]);
3687
+ await this.refreshJoins(sql, [record], ops);
3688
+ }
3689
+ return this.project(record, this.projection(args));
3690
+ }
3691
+ );
2511
3692
  });
2512
3693
  }
2513
3694
  async delete(args) {
2514
3695
  this.uniqueKey(args["where"], "delete");
2515
- const { t, sql } = await this.tbl.ready();
3696
+ const { t, sql } = await this.ready(args["where"]);
2516
3697
  return this.tbl.guard(async () => {
2517
3698
  const where = this.where(sql, t, args["where"]);
2518
- const [row] = (await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *`)).rows;
3699
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3700
+ const [row] = (await this.exec(
3701
+ sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
3702
+ )).rows;
2519
3703
  if (!row) throw new HttpError(404, `${this.name} not found`);
2520
3704
  return this.project(this.fromRaw(t, row), this.projection(args));
2521
3705
  });
2522
3706
  }
2523
3707
  async deleteMany(args = {}) {
2524
- const { t, sql } = await this.tbl.ready();
3708
+ const { t, sql } = await this.ready(args["where"]);
2525
3709
  return this.tbl.guard(async () => {
2526
3710
  const where = this.where(sql, t, args["where"]) ?? sql`true`;
2527
3711
  const result = await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where}`);
@@ -2529,6 +3713,18 @@ var TableRuntime = class {
2529
3713
  });
2530
3714
  }
2531
3715
  };
3716
+ function relArgs(arg) {
3717
+ return isPlainObject(arg) ? arg : {};
3718
+ }
3719
+ function runtimeOf(name, from) {
3720
+ const runtime = getRegisteredModel(name)?.tableRuntime?.();
3721
+ if (!runtime) {
3722
+ throw new Error(
3723
+ getRegisteredModel(name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
3724
+ );
3725
+ }
3726
+ return runtime;
3727
+ }
2532
3728
  var JSON_OPS = /* @__PURE__ */ new Set([
2533
3729
  "path",
2534
3730
  "equals",
@@ -2545,6 +3741,18 @@ var JSON_OPS = /* @__PURE__ */ new Set([
2545
3741
  ]);
2546
3742
  function createTable(name, schema, options = {}) {
2547
3743
  normalizeSchema(schema, "table", name);
3744
+ for (const [rel, def] of Object.entries(options.relations ?? {})) {
3745
+ const where = `[EFC] ${name}.relations.${rel}`;
3746
+ if (rel in schema) throw new Error(`${where}: a field already has this name`);
3747
+ if (!def || def.hasMany === void 0 === (def.hasOne === void 0)) {
3748
+ throw new Error(`${where}: give either hasMany or hasOne (a model name)`);
3749
+ }
3750
+ if (typeof def.foreignKey !== "string") {
3751
+ throw new Error(
3752
+ `${where}: foreignKey must name the ${def.hasMany ?? def.hasOne} field that references ${name}`
3753
+ );
3754
+ }
3755
+ }
2548
3756
  let runtime;
2549
3757
  const rt = () => {
2550
3758
  const engine2 = getDbEngine();
@@ -2566,24 +3774,31 @@ function createTable(name, schema, options = {}) {
2566
3774
  count: (args) => call((r) => r.count(args)),
2567
3775
  aggregate: (args) => call((r) => r.aggregate(args)),
2568
3776
  groupBy: (args) => call((r) => r.groupBy(args)),
2569
- create: (args) => call((r) => r.create(args)),
2570
- createMany: (args) => call((r) => r.createMany(args, false)),
2571
- createManyAndReturn: (args) => call((r) => r.createMany(args, true)),
2572
- update: (args) => call((r) => r.update(args)),
2573
- updateMany: (args) => call((r) => r.updateMany(args, false)),
2574
- updateManyAndReturn: (args) => call((r) => r.updateMany(args, true)),
2575
- upsert: (args) => call((r) => r.upsert(args)),
2576
- delete: (args) => call((r) => r.delete(args)),
3777
+ create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
3778
+ createMany: (args) => call((r) => (r.noNested(args?.["data"], "createMany"), r.createMany(args, false))),
3779
+ createManyAndReturn: (args) => call((r) => (r.noNested(args?.["data"], "createMany"), r.createMany(args, true))),
3780
+ update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
3781
+ updateMany: (args) => call((r) => (r.noNested(args?.["data"], "updateMany"), r.updateMany(args, false))),
3782
+ updateManyAndReturn: (args) => call((r) => (r.noNested(args?.["data"], "updateMany"), r.updateMany(args, true))),
3783
+ upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
3784
+ delete: (args) => call((r) => r.deleteWithInclude(args)),
2577
3785
  deleteMany: (args) => call((r) => r.deleteMany(args)),
2578
3786
  raw: () => call(async (r) => (await r.tbl.compile()).t),
2579
3787
  sync: (opts) => call((r) => r.tbl.reconcile(opts?.dryRun ?? false)),
2580
3788
  drop: () => call((r) => r.tbl.drop())
2581
3789
  };
3790
+ traceOps(
3791
+ name,
3792
+ model,
3793
+ Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
3794
+ );
2582
3795
  registerModel({
2583
3796
  name,
2584
3797
  sync: model.sync,
2585
3798
  drop: model.drop,
2586
- findByIds: (ids) => model.findMany({ where: { id: { in: ids } } })
3799
+ findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
3800
+ pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
3801
+ tableRuntime: () => rt()
2587
3802
  });
2588
3803
  return model;
2589
3804
  }
@@ -2619,17 +3834,14 @@ export {
2619
3834
  isHttpError,
2620
3835
  ModelValidationError,
2621
3836
  setDbEngine,
2622
- getDbEngine,
2623
3837
  setAutoSync,
2624
3838
  registeredModels,
2625
- currentTx,
2626
- runInTx,
2627
- loadMongoose,
2628
3839
  connectMongo,
2629
3840
  defineModel,
3841
+ transaction,
2630
3842
  defineTable,
2631
3843
  setDbClient,
2632
3844
  getDbClient,
2633
3845
  db
2634
3846
  };
2635
- //# sourceMappingURL=chunk-RTFJ32T5.js.map
3847
+ //# sourceMappingURL=chunk-6OGOVV57.js.map