@rocicorp/zero 1.12.0-canary.10 → 1.12.0-canary.12

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 (231) hide show
  1. package/out/analyze-query/src/zql-chain.js +9 -1
  2. package/out/analyze-query/src/zql-chain.js.map +1 -1
  3. package/out/ast-to-zql/src/ast-to-zql.d.ts.map +1 -1
  4. package/out/ast-to-zql/src/ast-to-zql.js +61 -20
  5. package/out/ast-to-zql/src/ast-to-zql.js.map +1 -1
  6. package/out/z2s/src/compiler.d.ts +1 -1
  7. package/out/z2s/src/compiler.d.ts.map +1 -1
  8. package/out/z2s/src/compiler.js +339 -2
  9. package/out/z2s/src/compiler.js.map +1 -1
  10. package/out/z2s/src/sql.d.ts +8 -0
  11. package/out/z2s/src/sql.d.ts.map +1 -1
  12. package/out/z2s/src/sql.js +58 -11
  13. package/out/z2s/src/sql.js.map +1 -1
  14. package/out/zero/package.js +1 -1
  15. package/out/zero/package.js.map +1 -1
  16. package/out/zero/src/bindings.js +4 -4
  17. package/out/zero-cache/src/auth/write-authorizer.js +1 -1
  18. package/out/zero-cache/src/config/zero-config.d.ts +4 -0
  19. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  20. package/out/zero-cache/src/config/zero-config.js +13 -0
  21. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  22. package/out/zero-cache/src/db/create.js +1 -1
  23. package/out/zero-cache/src/scripts/decommission.js +1 -1
  24. package/out/zero-cache/src/server/replicator.js +4 -2
  25. package/out/zero-cache/src/server/replicator.js.map +1 -1
  26. package/out/zero-cache/src/server/runner/run-worker.d.ts.map +1 -1
  27. package/out/zero-cache/src/server/runner/run-worker.js +8 -5
  28. package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
  29. package/out/zero-cache/src/server/serving-checkpointer.js +41 -0
  30. package/out/zero-cache/src/server/serving-checkpointer.js.map +1 -0
  31. package/out/zero-cache/src/server/worker-urls.d.ts +1 -0
  32. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
  33. package/out/zero-cache/src/server/worker-urls.js +2 -1
  34. package/out/zero-cache/src/server/worker-urls.js.map +1 -1
  35. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +1 -1
  36. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
  37. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +1 -1
  38. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +1 -1
  39. package/out/zero-cache/src/services/change-source/pg/schema/init.js +1 -1
  40. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +1 -1
  41. package/out/zero-cache/src/services/http-service.d.ts +6 -0
  42. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  43. package/out/zero-cache/src/services/http-service.js +13 -1
  44. package/out/zero-cache/src/services/http-service.js.map +1 -1
  45. package/out/zero-cache/src/services/life-cycle.d.ts +19 -0
  46. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/life-cycle.js +53 -1
  48. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  49. package/out/zero-cache/src/services/replicator/change-processor.js +1 -1
  50. package/out/zero-cache/src/services/replicator/serving-checkpointer.js +85 -0
  51. package/out/zero-cache/src/services/replicator/serving-checkpointer.js.map +1 -0
  52. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +101 -13
  53. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  54. package/out/zero-cache/src/services/view-syncer/query-covering.js +2 -2
  55. package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
  56. package/out/zero-cache/src/services/view-syncer/snapshotter.js +1 -1
  57. package/out/zero-cache/src/services/view-syncer/view-syncer.js +1 -1
  58. package/out/zero-cache/src/types/processes.js +4 -4
  59. package/out/zero-cache/src/types/processes.js.map +1 -1
  60. package/out/zero-cache/src/types/row-key.js +8 -1
  61. package/out/zero-cache/src/types/row-key.js.map +1 -1
  62. package/out/zero-cache/src/workers/connection.js +2 -2
  63. package/out/zero-cache/src/workers/replicator.js +9 -4
  64. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  65. package/out/zero-client/src/client/bindings.d.ts +1 -1
  66. package/out/zero-client/src/client/bindings.d.ts.map +1 -1
  67. package/out/zero-client/src/client/bindings.js +4 -4
  68. package/out/zero-client/src/client/context.d.ts +7 -1
  69. package/out/zero-client/src/client/context.d.ts.map +1 -1
  70. package/out/zero-client/src/client/context.js +7 -0
  71. package/out/zero-client/src/client/context.js.map +1 -1
  72. package/out/zero-client/src/client/crud-impl.d.ts.map +1 -1
  73. package/out/zero-client/src/client/crud-impl.js +171 -2
  74. package/out/zero-client/src/client/crud-impl.js.map +1 -1
  75. package/out/zero-client/src/client/custom.d.ts.map +1 -1
  76. package/out/zero-client/src/client/custom.js +42 -3
  77. package/out/zero-client/src/client/custom.js.map +1 -1
  78. package/out/zero-client/src/client/ivm-branch.d.ts +62 -2
  79. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  80. package/out/zero-client/src/client/ivm-branch.js +152 -31
  81. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  82. package/out/zero-client/src/client/keys.d.ts +33 -0
  83. package/out/zero-client/src/client/keys.d.ts.map +1 -1
  84. package/out/zero-client/src/client/keys.js +43 -4
  85. package/out/zero-client/src/client/keys.js.map +1 -1
  86. package/out/zero-client/src/client/version.js +1 -1
  87. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  88. package/out/zero-client/src/client/zero-poke-handler.js +29 -1
  89. package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
  90. package/out/zero-client/src/client/zero-rep.d.ts +1 -1
  91. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  92. package/out/zero-client/src/client/zero-rep.js +2 -15
  93. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  94. package/out/zero-client/src/client/zero.js +1 -1
  95. package/out/zero-client/src/mod.d.ts +3 -3
  96. package/out/zero-client/src/mod.d.ts.map +1 -1
  97. package/out/zero-protocol/src/aggregate-table.d.ts +15 -0
  98. package/out/zero-protocol/src/aggregate-table.d.ts.map +1 -0
  99. package/out/zero-protocol/src/aggregate-table.js +5 -0
  100. package/out/zero-protocol/src/aggregate-table.js.map +1 -0
  101. package/out/zero-protocol/src/ast.d.ts +141 -5
  102. package/out/zero-protocol/src/ast.d.ts.map +1 -1
  103. package/out/zero-protocol/src/ast.js +244 -18
  104. package/out/zero-protocol/src/ast.js.map +1 -1
  105. package/out/zero-protocol/src/down.d.ts +29 -29
  106. package/out/zero-protocol/src/inspect-down.d.ts +81 -81
  107. package/out/zero-protocol/src/protocol-version.d.ts +1 -1
  108. package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
  109. package/out/zero-protocol/src/protocol-version.js.map +1 -1
  110. package/out/zero-protocol/src/query-hash-visitor.d.ts.map +1 -1
  111. package/out/zero-protocol/src/query-hash-visitor.js +38 -0
  112. package/out/zero-protocol/src/query-hash-visitor.js.map +1 -1
  113. package/out/zero-react/src/bindings.js +4 -4
  114. package/out/zero-react/src/use-query.d.ts +3 -1
  115. package/out/zero-react/src/use-query.d.ts.map +1 -1
  116. package/out/zero-react/src/use-query.js +4 -2
  117. package/out/zero-react/src/use-query.js.map +1 -1
  118. package/out/zero-schema/src/builder/schema-builder.d.ts.map +1 -1
  119. package/out/zero-schema/src/builder/schema-builder.js +2 -0
  120. package/out/zero-schema/src/builder/schema-builder.js.map +1 -1
  121. package/out/zero-schema/src/name-mapper.d.ts.map +1 -1
  122. package/out/zero-schema/src/name-mapper.js +7 -4
  123. package/out/zero-schema/src/name-mapper.js.map +1 -1
  124. package/out/zero-server/src/custom.js +1 -1
  125. package/out/zero-server/src/schema.d.ts.map +1 -1
  126. package/out/zero-server/src/schema.js +13 -2
  127. package/out/zero-server/src/schema.js.map +1 -1
  128. package/out/zero-solid/src/bindings.js +4 -4
  129. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  130. package/out/zero-solid/src/solid-view.js +3 -3
  131. package/out/zero-solid/src/solid-view.js.map +1 -1
  132. package/out/zero-types/src/format.d.ts +13 -0
  133. package/out/zero-types/src/format.d.ts.map +1 -1
  134. package/out/zero-types/src/format.js.map +1 -1
  135. package/out/zero-types/src/name-mapper.d.ts +14 -0
  136. package/out/zero-types/src/name-mapper.d.ts.map +1 -1
  137. package/out/zero-types/src/name-mapper.js +12 -0
  138. package/out/zero-types/src/name-mapper.js.map +1 -1
  139. package/out/zero-types/src/schema-value.d.ts +2 -0
  140. package/out/zero-types/src/schema-value.d.ts.map +1 -1
  141. package/out/zero-types/src/schema-value.js +15 -0
  142. package/out/zero-types/src/schema-value.js.map +1 -0
  143. package/out/zero-types/src/server-schema.d.ts +18 -0
  144. package/out/zero-types/src/server-schema.d.ts.map +1 -1
  145. package/out/zql/src/builder/builder.d.ts +126 -1
  146. package/out/zql/src/builder/builder.d.ts.map +1 -1
  147. package/out/zql/src/builder/builder.js +281 -11
  148. package/out/zql/src/builder/builder.js.map +1 -1
  149. package/out/zql/src/builder/filter.d.ts +1 -1
  150. package/out/zql/src/builder/filter.d.ts.map +1 -1
  151. package/out/zql/src/builder/filter.js +41 -3
  152. package/out/zql/src/builder/filter.js.map +1 -1
  153. package/out/zql/src/ivm/aggregate.d.ts +188 -0
  154. package/out/zql/src/ivm/aggregate.d.ts.map +1 -0
  155. package/out/zql/src/ivm/aggregate.js +470 -0
  156. package/out/zql/src/ivm/aggregate.js.map +1 -0
  157. package/out/zql/src/ivm/array-view.d.ts +1 -1
  158. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  159. package/out/zql/src/ivm/array-view.js +3 -3
  160. package/out/zql/src/ivm/array-view.js.map +1 -1
  161. package/out/zql/src/ivm/cap.js +2 -2
  162. package/out/zql/src/ivm/constraint.d.ts.map +1 -1
  163. package/out/zql/src/ivm/constraint.js +2 -1
  164. package/out/zql/src/ivm/constraint.js.map +1 -1
  165. package/out/zql/src/ivm/deferred-input.js +1 -1
  166. package/out/zql/src/ivm/fan-in.js +1 -1
  167. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  168. package/out/zql/src/ivm/flipped-join.js +3 -2
  169. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  170. package/out/zql/src/ivm/group-by.d.ts +98 -0
  171. package/out/zql/src/ivm/group-by.d.ts.map +1 -0
  172. package/out/zql/src/ivm/group-by.js +384 -0
  173. package/out/zql/src/ivm/group-by.js.map +1 -0
  174. package/out/zql/src/ivm/join-index.d.ts.map +1 -1
  175. package/out/zql/src/ivm/join-index.js +2 -1
  176. package/out/zql/src/ivm/join-index.js.map +1 -1
  177. package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
  178. package/out/zql/src/ivm/join-utils.js +2 -1
  179. package/out/zql/src/ivm/join-utils.js.map +1 -1
  180. package/out/zql/src/ivm/join.js +1 -1
  181. package/out/zql/src/ivm/lift-field.d.ts +54 -0
  182. package/out/zql/src/ivm/lift-field.d.ts.map +1 -0
  183. package/out/zql/src/ivm/lift-field.js +168 -0
  184. package/out/zql/src/ivm/lift-field.js.map +1 -0
  185. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +1 -1
  186. package/out/zql/src/ivm/memory-source.d.ts +2 -0
  187. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  188. package/out/zql/src/ivm/memory-source.js +9 -4
  189. package/out/zql/src/ivm/memory-source.js.map +1 -1
  190. package/out/zql/src/ivm/push-accumulated.js +1 -1
  191. package/out/zql/src/ivm/schema.d.ts +1 -0
  192. package/out/zql/src/ivm/schema.d.ts.map +1 -1
  193. package/out/zql/src/ivm/source.d.ts +21 -0
  194. package/out/zql/src/ivm/source.d.ts.map +1 -1
  195. package/out/zql/src/ivm/source.js.map +1 -1
  196. package/out/zql/src/ivm/take.js +1 -1
  197. package/out/zql/src/ivm/union-fan-in.js +1 -1
  198. package/out/zql/src/ivm/view-apply-change.d.ts +5 -0
  199. package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
  200. package/out/zql/src/ivm/view-apply-change.js +23 -3
  201. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  202. package/out/zql/src/planner/planner-debug.d.ts +1 -1
  203. package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
  204. package/out/zql/src/planner/planner-debug.js +4 -0
  205. package/out/zql/src/planner/planner-debug.js.map +1 -1
  206. package/out/zql/src/query/expression.d.ts +50 -3
  207. package/out/zql/src/query/expression.d.ts.map +1 -1
  208. package/out/zql/src/query/expression.js +62 -6
  209. package/out/zql/src/query/expression.js.map +1 -1
  210. package/out/zql/src/query/measure-push-operator.js +1 -1
  211. package/out/zql/src/query/query-delegate-base.d.ts +8 -0
  212. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  213. package/out/zql/src/query/query-delegate-base.js +13 -5
  214. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  215. package/out/zql/src/query/query-impl.d.ts +17 -3
  216. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  217. package/out/zql/src/query/query-impl.js +239 -7
  218. package/out/zql/src/query/query-impl.js.map +1 -1
  219. package/out/zql/src/query/query.d.ts +319 -7
  220. package/out/zql/src/query/query.d.ts.map +1 -1
  221. package/out/zqlite/src/pending-delta.d.ts.map +1 -1
  222. package/out/zqlite/src/pending-delta.js +4 -3
  223. package/out/zqlite/src/pending-delta.js.map +1 -1
  224. package/out/zqlite/src/query-builder.d.ts +12 -1
  225. package/out/zqlite/src/query-builder.d.ts.map +1 -1
  226. package/out/zqlite/src/query-builder.js +114 -13
  227. package/out/zqlite/src/query-builder.js.map +1 -1
  228. package/out/zqlite/src/table-source.d.ts.map +1 -1
  229. package/out/zqlite/src/table-source.js +37 -3
  230. package/out/zqlite/src/table-source.js.map +1 -1
  231. package/package.json +1 -1
