@luma.gl/graph 10.0.0-beta.3 → 10.0.0-beta.4

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 (125) hide show
  1. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +66 -30
  2. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +7 -1
  3. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -1
  4. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +78 -32
  5. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -1
  6. package/dist/arrow/gpu/arrow-gpu-vector-conversion.cjs +7 -0
  7. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts +2 -0
  8. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts.map +1 -1
  9. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js +14 -0
  10. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js.map +1 -1
  11. package/dist/arrow/index.cjs.map +2 -2
  12. package/dist/arrow/vectors/arrow-temporal-gpu-vector.cjs +1 -2
  13. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js +2 -2
  14. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js.map +1 -1
  15. package/dist/dist.dev.js +62 -27
  16. package/dist/dist.min.js +48 -47
  17. package/dist/gpu-core/gpu-command-graph-budget-controller.cjs +10 -2
  18. package/dist/gpu-core/gpu-command-graph-budget-controller.d.ts +4 -0
  19. package/dist/gpu-core/gpu-command-graph-budget-controller.d.ts.map +1 -1
  20. package/dist/gpu-core/gpu-command-graph-budget-controller.js +10 -2
  21. package/dist/gpu-core/gpu-command-graph-budget-controller.js.map +1 -1
  22. package/dist/gpu-core/gpu-group-aggregation.cjs +45 -21
  23. package/dist/gpu-core/gpu-group-aggregation.d.ts +4 -0
  24. package/dist/gpu-core/gpu-group-aggregation.d.ts.map +1 -1
  25. package/dist/gpu-core/gpu-group-aggregation.js +58 -24
  26. package/dist/gpu-core/gpu-group-aggregation.js.map +1 -1
  27. package/dist/gpu-core/index.cjs.map +1 -1
  28. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.cjs +6 -2
  29. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts +2 -1
  30. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts.map +1 -1
  31. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js +6 -2
  32. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js.map +1 -1
  33. package/dist/gpu-dataframe/gpu-global-sort-compiler.cjs +61 -54
  34. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts +6 -1
  35. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts.map +1 -1
  36. package/dist/gpu-dataframe/gpu-global-sort-compiler.js +61 -55
  37. package/dist/gpu-dataframe/gpu-global-sort-compiler.js.map +1 -1
  38. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.cjs +88 -13
  39. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts +11 -4
  40. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts.map +1 -1
  41. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js +96 -16
  42. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js.map +1 -1
  43. package/dist/gpu-dataframe/gpu-group-by-query.cjs +12 -3
  44. package/dist/gpu-dataframe/gpu-group-by-query.d.ts +8 -1
  45. package/dist/gpu-dataframe/gpu-group-by-query.d.ts.map +1 -1
  46. package/dist/gpu-dataframe/gpu-group-by-query.js +13 -3
  47. package/dist/gpu-dataframe/gpu-group-by-query.js.map +1 -1
  48. package/dist/gpu-dataframe/gpu-join-compiler.cjs +53 -2
  49. package/dist/gpu-dataframe/gpu-join-compiler.d.ts +9 -1
  50. package/dist/gpu-dataframe/gpu-join-compiler.d.ts.map +1 -1
  51. package/dist/gpu-dataframe/gpu-join-compiler.js +51 -0
  52. package/dist/gpu-dataframe/gpu-join-compiler.js.map +1 -1
  53. package/dist/gpu-dataframe/gpu-query-compiler.cjs +24 -0
  54. package/dist/gpu-dataframe/gpu-query-compiler.d.ts +3 -1
  55. package/dist/gpu-dataframe/gpu-query-compiler.d.ts.map +1 -1
  56. package/dist/gpu-dataframe/gpu-query-compiler.js +25 -0
  57. package/dist/gpu-dataframe/gpu-query-compiler.js.map +1 -1
  58. package/dist/gpu-dataframe/index.cjs.map +3 -3
  59. package/dist/gpu-graph/index.cjs.map +1 -1
  60. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +2 -2
  61. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.cjs +182 -62
  62. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.d.ts +29 -2
  63. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.d.ts.map +1 -1
  64. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js +200 -64
  65. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js.map +1 -1
  66. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.cjs +135 -9
  67. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.d.ts +55 -8
  68. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.d.ts.map +1 -1
  69. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.js +145 -14
  70. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.js.map +1 -1
  71. package/dist/gpu-graph-algorithms/index.cjs.map +3 -3
  72. package/dist/gpu-physics/articulation-tree-shader.cjs +177 -0
  73. package/dist/gpu-physics/articulation-tree-shader.d.ts +3 -0
  74. package/dist/gpu-physics/articulation-tree-shader.d.ts.map +1 -0
  75. package/dist/gpu-physics/articulation-tree-shader.js +159 -0
  76. package/dist/gpu-physics/articulation-tree-shader.js.map +1 -0
  77. package/dist/gpu-physics/gpu-articulation-tree.cjs +203 -0
  78. package/dist/gpu-physics/gpu-articulation-tree.d.ts +81 -0
  79. package/dist/gpu-physics/gpu-articulation-tree.d.ts.map +1 -0
  80. package/dist/gpu-physics/gpu-articulation-tree.js +205 -0
  81. package/dist/gpu-physics/gpu-articulation-tree.js.map +1 -0
  82. package/dist/gpu-physics/gpu-rigid-body-world.cjs +62 -0
  83. package/dist/gpu-physics/gpu-rigid-body-world.d.ts +12 -0
  84. package/dist/gpu-physics/gpu-rigid-body-world.d.ts.map +1 -1
  85. package/dist/gpu-physics/gpu-rigid-body-world.js +76 -0
  86. package/dist/gpu-physics/gpu-rigid-body-world.js.map +1 -1
  87. package/dist/gpu-physics/index.cjs +3 -0
  88. package/dist/gpu-physics/index.cjs.map +3 -3
  89. package/dist/gpu-physics/index.d.ts +1 -0
  90. package/dist/gpu-physics/index.d.ts.map +1 -1
  91. package/dist/gpu-physics/index.js +1 -0
  92. package/dist/gpu-physics/index.js.map +1 -1
  93. package/dist/gpu-physics/rigid-body-joints.d.ts +2 -0
  94. package/dist/gpu-physics/rigid-body-joints.d.ts.map +1 -1
  95. package/dist/gpu-physics/rigid-body-joints.js.map +1 -1
  96. package/dist/gpu-project/graph.cjs.map +2 -2
  97. package/dist/gpu-simple-graph/index.cjs.map +2 -2
  98. package/dist/gpu-sql/gpu-sql.cjs +167 -47
  99. package/dist/gpu-sql/gpu-sql.d.ts +6 -1
  100. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  101. package/dist/gpu-sql/gpu-sql.js +187 -47
  102. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  103. package/dist/gpu-sql/index.cjs.map +3 -3
  104. package/dist/index.cjs.map +1 -1
  105. package/package.json +8 -8
  106. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +94 -40
  107. package/src/arrow/gpu/arrow-gpu-vector-conversion.ts +19 -0
  108. package/src/arrow/vectors/arrow-temporal-gpu-vector.ts +2 -2
  109. package/src/gpu-core/gpu-command-graph-budget-controller.ts +22 -2
  110. package/src/gpu-core/gpu-group-aggregation.ts +68 -30
  111. package/src/gpu-dataframe/gpu-global-aggregation-compiler.ts +9 -2
  112. package/src/gpu-dataframe/gpu-global-sort-compiler.ts +95 -78
  113. package/src/gpu-dataframe/gpu-group-aggregation-compiler.ts +191 -24
  114. package/src/gpu-dataframe/gpu-group-by-query.ts +27 -4
  115. package/src/gpu-dataframe/gpu-join-compiler.ts +75 -0
  116. package/src/gpu-dataframe/gpu-query-compiler.ts +41 -1
  117. package/src/gpu-graph-algorithms/README.md +4 -2
  118. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.ts +248 -66
  119. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.ts +218 -20
  120. package/src/gpu-physics/articulation-tree-shader.ts +169 -0
  121. package/src/gpu-physics/gpu-articulation-tree.ts +279 -0
  122. package/src/gpu-physics/gpu-rigid-body-world.ts +89 -0
  123. package/src/gpu-physics/index.ts +7 -0
  124. package/src/gpu-physics/rigid-body-joints.ts +2 -0
  125. package/src/gpu-sql/gpu-sql.ts +248 -57
