@kiri-orm/core 0.1.6 → 0.2.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 (117) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +66 -0
  4. package/dist/types/crud/chunk.d.ts +10 -0
  5. package/dist/types/crud/database-errors.d.ts +61 -0
  6. package/dist/types/crud/errors.d.ts +10 -0
  7. package/dist/types/crud/fast-path.d.ts +73 -0
  8. package/dist/types/crud/index.d.ts +4 -1
  9. package/dist/types/crud/insert-many.d.ts +12 -13
  10. package/dist/types/crud/order.d.ts +28 -0
  11. package/dist/types/crud/repository.d.ts +5 -3
  12. package/dist/types/crud/row-mapping.d.ts +9 -1
  13. package/dist/types/crud/upsert.d.ts +39 -0
  14. package/dist/types/crud/value.d.ts +39 -0
  15. package/dist/types/dialect/date-bucket.d.ts +2 -2
  16. package/dist/types/dialect/index.d.ts +1 -0
  17. package/dist/types/dialect/transaction-guard.d.ts +31 -0
  18. package/dist/types/domain/compile.d.ts +17 -0
  19. package/dist/types/fields/filter-value.d.ts +21 -0
  20. package/dist/types/fields/registry.d.ts +1 -0
  21. package/dist/types/fields/storage.d.ts +28 -0
  22. package/dist/types/fields/types/date.d.ts +6 -6
  23. package/dist/types/fields/types/decimal.d.ts +40 -0
  24. package/dist/types/global/errors.d.ts +3 -0
  25. package/dist/types/global/index.d.ts +2 -0
  26. package/dist/types/global/normalize-dates.d.ts +11 -0
  27. package/dist/types/global/state.d.ts +2 -0
  28. package/dist/types/global/transaction.d.ts +10 -13
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/meta/create-table-once.d.ts +15 -0
  31. package/dist/types/meta/snapshot.d.ts +10 -0
  32. package/dist/types/meta/upsert.d.ts +16 -0
  33. package/dist/types/migrations/diff.d.ts +25 -2
  34. package/dist/types/models/constraints.d.ts +27 -0
  35. package/dist/types/relations/pivot-schema.d.ts +1 -1
  36. package/dist/types/schema/alter-column.d.ts +46 -0
  37. package/dist/types/schema/build-column.d.ts +11 -0
  38. package/dist/types/schema/index.d.ts +1 -0
  39. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  40. package/dist/types/schema/normalize-dates.d.ts +41 -0
  41. package/dist/types/transaction/after-commit.d.ts +42 -0
  42. package/dist/types/transaction/context.d.ts +39 -0
  43. package/dist/types/uow/entity.d.ts +39 -29
  44. package/dist/types/uow/hooks.d.ts +6 -1
  45. package/dist/types/uow/lifecycle.d.ts +82 -0
  46. package/dist/types/uow/unit-of-work.d.ts +11 -7
  47. package/package.json +8 -5
  48. package/src/client/model-handle.js +14 -4
  49. package/src/client/orm-client.js +10 -5
  50. package/src/connection.js +53 -7
  51. package/src/crud/aggregate-filter.js +8 -2
  52. package/src/crud/aggregate-spec.js +2 -2
  53. package/src/crud/aggregate.js +16 -5
  54. package/src/crud/chunk.js +10 -0
  55. package/src/crud/create-many.js +52 -29
  56. package/src/crud/database-errors.js +107 -0
  57. package/src/crud/errors.js +14 -0
  58. package/src/crud/fast-path.js +449 -0
  59. package/src/crud/index.js +4 -1
  60. package/src/crud/insert-many.js +42 -7
  61. package/src/crud/map-filter.js +2 -1
  62. package/src/crud/order.js +59 -9
  63. package/src/crud/repository.js +106 -38
  64. package/src/crud/row-mapping.js +32 -7
  65. package/src/crud/upsert.js +203 -0
  66. package/src/crud/value.js +71 -0
  67. package/src/dialect/index.js +1 -0
  68. package/src/dialect/transaction-guard.js +254 -0
  69. package/src/domain/compile.js +85 -12
  70. package/src/dto/field-schema.js +5 -0
  71. package/src/fields/default-registry.js +3 -1
  72. package/src/fields/filter-value.js +87 -0
  73. package/src/fields/registry.js +1 -0
  74. package/src/fields/storage.js +50 -0
  75. package/src/fields/types/date.js +16 -3
  76. package/src/fields/types/decimal.js +147 -0
  77. package/src/fields/types/integer.js +7 -0
  78. package/src/global/connect.js +25 -1
  79. package/src/global/create-model.js +59 -57
  80. package/src/global/errors.js +1 -1
  81. package/src/global/index.js +2 -0
  82. package/src/global/normalize-dates.js +15 -0
  83. package/src/global/state.js +3 -0
  84. package/src/global/transaction.js +12 -14
  85. package/src/index.js +2 -0
  86. package/src/meta/create-table-once.js +23 -0
  87. package/src/meta/schema.js +15 -6
  88. package/src/meta/snapshot.js +5 -0
  89. package/src/meta/upsert.js +28 -0
  90. package/src/migrations/describe.js +49 -0
  91. package/src/migrations/diff.js +50 -7
  92. package/src/migrations/generate.js +38 -2
  93. package/src/migrations/render.js +30 -12
  94. package/src/migrations/runner.js +40 -6
  95. package/src/models/constraints.js +96 -0
  96. package/src/models/define-model.js +4 -0
  97. package/src/models/inheritance.js +4 -1
  98. package/src/models/registry.js +2 -1
  99. package/src/relations/attach-detach.js +49 -18
  100. package/src/relations/cascade-delete.js +32 -7
  101. package/src/relations/eager-load.js +75 -51
  102. package/src/relations/pivot-schema.js +24 -3
  103. package/src/reports/report-handle.js +2 -1
  104. package/src/schema/alter-column.js +219 -0
  105. package/src/schema/build-column.js +28 -2
  106. package/src/schema/default-column-builders.js +16 -2
  107. package/src/schema/index.js +1 -0
  108. package/src/schema/introspect-indexes.js +22 -0
  109. package/src/schema/normalize-dates.js +58 -0
  110. package/src/schema/sync.js +16 -2
  111. package/src/transaction/after-commit.js +142 -0
  112. package/src/transaction/context.js +84 -0
  113. package/src/uow/entity.js +133 -133
  114. package/src/uow/hooks.js +9 -0
  115. package/src/uow/lifecycle.js +162 -0
  116. package/src/uow/unit-of-work.js +55 -60
  117. package/src/uow/with-unit-of-work.js +2 -1