@@ -5,7 +5,8 @@ import { SUBQ_PREFIX, insertRelated, normalizeAST, normalizeCondition, normalize
5
5
  import { defaultFormat } from "../../../zero-types/src/format.js";
6
6
  import { hashOfQueryInternals } from "../../../zero-protocol/src/query-hash-visitor.js";
7
7
  import { NotImplementedError } from "../error.js";
8
- import { ExpressionBuilder, and, cmp, simplifyCondition } from "./expression.js";
8
+ import { isSyntheticColumn } from "../ivm/aggregate.js";
9
+ import { ExpressionBuilder, aggregateFromSelector, and, cmp, simplifyCondition } from "./expression.js";
9
10
  import { queryInternalsTag } from "./query-internals.js";
10
11
  import { HashIndex, Transitions } from "./query-transitions.js";
11
12
  //#region ../zql/src/query/query-impl.ts
@@ -28,7 +29,7 @@ var rootsBySchema = /* @__PURE__ */ new WeakMap();
28
29
  * count; each one has to be checked.
29
30
  */
30
31
  function isRootAST(ast, tableName) {
31
- return ast.table === tableName && ast.schema === void 0 && ast.alias === void 0 && ast.where === void 0 && ast.related === void 0 && ast.start === void 0 && ast.limit === void 0 && ast.orderBy === void 0;
32
+ return ast.table === tableName && ast.schema === void 0 && ast.alias === void 0 && ast.where === void 0 && ast.related === void 0 && ast.start === void 0 && ast.limit === void 0 && ast.orderBy === void 0 && ast.aggregate === void 0 && ast.groupBy === void 0;
32
33
  }
33
34
  function newQueryInternal(schema, tableName, ast, format, system) {
34
35
  const interned = format === defaultFormat && isRootAST(ast, tableName);
@@ -189,6 +190,8 @@ var QueryImpl = class {
189
190
  return this.#system === other.#system && this.#currentJunction === other.#currentJunction && this.customQueryID?.name === other.customQueryID?.name && deepEqual(this.customQueryID?.args, other.customQueryID?.args) && deepEqual(this.format, other.format) && deepEqual(this.#ast, other.#ast);
190
191
  }
191
192
  one() {
193
+ this.#assertNotAggregated("one");
194
+ this.#assertNotDistinct("one");
192
195
  return this.#derive("one", void 0, void 0, () => this.#newQuery(this.#tableName, {
193
196
  ...this.#ast,
194
197
  limit: 1
@@ -197,6 +200,109 @@ var QueryImpl = class {
197
200
  singular: true
198
201
  }, this.customQueryID, this.#currentJunction));
199
202
  }
203
+ /**
204
+ * A bound goes in the same AST fields whether it is applied before or after
205
+ * an aggregate, where it bounds the rows the aggregate reduces. So it must
206
+ * come first: `q.limit(10).count()`, not `q.count().limit(10)`.
207
+ */
208
+ #assertNotAggregated(method) {
209
+ const { aggregate } = this.format;
210
+ if (aggregate) throw new Error(`${method}() must come before ${aggregate.fn}(): it bounds the rows the aggregate reduces`);
211
+ }
212
+ /** `method` doesn't apply to the rows of a `distinct()` or `groupBy()` yet. */
213
+ #assertNotDistinct(method) {
214
+ if (this.#ast.groupBy) throw new Error(`${method}() does not support ${this.#ast.aggregate ? "groupBy()" : "distinct()"} yet`);
215
+ }
216
+ #aggregate(fn, selector) {
217
+ this.#assertNotAggregated(fn);
218
+ const distinct = this.#ast.groupBy;
219
+ if (distinct && (fn !== "count" || this.#ast.aggregate)) this.#assertNotDistinct(fn);
220
+ if (this.customQueryID) throw new Error(`${fn}() cannot be applied to the named query "${this.customQueryID.name}": put it in the query's definition`);
221
+ const aggregate = distinct ? {
222
+ fn,
223
+ distinct
224
+ } : aggregateFromSelector(fn, selector);
225
+ const { field, path } = aggregate;
226
+ return this.#derive(AGGREGATE_KEYS[fn], field, path, () => this.#newQuery(this.#tableName, {
227
+ ...this.#ast,
228
+ groupBy: void 0,
229
+ aggregate
230
+ }, {
231
+ ...this.format,
232
+ singular: true,
233
+ aggregate
234
+ }, this.customQueryID, this.#currentJunction));
235
+ }
236
+ count() {
237
+ return this.#aggregate("count");
238
+ }
239
+ sum(field) {
240
+ return this.#aggregate("sum", field);
241
+ }
242
+ avg(field) {
243
+ return this.#aggregate("avg", field);
244
+ }
245
+ min(field) {
246
+ return this.#aggregate("min", field);
247
+ }
248
+ max(field) {
249
+ return this.#aggregate("max", field);
250
+ }
251
+ distinct(...columns) {
252
+ this.#assertGroupable("distinct", columns);
253
+ return this.#derive("distinct", JSON.stringify(columns), void 0, () => this.#newQuery(this.#tableName, {
254
+ ...this.#ast,
255
+ groupBy: columns
256
+ }, this.format, this.customQueryID, this.#currentJunction));
257
+ }
258
+ groupBy(...columns) {
259
+ this.#assertGroupable("groupBy", columns);
260
+ return new GroupedQueryImpl(this, columns);
261
+ }
262
+ /**
263
+ * The rows of `groupBy(...columns)` reduced by `fn`, each with the value
264
+ * under the function's name, as plain rows: the AST's `groupBy` and
265
+ * `aggregate` together. Interned on this query, like any other step.
266
+ * Internal: {@link GroupedQueryImpl} calls it.
267
+ */
268
+ groupAggregate(columns, fn, selector) {
269
+ if (columns.includes(fn)) throw new Error(`groupBy(): the column "${fn}" has the same name as the ${fn}() value`);
270
+ const aggregate = aggregateFromSelector(fn, selector);
271
+ return this.#derive(`groupBy:${fn}`, JSON.stringify([columns, aggregate.field ?? null]), aggregate.path, () => this.#newQuery(this.#tableName, {
272
+ ...this.#ast,
273
+ groupBy: columns,
274
+ aggregate
275
+ }, this.format, this.customQueryID, this.#currentJunction));
276
+ }
277
+ /**
278
+ * Checks the columns of `method()` (`distinct` or `groupBy`), and that the
279
+ * query so far can be grouped by them.
280
+ */
281
+ #assertGroupable(method, columns) {
282
+ this.#assertNotAggregated(method);
283
+ this.#assertNotDistinct(method);
284
+ if (this.customQueryID) throw new Error(`${method}() cannot be applied to the named query "${this.customQueryID.name}": put it in the query's definition`);
285
+ if (columns.length === 0) throw new Error(`${method}() needs at least one column`);
286
+ const tableColumns = this.#schema.tables[this.#tableName].columns;
287
+ columns.forEach((col, i) => {
288
+ const colSchema = tableColumns[col];
289
+ if (colSchema === void 0) throw new Error(`${method}(): "${col}" is not a column of "${this.#tableName}"`);
290
+ if (colSchema.type === "json") throw new Error(`${method}() does not support the json column "${col}"`);
291
+ if (columns.indexOf(col) !== i) throw new Error(`${method}(): "${col}" is named twice`);
292
+ if (isSyntheticColumn(col)) throw new Error(`${method}(): "${col}" is the name of a synthetic column, which a grouped row has too`);
293
+ });
294
+ const { limit, start, orderBy, related } = this.#ast;
295
+ if (limit !== void 0 || start !== void 0) throw new Error(`${method}() does not support limit(), start() or one() yet`);
296
+ if (related !== void 0) throw new Error(`${method}() does not support related() yet`);
297
+ for (const [col] of orderBy ?? []) this.#assertGroupColumn(col, columns);
298
+ }
299
+ /**
300
+ * The rows of a `distinct()` or `groupBy()` can only be ordered by its
301
+ * columns.
302
+ */
303
+ #assertGroupColumn(col, columns) {
304
+ if (!columns.includes(col)) throw new Error(`orderBy("${col}"): the rows can only be ordered by the grouped columns (${columns.map((c) => JSON.stringify(c)).join(", ")})`);
305
+ }
200
306
  whereExists(relationship, cbOrOptions, options) {
201
307
  const cb = typeof cbOrOptions === "function" ? cbOrOptions : void 0;
202
308
  const opts = typeof cbOrOptions === "function" ? options : cbOrOptions;
@@ -205,6 +311,7 @@ var QueryImpl = class {
205
311
  related(relationship, cb) {
206
312
  if (relationship.startsWith("zsubq_")) throw new Error(`Relationship names may not start with "${SUBQ_PREFIX}". That is a reserved prefix.`);
207
313
  cb = cb ?? ((q) => q);
314
+ this.#assertNotDistinct("related");
208
315
  const related = this.#schema.relationships[this.#tableName][relationship];
209
316
  assert(related, "Invalid relationship");
210
317
  if (isOneHop(related)) {
@@ -214,9 +321,11 @@ var QueryImpl = class {
214
321
  singular: cardinality === "one"
215
322
  }, this.customQueryID, void 0));
216
323
  const subQuery = asQueryImpl(cb(q));
324
+ assertSubqueryNotGrouped(subQuery, "related");
217
325
  assert(isCompoundKey(sourceField), "The source of a relationship must specify at last 1 field");
218
326
  assert(isCompoundKey(destField), "The destination of a relationship must specify at last 1 field");
219
327
  assert(sourceField.length === destField.length, "The source and destination of a relationship must have the same number of fields");
328
+ assert(!subQuery.format.aggregate || subQuery.#ast.related === void 0, "an aggregate relationship does not support related() on its subquery");
220
329
  return this.#derive(relatedKey(relationship), astID(subQuery.#ast), void 0, () => this.#newQuery(this.#tableName, {
221
330
  ...this.#ast,
222
331
  related: insertRelated(this.#ast.related, {
@@ -224,8 +333,12 @@ var QueryImpl = class {
224
333
  parentField: sourceField,
225
334
  childField: destField
226
335
  },
227
- subquery: subQuery.#ast,
228
- system: this.#system
336
+ subquery: subQuery.format.aggregate ? {
337
+ ...subQuery.#ast,
338
+ aggregate: void 0
339
+ } : subQuery.#ast,
340
+ system: this.#system,
341
+ aggregate: subQuery.format.aggregate
229
342
  })
230
343
  }, {
231
344
  ...this.format,
@@ -243,12 +356,74 @@ var QueryImpl = class {
243
356
  relationships: {},
244
357
  singular: secondRelation.cardinality === "one"
245
358
  }, this.customQueryID, relationship))));
