@malloydata/malloy-tests 0.0.437 → 0.0.439

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.
@@ -3,10 +3,16 @@
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
5
 
6
+ import type {Dialect} from '@malloydata/malloy';
6
7
  import {RuntimeList, allDatabases, testFileSpace} from '../../runtimes';
7
8
  import {databasesFromEnvironmentOr} from '../../util';
8
9
  import '@malloydata/malloy/test/matchers';
9
- import {wrapTestModel} from '@malloydata/malloy/test';
10
+ import {
11
+ extendTestModel,
12
+ mkTestModel,
13
+ TV,
14
+ wrapTestModel,
15
+ } from '@malloydata/malloy/test';
10
16
 
11
17
  const runtimes = new RuntimeList(databasesFromEnvironmentOr(allDatabases));
12
18
 
@@ -205,6 +211,369 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
205
211
  }
206
212
  );
207
213
 
214
+ // Trino and Presto declare the nest's count() as INTEGER in its ROW type,
215
+ // which makes this the symmetric sum of a 32 bit value.
216
+ test.when(runtime.supportsNesting)(
217
+ 'symmetric sum of an integer nest field through a join',
218
+ async () => {
219
+ await expect(`
220
+ source: three is ${databaseName}.table('malloytest.airports') -> {
221
+ group_by: state
222
+ nest: types is { group_by: fac_type; aggregate: c is count() }
223
+ }
224
+ source: sf is ${databaseName}.table('malloytest.state_facts') extend {
225
+ join_one: three on three.state = state
226
+ }
227
+ run: sf -> {
228
+ where: state = 'AK'
229
+ aggregate:
230
+ n is three.types.count()
231
+ t is three.types.c.sum()
232
+ }
233
+ `).toMatchResult(joinModel, {n: 3, t: 608});
234
+ }
235
+ );
236
+
237
+ // A dialect which sums a value by adding it to a hash of its row does
238
+ // arithmetic on the value, in whatever type its column has.
239
+ describe('symmetric sum and avg, by the type of the value', () => {
240
+ const accounts = mkTestModel(runtime, {
241
+ accounts: [
242
+ {
243
+ account_id: 1,
244
+ small: 474,
245
+ negative: -474,
246
+ negative_fraction: TV.float(-2.5),
247
+ big: TV.bigint(30000000001),
248
+ huge: TV.float(2 ** 84),
249
+ fraction: TV.float(0.1),
250
+ },
251
+ {
252
+ account_id: 2,
253
+ small: 22,
254
+ negative: -22,
255
+ negative_fraction: TV.float(-0.25),
256
+ big: TV.bigint(30000000004),
257
+ huge: TV.float(2 ** 85),
258
+ fraction: TV.float(0.2),
259
+ },
260
+ {
261
+ account_id: 3,
262
+ small: 1,
263
+ negative: -5,
264
+ negative_fraction: TV.float(-1.00000001),
265
+ big: TV.bigint(1),
266
+ huge: TV.float(0),
267
+ fraction: TV.float(1.00000001),
268
+ },
269
+ ],
270
+ entries: [
271
+ {account_id: 1, n: 1},
272
+ {account_id: 1, n: 2},
273
+ {account_id: 2, n: 3},
274
+ {account_id: 3, n: 4},
275
+ {account_id: 3, n: 5},
276
+ ],
277
+ });
278
+ const fannedOut = (aggregate: string) => `
279
+ run: accounts extend {
280
+ primary_key: account_id
281
+ join_many: entries on entries.account_id = account_id
282
+ } -> {
283
+ aggregate:
284
+ entry_count is entries.count()
285
+ ${aggregate}
286
+ }
287
+ `;
288
+
289
+ it('sums a negative 32 bit integer', async () => {
290
+ await expect(fannedOut('negative_sum is negative.sum()')).toMatchResult(
291
+ accounts,
292
+ {entry_count: 5, negative_sum: -501}
293
+ );
294
+ });
295
+
296
+ // -2.5 is half way between the whole numbers a value is split at.
297
+ it('sums a negative value with fractional digits', async () => {
298
+ await expect(
299
+ fannedOut('negative_fraction_sum is negative_fraction.sum()')
300
+ ).toMatchResult(accounts, {
301
+ entry_count: 5,
302
+ negative_fraction_sum: -3.75000001,
303
+ });
304
+ });
305
+
306
+ // 30000000001 * 10^8 is past 2^53, where a double stops holding every
307
+ // integer.
308
+ it('sums a bigint exactly', async () => {
309
+ await expect(fannedOut('big_sum is big.sum()')).toMatchResult(accounts, {
310
+ entry_count: 5,
311
+ big_sum: 60000000006,
312
+ });
313
+ });
314
+
315
+ // Powers of two, which a double and a decimal both hold exactly. The sum
316
+ // is divided back down because the Presto client cannot read a double
317
+ // that large.
318
+ it('sums values near 10^25', async () => {
319
+ await expect(
320
+ fannedOut('huge_ratio is huge.sum() / pow(2, 84)')
321
+ ).toMatchResult(accounts, {entry_count: 5, huge_ratio: 3});
322
+ });
323
+
324
+ it('keeps eight fractional digits', async () => {
325
+ await expect(fannedOut('fraction_sum is fraction.sum()')).toMatchResult(
326
+ accounts,
327
+ {entry_count: 5, fraction_sum: 1.30000001}
328
+ );
329
+ });
330
+
331
+ // 497 / 3, to ten digits past the point.
332
+ it('averages past the fractional digits of the sum', async () => {
333
+ await expect(
334
+ fannedOut('avg_digits is floor(small.avg() * 10000000000)')
335
+ ).toMatchResult(accounts, {entry_count: 5, avg_digits: 1656666666666});
336
+ });
337
+ });
338
+
339
+ // These run the SQL of the shifty sum on its own, and compare its result
340
+ // with the expected one inside the database. A result which has come
341
+ // through a query, a DOUBLE and a driver no longer shows whether every
342
+ // digit is right.
343
+ describe('the shifty sum, digit for digit', () => {
344
+ const byHash = runtime.dialect.sumDistinctByHash;
345
+ const isShifty = byHash?.form === 'shifty';
346
+ const roundsWideProducts =
347
+ byHash?.form === 'shifty' && byHash.roundsWideProducts;
348
+
349
+ // The dialect without the cast to its result type, which would round
350
+ // away the digits these tests compare.
351
+ const exact: Dialect = Object.create(runtime.dialect);
352
+ if (byHash) {
353
+ exact.sumDistinctByHash = {...byHash, resultType: undefined};
354
+ }
355
+
356
+ // A row of the source being summed: its key, and its value as the digits
357
+ // of a number, or undefined for NULL. A join which repeats a row is a key
358
+ // which appears more than once.
359
+ type Row = [key: number, value: string | undefined];
360
+
361
+ const TOP_VALUE = '9'.repeat(29) + '.99999999';
362
+
363
+ async function shiftySum(
364
+ funcName: 'SUM' | 'AVG',
365
+ valueType: string,
366
+ rows: Row[],
367
+ expected: string | undefined,
368
+ where = ''
369
+ ) {
370
+ const source = rows
371
+ .map(
372
+ ([key, value]) =>
373
+ `SELECT ${key} AS k, CAST(${
374
+ value === undefined ? 'NULL' : `'${value}'`
375
+ } AS ${valueType}) AS v`
376
+ )
377
+ .join(' UNION ALL ');
378
+ const sum = exact.sqlSumDistinct('t.k', 't.v', funcName);
379
+ const matches =
380
+ expected === undefined
381
+ ? `(${sum}) IS NULL`
382
+ : `(${sum}) = CAST('${expected}' AS DECIMAL(38,8))`;
383
+ const result = await runtime.connection.runSQL(
384
+ `SELECT ${matches} AS matches FROM (${source}) t ${where}`
385
+ );
386
+ return Object.values(result.rows[0])[0];
387
+ }
388
+
389
+ test.when(isShifty)(
390
+ 'folds the rows a join repeated, and no others',
391
+ async () => {
392
+ const rows: Row[] = [
393
+ [1, '5'],
394
+ [1, '5'],
395
+ [1, '5'],
396
+ [2, '5'],
397
+ [3, '7'],
398
+ ];
399
+ expect(await shiftySum('SUM', 'INTEGER', rows, '17')).toBe(true);
400
+ }
401
+ );
402
+
403
+ test.when(isShifty)('sums the ends of a 32 bit integer', async () => {
404
+ const rows: Row[] = [
405
+ [1, '2147483647'],
406
+ [1, '2147483647'],
407
+ [2, '-2147483648'],
408
+ [3, '474'],
409
+ ];
410
+ expect(await shiftySum('SUM', 'INTEGER', rows, '473')).toBe(true);
411
+ });
412
+
413
+ test.when(isShifty)('sums the ends of a 64 bit integer', async () => {
414
+ const rows: Row[] = [
415
+ [1, '9223372036854775807'],
416
+ [1, '9223372036854775807'],
417
+ [2, '9223372036854775807'],
418
+ [3, '-9223372036854775807'],
419
+ [4, '1'],
420
+ ];
421
+ expect(
422
+ await shiftySum('SUM', 'BIGINT', rows, '9223372036854775808')
423
+ ).toBe(true);
424
+ });
425
+
426
+ test.when(isShifty)(
427
+ 'rounds each value at its ninth fractional digit',
428
+ async () => {
429
+ const rows: Row[] = [
430
+ [1, '0.000000005'],
431
+ [2, '0.000000014'],
432
+ [3, '-0.000000015'],
433
+ [4, '0.000000004'],
434
+ [5, '0.999999995'],
435
+ [6, '-2.5'],
436
+ [6, '-2.5'],
437
+ [7, '2.5'],
438
+ [8, '0.12345678'],
439
+ ];
440
+ expect(
441
+ await shiftySum('SUM', 'DECIMAL(20,9)', rows, '1.12345678')
442
+ ).toBe(true);
443
+ }
444
+ );
445
+
446
+ test.when(isShifty)(
447
+ 'sums a double as its nearest eight digits',
448
+ async () => {
449
+ const rows: Row[] = [
450
+ [1, '0.1'],
451
+ [1, '0.1'],
452
+ [2, '0.2'],
453
+ [3, '-1.00000001'],
454
+ ];
455
+ expect(await shiftySum('SUM', 'DOUBLE', rows, '-0.70000001')).toBe(
456
+ true
457
+ );
458
+ }
459
+ );
460
+
461
+ test.when(isShifty)('sums the largest value, of either sign', async () => {
462
+ const rows: Row[] = [
463
+ [1, TOP_VALUE],
464
+ [1, TOP_VALUE],
465
+ [2, `-${TOP_VALUE}`],
466
+ [3, '0.00000001'],
467
+ ];
468
+ expect(await shiftySum('SUM', 'DECIMAL(37,8)', rows, '0.00000001')).toBe(
469
+ true
470
+ );
471
+ });
472
+
473
+ test.when(isShifty)('fails on a value of 10^29', async () => {
474
+ const rows: Row[] = [[1, '1' + '0'.repeat(29)]];
475
+ await expect(
476
+ shiftySum('SUM', 'DECIMAL(38,0)', rows, undefined)
477
+ ).rejects.toThrow();
478
+ });
479
+
480
+ // Nine of the largest value: a tenth would pass 10^38 once shifted.
481
+ test.when(isShifty && !roundsWideProducts)(
482
+ 'sums as far as 38 digits reach',
483
+ async () => {
484
+ const rows: Row[] = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(key => [
485
+ key,
486
+ TOP_VALUE,
487
+ ]);
488
+ expect(
489
+ await shiftySum(
490
+ 'SUM',
491
+ 'DECIMAL(37,8)',
492
+ rows,
493
+ '8' + '9'.repeat(29) + '.99999991'
494
+ )
495
+ ).toBe(true);
496
+ }
497
+ );
498
+
499
+ // Twenty, because Snowflake sums a little past 38 digits before it fails.
500
+ test.when(isShifty)(
501
+ 'fails when the shifted values are more than the engine can sum',
502
+ async () => {
503
+ const rows: Row[] = [];
504
+ for (let key = 1; key <= 20; key++) {
505
+ rows.push([key, TOP_VALUE]);
506
+ }
507
+ await expect(
508
+ shiftySum('SUM', 'DECIMAL(37,8)', rows, undefined)
509
+ ).rejects.toThrow();
510
+ }
511
+ );
512
+
513
+ test.when(roundsWideProducts)(
514
+ 'sums to just below 10^27 where a wide product is rounded',
515
+ async () => {
516
+ const top = '9'.repeat(27) + '.99999999';
517
+ const rows: Row[] = [
518
+ [1, top],
519
+ [1, top],
520
+ ];
521
+ expect(await shiftySum('SUM', 'DECIMAL(37,8)', rows, top)).toBe(true);
522
+ }
523
+ );
524
+
525
+ test.when(roundsWideProducts)(
526
+ 'fails on a sum of 10^27 where a wide product is rounded',
527
+ async () => {
528
+ const half = '5' + '0'.repeat(26);
529
+ const rows: Row[] = [
530
+ [1, half],
531
+ [2, half],
532
+ ];
533
+ await expect(
534
+ shiftySum('SUM', 'DECIMAL(38,0)', rows, undefined)
535
+ ).rejects.toThrow();
536
+ }
537
+ );
538
+
539
+ test.when(isShifty)('counts a NULL value as zero', async () => {
540
+ const rows: Row[] = [
541
+ [1, undefined],
542
+ [2, '3'],
543
+ [2, '3'],
544
+ ];
545
+ expect(await shiftySum('SUM', 'INTEGER', rows, '3')).toBe(true);
546
+ });
547
+
548
+ test.when(isShifty)('is NULL when there are no rows', async () => {
549
+ const rows: Row[] = [[1, '3']];
550
+ expect(
551
+ await shiftySum('SUM', 'INTEGER', rows, undefined, 'WHERE t.k < 0')
552
+ ).toBe(true);
553
+ });
554
+
555
+ test.when(isShifty)(
556
+ 'averages over the rows whose value is not NULL',
557
+ async () => {
558
+ const rows: Row[] = [
559
+ [1, '1'],
560
+ [1, '1'],
561
+ [2, '2'],
562
+ [3, undefined],
563
+ ];
564
+ expect(await shiftySum('AVG', 'INTEGER', rows, '1.5')).toBe(true);
565
+ }
566
+ );
567
+
568
+ test.when(isShifty)('keeps thirty rows apart', async () => {
569
+ const rows: Row[] = [];
570
+ for (let key = 1; key <= 30; key++) {
571
+ rows.push([key, '7'], [key, '7']);
572
+ }
573
+ expect(await shiftySum('SUM', 'INTEGER', rows, '210')).toBe(true);
574
+ });
575
+ });
576
+
208
577
  it('activates parent join when fields in leaf join are referenced', async () => {
209
578
  await expect(`
210
579
  source: flights is ${databaseName}.table('malloytest.flights') extend {
@@ -350,4 +719,329 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
350
719
  testFileSpace.deleteFile(userURL);
351
720
  }
352
721
  });
722
+
723
+ // Carol is the customer no order matches: in the joined result she has one
724
+ // row, in which the order is all NULLs.
725
+ describe('aggregate at a joined source with an unmatched row', () => {
726
+ const unmatched = extendTestModel(
727
+ mkTestModel(runtime, {
728
+ customers: [
729
+ {customer_id: 1, name: 'Alice', credit: 100},
730
+ {customer_id: 2, name: 'Bob', credit: 400},
731
+ {customer_id: 3, name: 'Carol', credit: 5000},
732
+ ],
733
+ order_rows: [
734
+ {order_id: 10, customer_id: 1, amount: 5},
735
+ {order_id: 11, customer_id: 1, amount: 7},
736
+ {order_id: 12, customer_id: 2, amount: 11},
737
+ ],
738
+ tags: [
739
+ {customer_id: 1, tag: 'a'},
740
+ {customer_id: 1, tag: 'b'},
741
+ {customer_id: 2, tag: 'c'},
742
+ ],
743
+ profiles: [
744
+ {customer_id: 1, score: 7},
745
+ {customer_id: 2, score: 9},
746
+ ],
747
+ }),
748
+ `
749
+ source: keyless_orders is order_rows extend {
750
+ measure:
751
+ order_count is count()
752
+ padded_total is sum((amount ?? 0) + 1)
753
+ tripled_avg is avg((amount ?? 0) * 3)
754
+ }
755
+ source: keyed_orders is keyless_orders extend { primary_key: order_id }
756
+ source: buyers is customers extend {
757
+ primary_key: customer_id
758
+ join_many: keyed is keyed_orders on keyed.customer_id = customer_id
759
+ join_many: keyless is keyless_orders on keyless.customer_id = customer_id
760
+ join_many: tags on tags.customer_id = customer_id
761
+ join_one: keyed_profile is profiles extend {
762
+ primary_key: customer_id
763
+ } on keyed_profile.customer_id = customer_id
764
+ join_one: keyless_profile is profiles
765
+ on keyless_profile.customer_id = customer_id
766
+ }
767
+ `
768
+ );
769
+
770
+ // A second join_many fans the orders out, which changes how every
771
+ // aggregate at the orders is written.
772
+ const shapes = [
773
+ {orders: 'keyed', fanOut: ''},
774
+ {orders: 'keyed', fanOut: 'tag_count is tags.count()'},
775
+ {orders: 'keyless', fanOut: ''},
776
+ {orders: 'keyless', fanOut: 'tag_count is tags.count()'},
777
+ ].map(s => ({...s, shape: `${s.orders}${s.fanOut ? ', fanned out' : ''}`}));
778
+
779
+ describe.each(shapes)('$shape', ({orders, fanOut}) => {
780
+ it('count, sum and avg skip the unmatched row', async () => {
781
+ await expect(`
782
+ run: buyers -> {
783
+ group_by: name
784
+ aggregate:
785
+ order_count is ${orders}.count()
786
+ big_credit_count is ${orders}.count() { where: credit > 100 }
787
+ credit_sum is ${orders}.sum(credit)
788
+ big_credit_sum is ${orders}.sum(credit) { where: credit > 100 }
789
+ credit_avg is ${orders}.avg(credit)
790
+ amount_plus_one is ${orders}.sum((${orders}.amount ?? 0) + 1)
791
+ amount_sum is ${orders}.amount.sum()
792
+ ${fanOut}
793
+ order_by: name
794
+ }
795
+ `).toMatchResult(
796
+ unmatched,
797
+ {
798
+ name: 'Alice',
799
+ order_count: 2,
800
+ big_credit_count: 0,
801
+ credit_sum: 200,
802
+ big_credit_sum: 0,
803
+ credit_avg: 100,
804
+ amount_plus_one: 14,
805
+ amount_sum: 12,
806
+ },
807
+ {
808
+ name: 'Bob',
809
+ order_count: 1,
810
+ big_credit_count: 1,
811
+ credit_sum: 400,
812
+ big_credit_sum: 400,
813
+ credit_avg: 400,
814
+ amount_plus_one: 12,
815
+ amount_sum: 11,
816
+ },
817
+ {
818
+ name: 'Carol',
819
+ order_count: 0,
820
+ big_credit_count: 0,
821
+ credit_sum: 0,
822
+ big_credit_sum: 0,
823
+ credit_avg: null,
824
+ amount_plus_one: 0,
825
+ amount_sum: 0,
826
+ }
827
+ );
828
+ });
829
+
830
+ it('a measure is the same through the join as on its own source', async () => {
831
+ const measures = ['order_count', 'padded_total', 'tripled_avg'];
832
+ const onItsOwn = await unmatched.model
833
+ .loadQuery(
834
+ `run: ${orders}_orders -> { aggregate: ${measures.join(', ')} }`
835
+ )
836
+ .run();
837
+ await expect(`
838
+ run: buyers -> {
839
+ aggregate:
840
+ ${measures.map(m => `${orders}.${m}`).join('\n')}
841
+ ${fanOut}
842
+ }
843
+ `).toMatchResult(unmatched, onItsOwn.data.toObject()[0]);
844
+ });
845
+
846
+ it('totals skip the unmatched row', async () => {
847
+ await expect(`
848
+ run: buyers -> {
849
+ aggregate:
850
+ order_count is ${orders}.count()
851
+ credit_sum is ${orders}.sum(credit)
852
+ credit_avg is ${orders}.avg(credit)
853
+ customer_count is count()
854
+ ${fanOut}
855
+ }
856
+ `).toMatchResult(unmatched, {
857
+ order_count: 3,
858
+ credit_sum: 600,
859
+ credit_avg: 200,
860
+ customer_count: 3,
861
+ });
862
+ });
863
+
864
+ const canStringAgg =
865
+ fanOut === '' ||
866
+ !['snowflake', 'mysql', 'sqlserver'].includes(databaseName);
867
+ it.when(canStringAgg)(
868
+ 'an aggregate function skips the unmatched row',
869
+ async () => {
870
+ await expect(`
871
+ run: buyers -> {
872
+ group_by: name
873
+ aggregate:
874
+ name_chars is length(${orders}.string_agg(name, ',')) ?? 0
875
+ ${fanOut}
876
+ order_by: name
877
+ }
878
+ `).toMatchResult(
879
+ unmatched,
880
+ {name: 'Alice', name_chars: 11},
881
+ {name: 'Bob', name_chars: 3},
882
+ {name: 'Carol', name_chars: 0}
883
+ );
884
+ }
885
+ );
886
+ });
887
+
888
+ describe.each(['keyed_profile', 'keyless_profile'])(
889
+ 'join_one %s',
890
+ profile => {
891
+ it('count, sum and avg skip the unmatched row', async () => {
892
+ await expect(`
893
+ run: buyers -> {
894
+ group_by: name
895
+ aggregate:
896
+ profile_count is ${profile}.count()
897
+ credit_sum is ${profile}.sum(credit)
898
+ credit_avg is ${profile}.avg(credit)
899
+ score_plus_one is ${profile}.sum((${profile}.score ?? 0) + 1)
900
+ order_by: name
901
+ }
902
+ `).toMatchResult(
903
+ unmatched,
904
+ {
905
+ name: 'Alice',
906
+ profile_count: 1,
907
+ credit_sum: 100,
908
+ credit_avg: 100,
909
+ score_plus_one: 8,
910
+ },
911
+ {
912
+ name: 'Bob',
913
+ profile_count: 1,
914
+ credit_sum: 400,
915
+ credit_avg: 400,
916
+ score_plus_one: 10,
917
+ },
918
+ {
919
+ name: 'Carol',
920
+ profile_count: 0,
921
+ credit_sum: 0,
922
+ credit_avg: null,
923
+ score_plus_one: 0,
924
+ }
925
+ );
926
+ });
927
+ }
928
+ );
929
+
930
+ // A `where:` which no unmatched row passes lets the join be written
931
+ // INNER, with the same answers.
932
+ describe.each(['keyed', 'keyless'])('a where: on the %s orders', orders => {
933
+ const aggregates = `
934
+ group_by: name
935
+ aggregate:
936
+ order_count is ${orders}.count()
937
+ amount_sum is ${orders}.amount.sum()
938
+ credit_sum is ${orders}.sum(credit)
939
+ customer_count is count()
940
+ order_by: name
941
+ `;
942
+
943
+ it('writes the join INNER', async () => {
944
+ const query = `run: buyers -> {
945
+ where: ${orders}.amount > 6
946
+ ${aggregates}
947
+ }`;
948
+ const sql = await unmatched.model.loadQuery(query).getSQL();
949
+ expect(sql).toContain('INNER JOIN');
950
+ await expect(query).toMatchResult(
951
+ unmatched,
952
+ {
953
+ name: 'Alice',
954
+ order_count: 1,
955
+ amount_sum: 7,
956
+ credit_sum: 100,
957
+ customer_count: 1,
958
+ },
959
+ {
960
+ name: 'Bob',
961
+ order_count: 1,
962
+ amount_sum: 11,
963
+ credit_sum: 400,
964
+ customer_count: 1,
965
+ }
966
+ );
967
+ });
968
+ });
969
+
970
+ it('an inner join still skips a row whose declared key is NULL', async () => {
971
+ const nullKey = extendTestModel(
972
+ mkTestModel(runtime, {
973
+ customers: [{customer_id: 1, name: 'Alice'}],
974
+ null_key_orders: [
975
+ {order_id: 10, customer_id: 1, amount: 5},
976
+ {order_id: null, customer_id: 1, amount: 7},
977
+ ],
978
+ }),
979
+ `
980
+ source: nk_buyers is customers extend {
981
+ join_many: o is null_key_orders extend {
982
+ primary_key: order_id
983
+ } on o.customer_id = customer_id
984
+ }
985
+ `
986
+ );
987
+ const query = `run: nk_buyers -> {
988
+ where: o.amount > 0
989
+ aggregate: order_count is o.count(), amount_sum is o.amount.sum()
990
+ }`;
991
+ const sql = await nullKey.model.loadQuery(query).getSQL();
992
+ expect(sql).toContain('INNER JOIN');
993
+ await expect(query).toMatchResult(nullKey, {
994
+ order_count: 1,
995
+ amount_sum: 5,
996
+ });
997
+ });
998
+
999
+ // An empty array unnests to one unmatched row.
1000
+ it.when(databaseName === 'duckdb')(
1001
+ 'an aggregate at an array skips an empty array',
1002
+ async () => {
1003
+ await expect(`
1004
+ run: ${databaseName}.sql("""
1005
+ SELECT 'Alice' as name, 100 as credit, [5, 7] as amounts
1006
+ UNION ALL SELECT 'Carol', 5000, []::INTEGER[]
1007
+ """) -> {
1008
+ group_by: name
1009
+ aggregate:
1010
+ amount_count is amounts.count()
1011
+ credit_sum is amounts.sum(credit)
1012
+ credit_avg is amounts.avg(credit)
1013
+ order_by: name
1014
+ }
1015
+ `).toMatchResult(
1016
+ unmatched,
1017
+ {name: 'Alice', amount_count: 2, credit_sum: 200, credit_avg: 100},
1018
+ {name: 'Carol', amount_count: 0, credit_sum: 0, credit_avg: null}
1019
+ );
1020
+ }
1021
+ );
1022
+
1023
+ // A right join leaves the query's own source unmatched: Carol's row has
1024
+ // no order in it.
1025
+ it('the query source skips its own unmatched row', async () => {
1026
+ await expect(`
1027
+ ##! experimental.join_types
1028
+ run: keyed_orders -> {
1029
+ extend: {
1030
+ join_one: customers right on customers.customer_id = customer_id
1031
+ }
1032
+ group_by: customers.name
1033
+ aggregate:
1034
+ order_count is count()
1035
+ ones is sum(1)
1036
+ amount_avg is avg(amount ?? 0)
1037
+ order_by: name
1038
+ }
1039
+ `).toMatchResult(
1040
+ unmatched,
1041
+ {name: 'Alice', order_count: 2, ones: 2, amount_avg: 6},
1042
+ {name: 'Bob', order_count: 1, ones: 1, amount_avg: 11},
1043
+ {name: 'Carol', order_count: 0, ones: 0, amount_avg: null}
1044
+ );
1045
+ });
1046
+ });
353
1047
  });