@@ -6,6 +6,7 @@ import { defaultNamingStrategy } from "./naming.js";
6
6
  import { InvalidModelDefinitionError } from "./errors.js";
7
7
  import { defineRelation } from "../relations/define-relation.js";
8
8
  import { resolvePrimaryKey } from "./primary-key.js";
9
+ import { defineConstraints } from "./constraints.js";
9
10
 
10
11
  /**
11
12
  * @typedef {Object} ModelDescriptor
@@ -206,6 +207,8 @@ export function defineModel(
206
207
 
207
208
  const tableName = options.table ?? namingStrategy.modelToTable(options.name);
208
209
 
210
+ const constraints = defineConstraints(options.name, tableName, options.constraints, fields, columns);
211
+
209
212
  return Object.freeze({
210
213
  name: options.name,
211
214
  tableName,
@@ -214,5 +217,6 @@ export function defineModel(
214
217
  columns: Object.freeze(columns),
215
218
  relations: Object.freeze(relations),
216
219
  computed: Object.freeze(computed),
220
+ constraints,
217
221
  });
218
222
  }
@@ -1,4 +1,5 @@
1
1
  import { InvalidModelDefinitionError } from "./errors.js";
2
+ import { mergeConstraintInputs } from "./constraints.js";
2
3
 
3
4
  /**
4
5
  * Model inheritance, in the shape of Odoo's `_inherit` - which Odoo
@@ -155,13 +156,14 @@ export function foldModel(name, specs, stack = []) {
155
156
  if (stack.includes(name)) {
156
157
  throw new InvalidModelDefinitionError(`Circular mixins: ${[...stack, name].join(" -> ")}`);
157
158
  }
158
- const state = { table: undefined, primaryKey: undefined, fields: {}, relations: {}, origins: {} };
159
+ const state = { table: undefined, primaryKey: undefined, fields: {}, relations: {}, origins: {}, constraints: {} };
159
160
 
160
161
  for (const layer of specs.get(name).layers) {
161
162
  for (const mixinName of layer.def.mixins ?? []) {
162
163
  // A mixin contributes its fields and relations - never its name or table.
163
164
  const mixin = foldModel(mixinName, specs, [...stack, name]);
164
165
  applyPart(state, name, mixin.fields, mixin.relations, `mixin "${mixinName}"`);
166
+ mergeConstraintInputs(state.constraints, mixin.constraints);
165
167
  // A mixin may declare the primary key its models get; one set on the model itself wins.
166
168
  if (mixin.primaryKey !== undefined) state.primaryKey = mixin.primaryKey;
167
169
  }
@@ -175,6 +177,7 @@ export function foldModel(name, specs, stack = []) {
175
177
  state.table = layer.def.table;
176
178
  }
177
179
  applyPart(state, name, layer.def.fields ?? {}, layer.def.relations ?? {}, layerLabel(layer));
180
+ mergeConstraintInputs(state.constraints, layer.def.constraints);
178
181
  }
179
182
  return state;
180
183
  }
@@ -101,6 +101,7 @@ export class ModelRegistry {
101
101
  primaryKey: model.primaryKey ?? undefined,
102
102
  fields: { ...model.fields, ...(model.computed ?? {}) },
103
103
  relations: { ...model.relations },
104
+ constraints: { unique: (model.constraints?.unique ?? []).map((c) => [...c.fields]), index: (model.constraints?.index ?? []).map((c) => [...c.fields]) },
104
105
  };
105
106
  this.#specs.set(model.name, { abstract: false, layers: [{ kind: "primary", def, origin: null }] });
106
107
  this.#models.set(model.name, model);
@@ -249,7 +250,7 @@ export class ModelRegistry {
249
250
  try {
250
251
  folded = foldModel(name, candidate);
251
252
  const descriptor = defineModel(
252
- { name, table: spec.abstract ? undefined : folded.table, primaryKey: folded.primaryKey, fields: folded.fields, relations: folded.relations },
253
+ { name, table: spec.abstract ? undefined : folded.table, primaryKey: folded.primaryKey, fields: folded.fields, relations: folded.relations, constraints: folded.constraints },
253
254
  this.#namingStrategy,
254
255
  this.#fieldTypeRegistry
255
256
  );
@@ -1,6 +1,7 @@
1
1
  import { RelationError } from "./errors.js";
2
2
  import { resolveLocalKey } from "./keys.js";
3
3
  import { chunkArray, rowsPerStatement } from "../crud/insert-many.js";
4
+ import { IN_LIST_CHUNK } from "../crud/chunk.js";
4
5
 
5
6
  function resolveId(source, localKey) {
6
7
  return typeof source === "object" && source !== null ? source[localKey] : source;
@@ -11,10 +12,10 @@ function localKeyOf(relation, model) {
11
12
  return resolveLocalKey(relation, model);
12
13
  }
13
14
 
14
- function requireSourceId(sourceId, relationName, modelName, localKey) {
15
+ function requireSourceId(sourceId, relationName, modelName, localKey, verb = "attach") {
15
16
  if (sourceId === undefined || sourceId === null) {
16
17
  throw new RelationError(
17
- `Cannot attach via "${relationName}" on model "${modelName}": the source has no value for its "${localKey}" field`
18
+ `Cannot ${verb} via "${relationName}" on model "${modelName}": the source has no value for its "${localKey}" field`
18
19
  );
19
20
  }
20
21
  return sourceId;
@@ -102,21 +103,42 @@ export async function attachPairs(db, relation, pairs, options = {}) {
102
103
  }
103
104
  if (unique.length === 0) return 0;
104
105
 
105
- let toInsert = unique;
106
- if (options.checkExisting !== false) {
107
- const existing = await loadExistingPairs(db, relation, unique);
108
- toInsert = unique.filter(([source, target]) => !existing.has(pairKey(source, target)));
109
- }
110
- if (toInsert.length === 0) return 0;
111
-
112
- const rows = toInsert.map(([source, target]) => ({
113
- [relation.foreignKey]: source,
114
- [relation.otherKey]: target,
115
- }));
116
- for (const chunk of chunkArray(rows, rowsPerStatement(db, 2, options.chunkSize))) {
117
- await db(relation.through).insert(chunk);
106
+ // Check, then insert. Two concurrent attach() calls for the same pair can both pass the check;
107
+ // the pivot's unique constraint then rejects the slower insert. Before 0.1.7 that surfaced as a
108
+ // unique-violation error. Now the whole insert runs in its own transaction (a savepoint when
109
+ // `db` is already a transaction, so a failure there doesn't abort the caller's transaction on
110
+ // Postgres); on a unique violation it is rolled back and retried against fresh state - the
111
+ // pairs the other caller inserted are now found and skipped.
112
+ for (let attempt = 1; ; attempt++) {
113
+ let toInsert = unique;
114
+ if (options.checkExisting !== false) {
115
+ const existing = await loadExistingPairs(db, relation, unique);
116
+ toInsert = unique.filter(([source, target]) => !existing.has(pairKey(source, target)));
117
+ }
118
+ if (toInsert.length === 0) return 0;
119
+
120
+ const rows = toInsert.map(([source, target]) => ({
121
+ [relation.foreignKey]: source,
122
+ [relation.otherKey]: target,
123
+ }));
124
+ try {
125
+ await db.transaction(async (trx) => {
126
+ for (const chunk of chunkArray(rows, rowsPerStatement(db, 2, options.chunkSize))) {
127
+ await trx(relation.through).insert(chunk);
128
+ }
129
+ });
130
+ return rows.length;
131
+ } catch (error) {
132
+ if (options.checkExisting === false || attempt >= MAX_ATTACH_ATTEMPTS || !isUniqueViolation(error)) throw error;
133
+ }
118
134
  }
119
- return rows.length;
135
+ }
136
+
137
+ const MAX_ATTACH_ATTEMPTS = 3;
138
+
139
+ /** A duplicate-key error: Postgres SQLSTATE 23505, SQLite's UNIQUE / PRIMARY KEY constraint codes. */
140
+ function isUniqueViolation(error) {
141
+ return error?.code === "23505" || error?.code === "SQLITE_CONSTRAINT_UNIQUE" || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY";
120
142
  }