359
+ assertSubqueryNotGrouped(sq, "related");
246
360
  const { sourceField: firstSource, destField: firstDest } = firstRelation;
247
361
  const { sourceField: secondSource, destField: secondDest } = secondRelation;
248
362
  assert(isCompoundKey(firstSource), "Invalid relationship");
249
363
  assert(isCompoundKey(firstDest), "Invalid relationship");
250
364
  assert(isCompoundKey(secondSource), "Invalid relationship");
251
365
  assert(isCompoundKey(secondDest), "Invalid relationship");
366
+ if (sq.format.aggregate) {
367
+ assert(sq.#ast.related === void 0 && sq.#ast.limit === void 0 && sq.#ast.start === void 0, "an aggregate over a junction relationship does not yet support related/limit/start on the destination");
368
+ const aggregate = sq.format.aggregate;
369
+ const { fn } = aggregate;
370
+ const correlation = {
371
+ parentField: firstSource,
372
+ childField: firstDest
373
+ };
374
+ const junctionWhere = normalizeCondition({
375
+ type: "correlatedSubquery",
376
+ op: "EXISTS",
377
+ related: {
378
+ correlation: {
379
+ parentField: secondSource,
380
+ childField: secondDest
381
+ },
382
+ subquery: {
383
+ ...sq.#ast,
384
+ aggregate: void 0
385
+ },
386
+ system: this.#system
387
+ }
388
+ });
389
+ const format = {
390
+ ...this.format,
391
+ relationships: {
392
+ ...this.format.relationships,
393
+ [relationship]: sq.format
394
+ }
395
+ };
396
+ return this.#derive(relatedKey(relationship), astID(sq.#ast), void 0, () => this.#newQuery(this.#tableName, {
397
+ ...this.#ast,
398
+ related: insertRelated(this.#ast.related, fn === "count" ? {
399
+ correlation,
400
+ subquery: {
401
+ ...tableAST(junctionSchema, relationship),
402
+ where: junctionWhere
403
+ },
404
+ system: this.#system,
405
+ aggregate: { fn: "count" }
406
+ } : {
407
+ correlation,
408
+ subquery: {
409
+ ...tableAST(junctionSchema, relationship),
410
+ related: [normalizedRelated({
411
+ correlation: {
412
+ parentField: secondSource,
413
+ childField: secondDest
414
+ },
415
+ subquery: {
416
+ ...sq.#ast,
417
+ aggregate: void 0
418
+ },
419
+ system: this.#system
420
+ })]
421
+ },
422
+ system: this.#system,
423
+ aggregate
424
+ })
425
+ }, format, this.customQueryID, this.#currentJunction));
426
+ }
252
427
  return this.#derive(relatedKey(relationship), astID(sq.#ast), void 0, () => this.#newQuery(this.#tableName, {