@@ -31,7 +31,9 @@ import {
31
31
  type GPUExpressionNode
32
32
  } from '../gpu-dataframe/gpu-expression';
33
33
  import {lowerPortableExpression} from '../gpu-dataframe/portable-expression';
34
- import {compileGPUDataFrameJoin} from '../gpu-dataframe/gpu-join-compiler';
34
+ import {compileGPUDataFrameAggregation} from '../gpu-dataframe/gpu-global-aggregation-compiler';
35
+ import type {GPUDataFrameAggregationDefinition} from '../gpu-dataframe/gpu-group-by-query';
36
+ import {compileGPUDataFrameJoin, type GPUAggregateJoin} from '../gpu-dataframe/gpu-join-compiler';
35
37
  import type {
36
38
  GPUDataFrameJoinType,
37
39
  GPUDataFrameNormalizedJoinOptions
@@ -44,8 +46,13 @@ import type {
44
46
  /** Explicit GPU dataframe registrations; Arrow remains exclusively an adapter boundary. */
45
47
  export type GPUSQLTables = Readonly<Record<string, GPUDataFrame>>;
46
48
 
47
- /** Defaults for named SQL parameters such as `:minimumFare`; values remain caller-controlled. */
48
- export type GPUSQLQueryOptions = Readonly<{parameters?: GPUDataFrameQueryParameters}>;
49
+ /** Configuration for GPU-only SQL planning. */
50
+ export type GPUSQLQueryOptions = Readonly<{
51
+ /** Defaults for named SQL parameters such as :minimumFare. */
52
+ parameters?: GPUDataFrameQueryParameters;
53
+ /** Maximum temporary count bytes per grouped AVG operation. */
54
+ maxMeanScratchBytes?: number;
55
+ }>;
49
56
 
50
57
  /** A source column name with its optional, separately parsed table qualifier. */
51
58
  type GPUSQLColumnReference = Readonly<{name: string; qualifier?: string}>;
@@ -72,6 +79,7 @@ type GPUSQLStatement = Readonly<{
72
79
  }>;
73
80
  predicate?: Expression;
74
81
  groupBy?: readonly Expression[];
82
+ having?: Expression;
75
83
  orderBy?: readonly Readonly<{
76
84
  expression: Expression;
77
85
  direction: 'ascending' | 'descending';
@@ -96,6 +104,8 @@ export type GPUSQLExplanation = Readonly<{
96
104
  table: string;
97
105
  /** Whether a source-row WHERE predicate runs before the terminal operation. */
98
106
  filtered: boolean;
107
+ /** A post-aggregation HAVING predicate filters the grouped result. */
108
+ having?: true;
99
109
  /** Terminal GPU dataframe execution route. */
100
110
  execution: GPUSQLExecution;
101
111
  /** Result fields in SELECT order. */
@@ -143,7 +153,9 @@ type GPUSQLDynamicQuery = GPUSQLCompiledPlan & {
143
153
  groupBy: (key: string) => {
144
154
  readonly groupCount: number;
145
155
  };
146
- aggregate: (definitions: GPUSQLAggregationDefinitions) => GPUSQLCompiledPlan;
156
+ aggregate: (
157
+ definitions: GPUSQLAggregationDefinitions
158
+ ) => GPUSQLCompiledPlan & {readonly definitions: readonly GPUDataFrameAggregationDefinition[]};
147
159
  sortByGlobal: (
148
160
  name: string,
149
161
  options: {direction: 'ascending' | 'descending'; nulls?: 'first' | 'last'}
@@ -182,7 +194,7 @@ export class GPUSQLContext {
182
194
  const statement = parseGPUSQLStatement(source);
183
195
  return new GPUSQLQuery(
184
196
  source,
185
- buildGPUSQLPlan(this.tables, statement, options.parameters ?? {})
197
+ buildGPUSQLPlan(this.tables, statement, options.parameters ?? {}, options.maxMeanScratchBytes)
186
198
  );
187
199
  }
188
200
  }
@@ -214,7 +226,8 @@ export class GPUSQLQuery {
214
226
  function buildGPUSQLPlan(
215
227
  tables: Readonly<Record<string, GPUDataFrame>>,
216
228
  statement: GPUSQLStatement,
217
- parameters: GPUDataFrameQueryParameters
229
+ parameters: GPUDataFrameQueryParameters,
230
+ maxMeanScratchBytes?: number
218
231
  ): GPUSQLBoundPlan {
219
232
  const frame = tables[statement.table.toLowerCase()];
220
233
  if (!frame) throw new Error(`GPUSQL table "${statement.table}" is not registered`);
@@ -242,6 +255,7 @@ function buildGPUSQLPlan(
242
255
  explanation: Object.freeze({
243
256
  table: statement.table,
244
257
  filtered: Boolean(statement.predicate),
258
+ ...(statement.having ? {having: true as const} : {}),
245
259
  execution,
246
260
  columns: Object.freeze([...columns]),
247
261
  workingColumns: Object.freeze([...workingColumns]),
@@ -255,49 +269,106 @@ function buildGPUSQLPlan(
255
269
  })
256
270
  });
257
271
 
272
+ /** Binds a single equality join for row-returning and aggregate plans. */
273
+ const bindJoin = (join: NonNullable<GPUSQLStatement['join']>) => {
274
+ const right = tables[join.table.toLowerCase()];
275
+ if (!right) throw new Error(`GPUSQL table "${join.table}" is not registered`);
276
+ const rightQualifier = join.alias ?? join.table;
277
+ const {left: firstOperand, right: secondOperand} = join;
278
+ const matchesLeft = (reference: GPUSQLColumnReference) =>
279
+ matchesGPUSQLColumn(reference, qualifier, frame.columnNames);
280
+ const matchesRight = (reference: GPUSQLColumnReference) =>
281
+ matchesGPUSQLColumn(reference, rightQualifier, right.columnNames);
282
+ const forward = matchesLeft(firstOperand) && matchesRight(secondOperand);
283
+ const reversed = matchesLeft(secondOperand) && matchesRight(firstOperand);
284
+ if (forward && reversed) {
285
+ throw new Error('GPUSQL JOIN key references are ambiguous; qualify the columns');
286
+ }
287
+ const leftKey = resolve(reversed ? secondOperand : firstOperand);
288
+ const rightKey = resolveGPUSQLColumn(
289
+ reversed ? firstOperand : secondOperand,
290
+ rightQualifier,
291
+ right.columnNames
292
+ );
293
+ return {right, leftKey, rightKey};
294
+ };
295
+ const joinMethods = {
296
+ left: 'leftJoin',
297
+ semi: 'semiJoin',
298
+ anti: 'antiJoin',
299
+ inner: 'innerJoin'
300
+ } as const;
301
+
258
302
  const aggregates = statement.items.filter(item => item.aggregate);
259
- if (aggregates.length > 0) {
303
+ if (statement.having && !statement.groupBy) {
304
+ throw new Error('GPUSQL HAVING requires GROUP BY');
305
+ }
306
+ if (aggregates.length > 0 || statement.having || (statement.groupBy && statement.orderBy)) {
260
307
  if (
261
- statement.join ||
262
- statement.orderBy ||
263
- statement.limit !== undefined ||
264
- statement.offset !== undefined
308
+ !statement.groupBy &&
309
+ (statement.orderBy || statement.limit !== undefined || statement.offset !== undefined)
265
310
  ) {
266
- throw new Error('GPUSQL aggregate queries do not yet support joins, ordering, or pagination');
311
+ throw new Error(
312
+ 'GPUSQL aggregate queries without GROUP BY do not yet support ordering or pagination'
313
+ );
314
+ }
315
+ let aggregateJoin: GPUAggregateJoin | undefined;
316
+ if (statement.join) {
317
+ const {right, leftKey, rightKey} = bindJoin(statement.join);
318
+ const type = statement.join.type;
319
+ const join = query[joinMethods[type]](right, {leftOn: leftKey, rightOn: rightKey});
320
+ aggregateJoin = {right, type, options: join.options};
267
321
  }
268
- const definitions: GPUSQLAggregationDefinitions = {};
322
+ const definitions: GPUSQLAggregationDefinitions = Object.create(null);
269
323
  const reservedNames = new Set(frame.columnNames);
270
324
  const outputNames = new Map<GPUSQLSelectItem, string>();
325
+ const aggregateOutputs = new Map<string, string>();
271
326
  let inputIndex = 0;
272
- for (const item of aggregates) {
273
- const input =
274
- item.aggregateInput && lowerSQLExpression(item.aggregateInput, parameters, resolve);
327
+ /** Registers an aggregate and materializes its computed input when needed. */
328
+ const registerAggregate = (
329
+ operation: NonNullable<GPUSQLSelectItem['aggregate']>,
330
+ input?: GPUExpressionNode,
331
+ alias?: string
332
+ ): string => {
275
333
  let inputColumn = input?.kind === 'column' ? input.name : undefined;
276
334
  if (input && input.kind !== 'column') {
277
- if (!item.alias) {
335
+ if (!alias)
278
336
  throw new Error('GPUSQL computed aggregate inputs require an explicit AS alias');
279
- }
280
337
  do {
281
338
  inputColumn = '__sqlAggregateInput' + inputIndex++;
282
339
  } while (reservedNames.has(inputColumn));
283
340
  reservedNames.add(inputColumn);
284
341
  query = query.withColumn(inputColumn, new GPUExpression<number | null, string>(input));
285
342
  }
286
- const name = item.alias ?? `${item.aggregate}_${inputColumn ?? 'all'}`;
287
- outputNames.set(item, name);
288
- if (definitions[name]) throw new Error(`GPUSQL aggregate alias "${name}" is duplicated`);
343
+ const name = alias ?? `${operation}_${inputColumn ?? 'all'}`;
344
+ if (Object.hasOwn(definitions, name)) {
345
+ throw new Error(`GPUSQL aggregate alias "${name}" is duplicated`);
346
+ }
347
+ aggregateOutputs.set(JSON.stringify([operation, input ?? null]), name);
289
348
  definitions[name] =
290
- item.aggregate === 'count'
349
+ operation === 'count'
291
350
  ? inputColumn === undefined
292
351
  ? 'count'
293
352
  : {count: inputColumn}
294
- : ({[item.aggregate!]: inputColumn!} as
353
+ : ({[operation]: inputColumn!} as
295
354
  | {sum: string}
296
355
  | {min: string}
297
356
  | {max: string}
298
357
  | {mean: string});
358
+ return name;
359
+ };
360
+ for (const item of aggregates) {
361
+ const input =
362
+ item.aggregateInput && lowerSQLExpression(item.aggregateInput, parameters, resolve);
363
+ outputNames.set(item, registerAggregate(item.aggregate!, input, item.alias));
299
364
  }
300
365
  if (statement.groupBy !== undefined) {
366
+ if (
367
+ maxMeanScratchBytes !== undefined &&
368
+ (!Number.isSafeInteger(maxMeanScratchBytes) || maxMeanScratchBytes < 4)
369
+ ) {
370
+ throw new Error('GPUSQL mean scratch budget requires at least four bytes');
371
+ }
301
372
  const keyItems = statement.items.filter(item => !item.aggregate);
302
373
  const occupied = new Set(Object.keys(definitions));
303
374
  const selectedKeys = new Map<string, {source: string; output: string}>();
@@ -369,8 +440,81 @@ function buildGPUSQLPlan(
369
440
  );
370
441
  }
371
442
 
372
- const {predicates, selectedColumns, derivedColumns} = query;
373
443
  const columns = statement.items.map(item => outputNames.get(item)!);
444
+ if (!statement.orderBy && (statement.limit !== undefined || statement.offset !== undefined)) {
445
+ throw new Error('GPUSQL LIMIT or OFFSET currently requires ORDER BY');
446
+ }
447
+ /** Resolves or registers an aggregate used by a post-group clause. */
448
+ const bindAggregateCall = (call: Extract<Expression, {type: 'CallExpression'}>) => {
449
+ const name =
450
+ call.callee.type === 'Identifier' ? String(call.callee['name']).toLowerCase() : '';
451
+ const operation = name === 'avg' ? 'mean' : name;
452
+ if (
453
+ operation !== 'count' &&
454
+ operation !== 'sum' &&
455
+ operation !== 'min' &&
456
+ operation !== 'max' &&
457
+ operation !== 'mean'
458
+ )
459
+ return undefined;
460
+ if (call.arguments.length !== 1) throw new Error('GPUSQL aggregates require one argument');
461
+ const argument = call.arguments[0] as Expression;
462
+ const wildcard = argument.type === 'Identifier' && argument['sqlWildcard'] === true;
463
+ if (wildcard && operation !== 'count') {
464
+ throw new Error('GPUSQL only permits COUNT(*) as a wildcard aggregation');
465
+ }
466
+ const input = wildcard ? undefined : lowerSQLExpression(argument, parameters, resolve);
467
+ const output = aggregateOutputs.get(JSON.stringify([operation, input ?? null]));
468
+ if (output !== undefined) return column(output).node;
469
+ let hiddenName: string;
470
+ do {
471
+ hiddenName = '__sqlPostGroupAggregate' + inputIndex++;
472
+ } while (occupied.has(hiddenName));
473
+ occupied.add(hiddenName);
474
+ return column(registerAggregate(operation, input, hiddenName)).node;
475
+ };
476
+ const having = statement.having
477
+ ? new GPUExpression<boolean, string>(
478
+ lowerSQLExpression(
479
+ statement.having,
480
+ parameters,
481
+ reference => resolveGPUSQLColumn(reference, '', columns),
482
+ bindAggregateCall
483
+ )
484
+ )
485
+ : undefined;
486
+ const ordering: GPUGlobalSortKey[] | undefined = statement.orderBy?.map(
487
+ ({expression, direction, nulls}, index) => {
488
+ const column =
489
+ expression.type === 'Literal' && typeof expression.value === 'number'
490
+ ? getGPUSQLProjectionItem(columns, expression.value, 'ORDER BY')
491
+ : expression.type === 'Identifier' && !('gpuSQLParameter' in expression)
492
+ ? expression.name
493
+ : undefined;
494
+ const aggregate =
495
+ expression.type === 'CallExpression' ? bindAggregateCall(expression) : undefined;
496
+ const sortColumn = aggregate?.kind === 'column' ? aggregate.name : column;
497
+ if (sortColumn === undefined || (!aggregate && !columns.includes(sortColumn))) {
498
+ throw new Error(
499
+ 'GPUSQL grouped ORDER BY requires a SELECT output name, position, or aggregate call'
500
+ );
501
+ }
502
+ return {
503
+ column: sortColumn,
504
+ options: {
505
+ direction,
506
+ nulls: nulls ?? 'last',
507
+ nans: 'last',
508
+ algorithm: 'auto',
509
+ ...(index === 0 ? {limit: statement.limit, offset: statement.offset} : {})
510
+ }
511
+ };
512
+ }
513
+ );
514
+ const {predicates, selectedColumns, derivedColumns} = query;
515
+ if (Object.keys(definitions).length === 0) {
516
+ throw new Error('GPUSQL GROUP BY requires at least one aggregation');
517
+ }
374
518
  const normalized = normalizeGPUDataFrameAggregations<GPUTypeMap, string, GPUTypeMap>(
375
519
  {...query, source: frame},
376
520
  keys[0].output,
@@ -400,7 +544,11 @@ function buildGPUSQLPlan(
400
544
  keys,
401
545
  normalized,
402
546
  graph,
403
- columns
547
+ columns,
548
+ ordering,
549
+ having,
550
+ aggregateJoin,
551
+ maxMeanScratchBytes
404
552
  )
405
553
  },
406
554
  'observed-grouping',
@@ -424,7 +572,11 @@ function buildGPUSQLPlan(
424
572
  groupCount,
425
573
  normalized,
426
574
  graph,
427
- {key: key.output!, columns}
575
+ {key: key.output!, columns},
576
+ ordering,
577
+ having,
578
+ aggregateJoin,
579
+ maxMeanScratchBytes
428
580
  )
429
581
  },
430
582
  'dense-grouping',
@@ -436,8 +588,23 @@ function buildGPUSQLPlan(
436
588
  if (aggregates.length !== statement.items.length) {
437
589
  throw new Error('GPUSQL global aggregates cannot mix ordinary source columns');
438
590
  }
591
+ const aggregate = query.aggregate(definitions);
592
+ const {predicates, selectedColumns, derivedColumns} = query;
439
593
  return describe(
440
- query.aggregate(definitions),
594
+ aggregateJoin
595
+ ? {
596
+ compile: graph =>
597
+ compileGPUDataFrameAggregation(
598
+ frame,
599
+ predicates,
600
+ selectedColumns,
601
+ derivedColumns,
602
+ aggregate.definitions,
603
+ graph,
604
+ aggregateJoin
605
+ )
606
+ }
607
+ : aggregate,
441
608
  'global-aggregation',
442
609
  statement.items.map(item => outputNames.get(item)!),
443
610
  query.selectedColumns
@@ -471,36 +638,12 @@ function buildGPUSQLPlan(
471
638
  if (statement.orderBy || statement.limit !== undefined || statement.offset !== undefined) {
472
639
  throw new Error('GPUSQL joined results do not yet support ORDER BY or pagination');
473
640
  }
474
- const right = tables[statement.join.table.toLowerCase()];
475
- if (!right) throw new Error(`GPUSQL table "${statement.join.table}" is not registered`);
476
- const rightQualifier = statement.join.alias ?? statement.join.table;
477
- const {left: firstOperand, right: secondOperand} = statement.join;
478
- const matchesLeft = (reference: GPUSQLColumnReference) =>
479
- matchesGPUSQLColumn(reference, qualifier, frame.columnNames);
480
- const matchesRight = (reference: GPUSQLColumnReference) =>
481
- matchesGPUSQLColumn(reference, rightQualifier, right.columnNames);
482
- const forward = matchesLeft(firstOperand) && matchesRight(secondOperand);
483
- const reversed = matchesLeft(secondOperand) && matchesRight(firstOperand);
484
- if (forward && reversed) {
485
- throw new Error('GPUSQL JOIN key references are ambiguous; qualify the columns');
486
- }
487
- const leftKey = resolve(reversed ? secondOperand : firstOperand);
488
- const rightKey = resolveGPUSQLColumn(
489
- reversed ? firstOperand : secondOperand,
490
- rightQualifier,
491
- right.columnNames
492
- );
641
+ const {right, leftKey, rightKey} = bindJoin(statement.join);
493
642
  const keyIsSelected = selected.includes(leftKey);
494
643
  const workingColumns = keyIsSelected ? selected : [...selected, leftKey];
495
644
  const workingQuery = query.select(workingColumns);
496
645
  const joinType = statement.join.type;
497
- const method = {
498
- left: 'leftJoin',
499
- semi: 'semiJoin',
500
- anti: 'antiJoin',
501
- inner: 'innerJoin'
502
- } as const;
503
- const join = workingQuery[method[joinType]](right, {leftOn: leftKey, rightOn: rightKey});
646
+ const join = workingQuery[joinMethods[joinType]](right, {leftOn: leftKey, rightOn: rightKey});
504
647
  if (keyIsSelected) return describe(join, 'unique-right-join', selected, workingColumns, 1);
505
648
 
506
649
  const {predicates, derivedColumns} = workingQuery;
@@ -641,11 +784,49 @@ function resolveGPUSQLColumn(
641
784
  return reference.name;
642
785
  }
643
786
 
787
+ /** Isolates the top-level HAVING clause until the shared SELECT parser exposes it. */
788
+ function splitGPUSQLHaving(source: string): {select: string; having?: string} {
789
+ const tokens = /"(?:""|[^"])*"|'(?:''|[^'])*'|:[A-Za-z_]\w*|[A-Za-z_]\w*|[();]|--[^\r\n]*|\/\*/g;
790
+ let depth = 0;
791
+ let start = -1;
792
+ let predicateStart = -1;
793
+ let end = source.length;
794
+ let tailStarted = false;
795
+ for (const token of source.matchAll(tokens)) {
796
+ if (token[0].startsWith('--')) continue;
797
+ if (token[0] === '/*') {
798
+ throw new Error('GPUSQL does not support SQL comments');
799
+ }
800
+ if (token[0] === '(') depth++;
801
+ if (token[0] === ')') depth--;
802
+ if (depth !== 0) continue;
803
+ const keyword = token[0].toUpperCase();
804
+ if (start !== -1 && ['ORDER', 'LIMIT', 'OFFSET', ';'].includes(keyword)) {
805
+ end = token.index;
806
+ break;
807
+ }
808
+ if (start === -1 && ['ORDER', 'LIMIT', 'OFFSET', ';'].includes(keyword)) tailStarted = true;
809
+ if (start === -1 && keyword === 'HAVING') {
810
+ if (tailStarted) throw new Error('GPUSQL HAVING must precede ORDER BY and pagination');
811
+ start = token.index;
812
+ predicateStart = start + token[0].length;
813
+ }
814
+ }
815
+ return start === -1
816
+ ? {select: source}
817
+ : {
818
+ select: source.slice(0, start) + ' ' + source.slice(end),
819
+ having: source.slice(predicateStart, end)
820
+ };
821
+ }
822
+
644
823
  /** Parses the SQL subset supported by the GPU relational planner. */
645
824
  function parseGPUSQLStatement(source: string): GPUSQLStatement {
646
- const statement = parseSQLSelectStatement(source, {
647
- parseParameter: name => ({type: 'Identifier', name, gpuSQLParameter: true})
648
- });
825
+ const {select, having} = splitGPUSQLHaving(source);
826
+ const options = {
827
+ parseParameter: (name: string) => ({type: 'Identifier' as const, name, gpuSQLParameter: true})
828
+ };
829
+ const statement = parseSQLSelectStatement(select, options);
649
830
  if (statement.offset !== undefined && statement.offset > 0xffffffff) {
650
831
  throw new Error('GPUSQL OFFSET must fit an unsigned 32-bit row count');
651
832
  }
@@ -706,6 +887,11 @@ function parseGPUSQLStatement(source: string): GPUSQLStatement {
706
887
  alias: statement.from.alias,
707
888
  join: loweredJoin,
708
889
  predicate: statement.where as Expression | undefined,
890
+ having:
891
+ having === undefined
892
+ ? undefined
893
+ : parseSQLSelectStatement('SELECT (' + having + '\n) FROM __gpu_having', options).select![0]
894
+ .expression,
709
895
  groupBy: statement.groupBy?.length
710
896
  ? statement.groupBy.map(expression => expression as Expression)
711
897
  : undefined,
@@ -759,7 +945,10 @@ function readGPUSQLColumn(
759
945
  function lowerSQLExpression(
760
946
  node: Extract<Expression, {type: 'BinaryExpression'}>['left'],
761
947
  parameters: GPUDataFrameQueryParameters,
762
- resolve: (reference: GPUSQLColumnReference) => string
948
+ resolve: (reference: GPUSQLColumnReference) => string,
949
+ resolveCall?: (
950
+ call: Extract<Expression, {type: 'CallExpression'}>
951
+ ) => GPUExpressionNode | undefined
763
952
  ): GPUExpressionNode {
764
953
  const expression = node as Expression;
765
954
  try {
@@ -775,6 +964,8 @@ function lowerSQLExpression(
775
964
  return column(resolve(readGPUSQLColumn(leaf))).node;
776
965
  }
777
966
  if (leaf.type === 'CallExpression' && leaf.callee.type === 'Identifier') {
967
+ const replacement = resolveCall?.(leaf);
968
+ if (replacement) return replacement;
778
969
  const name = leaf.callee['name'];
779
970
  const functionName =
780
971
  typeof name === 'string' && leaf['sqlFunction'] === true ? name.toLowerCase() : name;