121
143
 
122
144
  /**
@@ -197,9 +219,18 @@ export async function attachManyRelation(db, model, modelName, relationName, lin
197
219
  */
198
220
  export async function detachRelation(db, model, modelName, source, relationName, targetIds) {
199
221
  const relation = requireBelongsToMany(model, modelName, relationName);
200
- const sourceId = resolveId(source, localKeyOf(relation, model));
222
+ const localKey = localKeyOf(relation, model);
223
+ const sourceId = requireSourceId(resolveId(source, localKey), relationName, modelName, localKey, "detach");
201
224
  const ids = Array.isArray(targetIds) ? targetIds : [targetIds];
202
225
  if (ids.length === 0) return 0;
203
226
 
204
- return db(relation.through).where(relation.foreignKey, sourceId).whereIn(relation.otherKey, ids).delete();
227
+ // In chunks: one IN list per statement stays under SQLite's and Postgres' bound-parameter limits
228
+ // (a single list of ~33k / ~65k ids failed before 0.1.7). One transaction keeps it all-or-nothing.
229
+ return db.transaction(async (trx) => {
230
+ let removed = 0;
231
+ for (const chunk of chunkArray(ids, IN_LIST_CHUNK)) {
232
+ removed += await trx(relation.through).where(relation.foreignKey, sourceId).whereIn(relation.otherKey, chunk).delete();
233
+ }
234
+ return removed;
235
+ });
205
236
  }