253
428
  ...this.#ast,
254
429
  related: insertRelated(this.#ast.related, {
@@ -321,6 +496,8 @@ var QueryImpl = class {
321
496
  });
322
497
  }
323
498
  start(row, opts) {
499
+ this.#assertNotAggregated("start");
500
+ this.#assertNotDistinct("start");
324
501
  return this.#derive(opts?.inclusive ? "start:inclusive" : "start:exclusive", valueTag(row), void 0, () => this.#newQuery(this.#tableName, {
325
502
  ...this.#ast,
326
503
  start: {
@@ -330,6 +507,8 @@ var QueryImpl = class {
330
507
  }, this.format, this.customQueryID, this.#currentJunction));
331
508
  }
332
509
  limit(limit) {
510
+ this.#assertNotAggregated("limit");
511
+ this.#assertNotDistinct("limit");
333
512
  if (limit < 0) throw new Error("Limit must be non-negative");
334
513
  if ((limit | 0) !== limit) throw new Error("Limit must be an integer");
335
514
  if (this.#currentJunction) throw new NotImplementedError("Limit is not supported in junction relationships yet. Junction relationship being limited: " + this.#currentJunction);
@@ -340,6 +519,7 @@ var QueryImpl = class {
340
519
  }
341
520
  orderBy(field, direction) {
342
521
  if (this.#currentJunction) throw new NotImplementedError("Order by is not supported in junction relationships yet. Junction relationship being ordered: " + this.#currentJunction);
522
+ if (this.#ast.groupBy) this.#assertGroupColumn(field, this.#ast.groupBy);
343
523
  return this.#derive(direction === "asc" ? "orderBy:asc" : "orderBy:desc", field, void 0, () => this.#newQuery(this.#tableName, {
344
524
  ...this.#ast,
345
525
  orderBy: [...this.#ast.orderBy ?? [], [field, direction]]
@@ -356,6 +536,8 @@ var QueryImpl = class {
356
536
  assert(isCompoundKey(sourceField), "Invalid relationship");
357
537
  assert(isCompoundKey(destField), "Invalid relationship");
358
538
  const subQuery = asQueryImpl(cb(this.#deriveBounded(`existsBase:${relationship}`, () => this.#newQuery(destTableName, tableAST(destTableName, `${SUBQ_PREFIX}${relationship}`), defaultFormat, this.customQueryID, void 0))));
539
+ assert(subQuery.#ast.aggregate === void 0, "exists() does not support an aggregate subquery");
540
+ assertSubqueryNotGrouped(subQuery, "exists");
359
541
  astID(subQuery.#ast);
360
542
  return {
361
543
  type: "correlatedSubquery",
@@ -381,6 +563,8 @@ var QueryImpl = class {
381
563
  const { destSchema } = secondRelation;
382
564
  const junctionSchema = firstRelation.destSchema;
383
565
  const queryToDest = cb(this.#deriveBounded(`existsJunctionBase:${relationship}`, () => this.#newQuery(destSchema, tableAST(destSchema, `${SUBQ_PREFIX}zhidden_${relationship}`), defaultFormat, this.customQueryID, relationship)));
566
+ assert(asQueryImpl(queryToDest).#ast.aggregate === void 0, "exists() does not support an aggregate subquery");
567
+ assertSubqueryNotGrouped(asQueryImpl(queryToDest), "exists");
384
568
  return {
385
569
  type: "correlatedSubquery",
386
570
  related: {
@@ -420,6 +604,42 @@ var QueryImpl = class {
420
604
  return this.#expressionBuilder ??= new ExpressionBuilder(this.#exists.bind(this));
421
605
  }
422
606
  };
607
+ /**
608
+ * The {@link GroupedQuery} of `query.groupBy(...columns)`. It only holds the
609
+ * grouping: each aggregate is a query derived from `query`, so asking for the
610
+ * same one twice gives the same query.
611
+ */
612
+ var GroupedQueryImpl = class {
613
+ #query;
614
+ #columns;
615
+ constructor(query, columns) {
616
+ this.#query = query;
617
+ this.#columns = columns;
618
+ }
619
+ count() {
620
+ return this.#query.groupAggregate(this.#columns, "count", void 0);
621
+ }
622
+ sum(selector) {
623
+ return this.#query.groupAggregate(this.#columns, "sum", selector);
624
+ }
625
+ avg(selector) {
626
+ return this.#query.groupAggregate(this.#columns, "avg", selector);
627
+ }
628
+ min(selector) {
629
+ return this.#query.groupAggregate(this.#columns, "min", selector);
630
+ }
631
+ max(selector) {
632
+ return this.#query.groupAggregate(this.#columns, "max", selector);
633
+ }
634
+ };
635
+ /**
636
+ * A subquery of `related()` or `exists()` can't be a `distinct()` or a
637
+ * `groupBy()` yet.
638
+ */
639
+ function assertSubqueryNotGrouped(sq, method) {
640
+ const { groupBy, aggregate } = sq.ast;
641
+ if (groupBy || aggregate?.distinct) throw new Error(`${method}() does not support a ${groupBy && aggregate ? "groupBy()" : "distinct()"} subquery yet`);
642
+ }
423
643
  function asQueryImpl(q) {
424
644
  assert(q instanceof QueryImpl, "Expected QueryImpl instance");
425
645
  return q;
@@ -457,6 +677,13 @@ function whereKey(column, op) {
457
677
  const byOp = getOrInsertComputed(whereKeys, column, newMap);
458
678
  return getOrInsertComputed(byOp, op, (op) => `where:${column}:${op}`);
459
679
  }
680
+ var AGGREGATE_KEYS = {
681
+ count: "aggregate:count",
682
+ sum: "aggregate:sum",
683
+ avg: "aggregate:avg",
684
+ min: "aggregate:min",
685
+ max: "aggregate:max"
686
+ };
460
687
  var relatedKeys = /* @__PURE__ */ new Map();
461
688
  var newRelatedKey = (relationship) => `related:${relationship}`;
462
689
  function relatedKey(relationship) {
@@ -542,9 +769,14 @@ function tri(b) {
542
769
  */
543
770
  function condKey(cond) {
544
771
  switch (cond.type) {
545
- case "simple":
546
- if (cond.left.type !== "column") return;
547
- return `S${enc(cond.left.name)}${enc(cond.op)}${rightTag(cond.right)}`;
772
+ case "simple": {
773
+ const { left } = cond;
774
+ switch (left.type) {
775
+ case "column": return `S${enc(left.name)}${enc(cond.op)}${rightTag(cond.right)}`;
776
+ case "json": return `J${enc(left.value.name)}${valueTag(left.path)}${enc(cond.op)}${rightTag(cond.right)}`;
777
+ default: return;
778
+ }
779
+ }
548
780
  case "correlatedSubquery": {
549
781
  const id = astIDs.get(cond.related.subquery);
550
782
  return id === void 0 ? void 0 : `E${id}:${enc(cond.op)}${tri(cond.flip)}${tri(cond.scalar)}`;