@@ -2,6 +2,9 @@ import { RelationError } from "./errors.js";
2
2
  import { ON_DELETE_ACTIONS } from "./define-relation.js";
3
3
  import { resolveOnDelete } from "./foreign-keys.js";
4
4
  import { primaryKeyOf } from "../models/primary-key.js";
5
+ import { IN_LIST_CHUNK } from "../crud/chunk.js";
6
+ import { chunkArray } from "../crud/insert-many.js";
7
+ import { resolveDb } from "../transaction/context.js";
5
8
 
6
9
  // Since foreign keys became real database constraints (see foreign-keys.js), the database applies
7
10
  // onDelete itself and a delete is a single statement. Everything in this file is therefore only
@@ -74,11 +77,15 @@ async function cascadeDelete(db, modelRegistry, model, ids) {
74
77
  for (const { childModel, relation, action } of incoming) {
75
78
  if (action !== "restrict") continue;
76
79
  const column = childModel.columns[relation.foreignKey];
77
- const blocking = await db(childModel.tableName).whereIn(column, ids).first(column);
80
+ let blocking;
81
+ for (const chunk of chunkArray(ids, IN_LIST_CHUNK)) {
82
+ blocking = await db(childModel.tableName).whereIn(column, chunk).first(column);
83
+ if (blocking) break;
84
+ }
78
85
  if (blocking) {
79
86
  throw new RelationError(
80
87
  `Can't delete from "${model.name}": "${childModel.name}.${relation.foreignKey}" (belongsTo, onDelete: "restrict") ` +
81
- `still has at least one row pointing at ${JSON.stringify(ids.length === 1 ? ids[0] : ids)}.`
88
+ `still has at least one row pointing at ${describeIds(ids)}.`
82
89
  );
83
90
  }
84
91
  }
@@ -86,7 +93,9 @@ async function cascadeDelete(db, modelRegistry, model, ids) {
86
93
  for (const { childModel, relation, action } of incoming) {
87
94
  const column = childModel.columns[relation.foreignKey];
88
95
  if (action === "setNull") {
89
- await db(childModel.tableName).whereIn(column, ids).update({ [column]: null });
96
+ for (const chunk of chunkArray(ids, IN_LIST_CHUNK)) {
97
+ await db(childModel.tableName).whereIn(column, chunk).update({ [column]: null });
98
+ }
90
99
  } else if (action === "cascade") {
91
100
  const childKey = primaryKeyOf(childModel);
92
101
  if (childKey === null) {
@@ -96,13 +105,29 @@ async function cascadeDelete(db, modelRegistry, model, ids) {
96
105
  );
97
106
  }
98
107
  const childIdColumn = childModel.columns[childKey];
99
- const rows = await db(childModel.tableName).whereIn(column, ids).select(childIdColumn);
100
- const childIds = rows.map((row) => row[childIdColumn]);
108
+ const childIds = [];
109
+ for (const chunk of chunkArray(ids, IN_LIST_CHUNK)) {
110
+ const rows = await db(childModel.tableName).whereIn(column, chunk).select(childIdColumn);
111
+ for (const row of rows) childIds.push(row[childIdColumn]);
112
+ }
101
113
  await cascadeDelete(db, modelRegistry, childModel, childIds);
102
114
  }
103
115
  }
104
116
 
105
- return db(model.tableName).whereIn(model.columns[primaryKeyOf(model)], ids).delete();
117
+ // Every IN list in this file goes in IN_LIST_CHUNK-sized slices: a cascade through tens of
118
+ // thousands of children went past the databases' bound-parameter limits before 0.1.7.
119
+ let deleted = 0;
120
+ for (const chunk of chunkArray(ids, IN_LIST_CHUNK)) {
121
+ deleted += await db(model.tableName).whereIn(model.columns[primaryKeyOf(model)], chunk).delete();
122
+ }
123
+ return deleted;
124
+ }
125
+
126
+ /** The ids for an error message: all of a few, or a count and a sample of many. */
127
+ function describeIds(ids) {
128
+ if (ids.length === 1) return JSON.stringify(ids[0]);
129
+ if (ids.length <= 10) return JSON.stringify(ids);
130
+ return `${ids.length} ids (${JSON.stringify(ids.slice(0, 10)).slice(0, -1)}, ...])`;
106
131
  }
107
132
 
108
133
  /**
@@ -127,7 +152,7 @@ export async function deleteRowsWithCascade(db, modelRegistry, model, where, opt
127
152
  `Remove the relations that point at it, or declare a primary key.`
128
153
  );
129
154
  }
130
- const baseDb = options.trx ?? db;
155
+ const baseDb = resolveDb(db, options.trx);
131
156
  const idColumn = model.columns[key];
132
157
  const ids = (await baseDb(model.tableName).where(where).select(idColumn)).map((row) => row[idColumn]);
133
158
  if (ids.length === 0) return 0;
@@ -1,10 +1,15 @@
1
1
  import { fromRow } from "../crud/row-mapping.js";
2
2
  import { isPostgres } from "../crud/sequence.js";
3
+ import { dialectOfClient } from "../fields/storage.js";
4
+ import { IN_LIST_CHUNK } from "../crud/chunk.js";
5
+ import { nullsClause, orderWithNulls } from "../crud/order.js";
6
+ import { chunkArray } from "../crud/insert-many.js";
3
7
  import { planSelect, stripHidden } from "../crud/select.js";
4
8
  import { RelationError } from "./errors.js";
5
9
  import { resolveLocalKey } from "./keys.js";
6
10
  import { normalizeWith, parentKeysNeeded } from "./with-spec.js";
7
11
  import { primaryKeyOf } from "../models/primary-key.js";
12
+ import { compileFastFind, runFast } from "../crud/fast-path.js";
8
13
 
9
14
  /**
10
15
  * Fails clearly when the records being loaded onto don't carry the field a relation is
@@ -25,7 +30,7 @@ function assertKeysLoaded(records, keys, relationName, model) {
25
30
  /**
26
31
  * Batch-loads one relation for a whole set of already-fetched records
27
32
  * and attaches the result onto each record under `relationName`.
28
- * Exactly one additional query is issued (two for belongsToMany: one
33
+ * Exactly one additional query is issued per relation (since 0.2.0 belongsToMany too; before, one
29
34
  * against the pivot table, one against the related table) regardless
30
35
  * of how many records are in `records` - this is the N+1 prevention
31
36
  * the roadmap calls for. See defineRelation() for what `foreignKey`/
@@ -58,14 +63,14 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
58
63
  const table = relatedModel.tableName;
59
64
  const windowed = node.limit !== undefined || node.offset !== undefined;
60
65
 
61
- const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed, jsonParsed: isPostgres(db) }));
66
+ const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed, jsonParsed: isPostgres(db), dialect: dialectOfClient(db.client) }));
62
67
 
63
68
  /** ORDER BY for the related rows: the requested order, then the primary key so ties (and a limit) are deterministic. */
64
69
  const orderFor = (prefix) => {
65
70
  const entries = [...node.order];
66
71
  const key = primaryKeyOf(relatedModel);
67
72
  if ((windowed || entries.length > 0) && key !== null && !entries.some((e) => e.field === key)) entries.push({ field: key, direction: "asc" });
68
- return entries.map((e) => ({ column: `${prefix}${relatedModel.columns[e.field]}`, direction: e.direction }));
73
+ return entries.map((e) => ({ column: `${prefix}${relatedModel.columns[e.field]}`, direction: e.direction, nulls: e.nulls, field: e.field === key ? null : relatedModel.fields[e.field] }));
69
74
  };
70
75
 
71
76
  /**
@@ -77,11 +82,25 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
77
82
  */
78
83
  const read = async (matchColumn, values, ownKey) => {
79
84
  const plan = planSelect(relatedModel, node.select, [ownKey, ...nestedKeys]);
85
+ const rows = await inChunks(values, (chunk) => readChunk(matchColumn, chunk, plan, ownKey));
86
+ return { hidden: plan.hidden, related: toRecords(rows, plan) };
87
+ };
88
+ const readChunk = async (matchColumn, values, plan, ownKey) => {
89
+ if (!windowed || values.length === 1) {
90
+ // The plain read (no per-parent window) is a find() on the related model: written directly
91
+ // when it can be (crud/fast-path.js), like any find.
92
+ const order = orderFor("").map((o) => [relatedModelField(o.column), o.direction, o.nulls]);
93
+ const filter = [[ownKey, "in", values], ...(node.where === undefined ? [] : [asDomain(node.where)])];
94
+ const paging = windowed ? { limit: node.limit, offset: node.offset } : {};
95
+ const fast = compileFastFind(db, relatedModel, filter, plan.columns, { orderBy: order, ...paging }, fieldTypeRegistry);
96
+ const rows = fast ? await runFast(db, fast) : undefined;
97
+ if (rows !== undefined) return rows;
98
+ }
80
99
  let query = db(table).whereIn(matchColumn, values);
81
100
  if (node.whereFn) query = query.where(node.whereFn);
82
101
 
83
102
  let rows;
84
- if (windowed) {
103
+ if (windowed && values.length > 1) {
85
104
  const order = orderFor("");
86
105
  const orderBy = order.map((o) => `?? ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ");
87
106
  const inner = query
@@ -90,11 +109,18 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
90
109
  rows = await rankWindow(db, inner, plan.columns, node);
91
110
  } else {
92
111
  if (plan.columns) query = query.select(plan.columns);
93
- for (const { column, direction } of orderFor("")) query = query.orderBy(column, direction);
112
+ for (const { column, direction, nulls, field } of orderFor("")) query = orderWithNulls(query, column, direction, nullsClause(query, field, direction, nulls));
113
+ // One parent: a limit per parent is just a LIMIT, no window function needed (since 0.2.0).
114
+ if (windowed) {
115
+ if (node.limit !== undefined) query = query.limit(node.limit);
116
+ if (node.offset) query = query.offset(node.offset);
117
+ }
94
118
  rows = await query;
95
119
  }
96
- return { hidden: plan.hidden, related: toRecords(rows, plan) };
120
+ return rows;
97
121
  };
122
+ const fieldOfColumn = new Map(Object.entries(relatedModel.columns).map(([field, column]) => [column, field]));
123
+ const relatedModelField = (column) => fieldOfColumn.get(column);
98
124
  const nothing = { relatedModel, related: [], hidden: [] };
99
125
 
100
126
  if (relation.type === "belongsTo") {
@@ -152,30 +178,36 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
152
178
  );
153
179
  }
154
180
 
155
- // Ordering or limiting a many-to-many needs the pivot and the related rows together (the order is by
156
- // the RELATED row's columns, and a limit counts per parent), so that case is one joined statement.
157
- if (windowed || node.order.length > 0) {
181
+ // One joined statement: the pivot and the related rows together (since 0.2.0 also when there's
182
+ // no order or limit; before, that case read the pivot, then the related rows - two round trips).
183
+ {
158
184
  const plan = planSelect(relatedModel, node.select, [relatedKey, ...nestedKeys]);
159
- const related = (node.whereFn ? db(table).where(node.whereFn) : db(table)).as("t");
185
+ // A `where` on the related rows needs them as a subquery; otherwise join the table itself.
186
+ const related = node.whereFn ? db(table).where(node.whereFn).as("t") : `${table} as t`;
160
187
  const order = orderFor("t.");
161
188
 
162
- let query = db({ pv: relation.through })
163
- .join(related, `t.${relatedModel.columns[relatedKey]}`, `pv.${relation.otherKey}`)
164
- .whereIn(`pv.${relation.foreignKey}`, localValues)
165
- .select(db.raw("?? AS ??", [`pv.${relation.foreignKey}`, PARENT]))
166
- .select(plan.columns ? plan.columns.map((c) => `t.${c}`) : "t.*");
189
+ const rows = await inChunks(localValues, async (chunk) => {
190
+ let query = db({ pv: relation.through })
191
+ .join(related, `t.${relatedModel.columns[relatedKey]}`, `pv.${relation.otherKey}`)
192
+ .whereIn(`pv.${relation.foreignKey}`, chunk)
193
+ .select(db.raw("?? AS ??", [`pv.${relation.foreignKey}`, PARENT]))
194
+ .select(plan.columns ? plan.columns.map((c) => `t.${c}`) : "t.*");
167
195
 
168
- let rows;
169
- if (windowed) {
170
- const orderBy = order.map((o) => `?? ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ");
171
- query = query.select(db.raw(`row_number() OVER (PARTITION BY ?? ORDER BY ${orderBy}) AS ??`, [`pv.${relation.foreignKey}`, ...order.map((o) => o.column), RANK]));
172
- rows = await rankWindow(db, query, plan.columns ? [...plan.columns.map((c) => c), PARENT] : null, node, PARENT);
173
- } else {
174
- for (const { column, direction } of order) query = query.orderBy(column, direction);
175
- rows = await query;
176
- }
196
+ if (windowed && chunk.length > 1) {
197
+ const orderBy = order.map((o) => `?? ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ");
198
+ query = query.select(db.raw(`row_number() OVER (PARTITION BY ?? ORDER BY ${orderBy}) AS ??`, [`pv.${relation.foreignKey}`, ...order.map((o) => o.column), RANK]));
199
+ return rankWindow(db, query, plan.columns ? [...plan.columns.map((c) => c), PARENT] : null, node, PARENT);
200
+ }
201
+ for (const { column, direction, nulls, field } of order) query = orderWithNulls(query, column, direction, nullsClause(query, field, direction, nulls));
202
+ if (windowed) {
203
+ // One parent: the per-parent limit is a plain LIMIT.
204
+ if (node.limit !== undefined) query = query.limit(node.limit);
205
+ if (node.offset) query = query.offset(node.offset);
206
+ }
207
+ return query;
208
+ });
177
209
 
178
- // The same related row may sit under several parents: one object, shared, as in the unordered path.
210
+ // The same related row may sit under several parents: one object, shared between them.
179
211
  const byKey = new Map();
180
212
  const byParent = new Map();
181
213
  for (const row of rows) {
@@ -189,32 +221,6 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
189
221
  return { relatedModel, related: [...byKey.values()], hidden: plan.hidden };
190
222
  }
191
223
 
192
- // Only the two link columns are needed from the pivot table.
193
- const pivotRows = await db(relation.through)
194
- .select(relation.foreignKey, relation.otherKey)
195
- .whereIn(relation.foreignKey, localValues);
196
- const relatedIds = uniqueDefined(pivotRows.map((row) => row[relation.otherKey]));
197
-
198
- let related = [];
199
- let hidden = [];
200
- let relatedById = new Map();
201
- if (relatedIds.length > 0) {
202
- ({ related, hidden } = await read(relatedModel.columns[relatedKey], relatedIds, relatedKey));
203
- relatedById = new Map(related.map((rec) => [rec[relatedKey], rec]));
204
- }
205
-
206
- const idsByLocalKey = new Map();
207
- for (const row of pivotRows) {
208
- const key = row[relation.foreignKey];
209
- if (!idsByLocalKey.has(key)) idsByLocalKey.set(key, []);
210
- idsByLocalKey.get(key).push(row[relation.otherKey]);
211
- }
212
-
213
- for (const r of records) {
214
- const ids = idsByLocalKey.get(r[localKey]) ?? [];
215
- r[relationName] = ids.map((id) => relatedById.get(id)).filter((rec) => rec !== undefined);
216
- }
217
- return { relatedModel, related, hidden };
218
224
  }
219
225
 
220
226
  return nothing;
@@ -236,6 +242,11 @@ async function rankWindow(db, inner, columns, node, extraColumn = null) {
236
242
  return outer.orderBy(RANK);
237
243
  }
238
244
 
245
+ /** A `where` of a `with` entry as a domain (a plain object is equality on each of its fields). */
246
+ function asDomain(where) {
247
+ return Array.isArray(where) ? where : Object.entries(where).map(([field, value]) => [field, "=", value]);
248
+ }
249
+
239
250
  function uniqueDefined(values) {
240
251
  return [...new Set(values.filter((v) => v !== null && v !== undefined))];
241
252
  }
@@ -290,3 +301,16 @@ export async function eagerLoad(db, modelRegistry, model, records, withSpec, fie
290
301
  const tree = withSpec instanceof Map ? withSpec : normalizeWith(model, modelRegistry, withSpec, fieldTypeRegistry);
291
302
  return loadTree(db, modelRegistry, model, records, tree, fieldTypeRegistry);
292
303
  }
304
+
305
+ /**
306
+ * Runs `query(chunk)` for each IN_LIST_CHUNK-sized slice of `values` and concatenates the rows.
307
+ * Each slice is a set of whole parents (or whole related keys), so per-parent grouping, ordering
308
+ * and limits are unchanged; only rows of different parents may come from different statements.
309
+ * One slice - the usual case - is exactly the single statement this always ran.
310
+ */
311
+ async function inChunks(values, query) {
312
+ if (values.length <= IN_LIST_CHUNK) return query(values);
313
+ const rows = [];
314
+ for (const chunk of chunkArray(values, IN_LIST_CHUNK)) rows.push(...(await query(chunk)));
315
+ return rows;
316
+ }
@@ -1,5 +1,8 @@
1
1
  import { addForeignKey } from "../schema/foreign-keys.js";
2
2
  import { pivotForeignKeysOf } from "./foreign-keys.js";
3
+ import { resolveLocalKey } from "./keys.js";
4
+ import { primaryKeyOf } from "../models/primary-key.js";
5
+ import { defaultColumnBuilderRegistry } from "../schema/default-column-builders.js";
3
6
 
4
7
  /**
5
8
  * Creates the pivot table for every `belongsToMany` relation across
@@ -24,7 +27,7 @@ import { pivotForeignKeysOf } from "./foreign-keys.js";
24
27
  * @param {import('knex').Knex} db
25
28
  * @param {import('../models/registry.js').ModelRegistry} modelRegistry
26
29
  */
27
- export async function ensurePivotTables(db, modelRegistry) {
30
+ export async function ensurePivotTables(db, modelRegistry, columnBuilderRegistry = defaultColumnBuilderRegistry) {
28
31
  for (const modelName of modelRegistry.listModels()) {
29
32
  const model = modelRegistry.getModel(modelName);
30
33
  for (const relation of Object.values(model.relations ?? {})) {
@@ -34,8 +37,9 @@ export async function ensurePivotTables(db, modelRegistry) {
34
37
  if (exists) continue;
35
38
 
36
39
  await db.schema.createTable(relation.through, (table) => {
37
- table.integer(relation.foreignKey).notNullable();
38
- table.integer(relation.otherKey).notNullable();
40
+ const related = modelRegistry.listModels().includes(relation.model) ? modelRegistry.getModel(relation.model) : null;
41
+ pivotColumn(table, relation.foreignKey, model.fields?.[resolveLocalKey(relation, model)], columnBuilderRegistry);
42
+ pivotColumn(table, relation.otherKey, related && related.fields?.[primaryKeyOf(related)], columnBuilderRegistry);
39
43
  table.unique([relation.foreignKey, relation.otherKey]);
40
44
  // both sides cascade: deleting a row removes its associations, in the database
41
45
  for (const fk of pivotForeignKeysOf(modelRegistry, model, relation)) addForeignKey(table, fk);
@@ -43,3 +47,20 @@ export async function ensurePivotTables(db, modelRegistry) {
43
47
  }
44
48
  }
45
49
  }
50
+
51
+ /**
52
+ * A pivot column of the same type as the key it points to. Before 0.1.7 both pivot columns
53
+ * were always `integer`: with uuid (or char) keys, Postgres refused to create the foreign key
54
+ * ("incompatible types"), so syncModels() failed; SQLite silently stored the uuids in
55
+ * integer-typed columns. Existing pivot tables are never altered - only new ones get this.
56
+ *
57
+ * An auto-increment key is an integer column; any other key is built by the same column builder
58
+ * as the key itself (uuid -> uuid, char -> varchar of its maxLength, ...), without the key's own
59
+ * primary/unique/default. A key that can't be resolved falls back to `integer`, as before.
60
+ */
61
+ function pivotColumn(table, columnName, keyField, columnBuilderRegistry) {
62
+ if (!keyField || keyField.autoId === "increment" || !columnBuilderRegistry.has?.(keyField.type)) {
63
+ return table.integer(columnName).notNullable();
64
+ }
65
+ return columnBuilderRegistry.get(keyField.type)(table, columnName, keyField).notNullable();
66
+ }
@@ -5,6 +5,7 @@ import { planAggregate } from "../crud/aggregate-spec.js";
5
5
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
6
6
  import { toAggregateOptions } from "./define-report.js";
7
7
  import { ReportDefinitionError } from "./errors.js";
8
+ import { resolveDb } from "../transaction/context.js";
8
9
 
9
10
  /**
10
11
  * Runs a report (see defineReport()). Every call is one SQL statement, whatever the grain,
@@ -102,7 +103,7 @@ export class ReportHandle {
102
103
 
103
104
  const fieldTypeRegistry = this.#env.fieldTypeRegistry ?? defaultFieldTypeRegistry;
104
105
  const ctx = {
105
- db: options.trx ?? this.#env.db(),
106
+ db: resolveDb(this.#env.db(), options.trx),
106
107
  model,
107
108
  filter: [...toTerms(descriptor.where), ...toTerms(filter)],
108
109
  options: { ...this.#prepared.aggregateOptions, orderBy, limit: options.limit, offset: options.offset },