@malloydata/malloy-tests 0.0.438 → 0.0.440

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.
package/package.json CHANGED
@@ -20,28 +20,28 @@
20
20
  "malloyc": "ts-node ../scripts/malloy-to-json"
21
21
  },
22
22
  "dependencies": {
23
- "@malloydata/db-bigquery": "0.0.438",
24
- "@malloydata/db-duckdb": "0.0.438",
25
- "@malloydata/db-postgres": "0.0.438",
26
- "@malloydata/db-snowflake": "0.0.438",
27
- "@malloydata/db-sqlserver": "0.0.438",
28
- "@malloydata/db-trino": "0.0.438",
29
- "@malloydata/malloy": "0.0.438",
30
- "@malloydata/malloy-tag": "0.0.438",
31
- "@malloydata/render": "0.0.438",
32
- "@malloydata/render-validator": "0.0.438",
23
+ "@malloydata/db-bigquery": "0.0.440",
24
+ "@malloydata/db-duckdb": "0.0.440",
25
+ "@malloydata/db-postgres": "0.0.440",
26
+ "@malloydata/db-snowflake": "0.0.440",
27
+ "@malloydata/db-sqlserver": "0.0.440",
28
+ "@malloydata/db-trino": "0.0.440",
29
+ "@malloydata/malloy": "0.0.440",
30
+ "@malloydata/malloy-tag": "0.0.440",
31
+ "@malloydata/render": "0.0.440",
32
+ "@malloydata/render-validator": "0.0.440",
33
33
  "events": "^3.3.0",
34
34
  "jsdom": "^22.1.0",
35
35
  "luxon": "^3.7.2",
36
36
  "madge": "^8.0.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@jest/globals": "^29.4.3",
39
+ "@jest/globals": "^30.5.2",
40
40
  "@types/jsdom": "^21.1.1",
41
- "@types/luxon": "^3.7.2"
41
+ "@types/luxon": "^3.7.6"
42
42
  },
43
43
  "overrides": {
44
44
  "typescript": "^6.0.3"
45
45
  },
46
- "version": "0.0.438"
46
+ "version": "0.0.440"
47
47
  }
@@ -46,6 +46,31 @@ describe('givens — runtime supply path (Stage 4)', () => {
46
46
  expect(result.data.toObject().length).toBe(1);
47
47
  });
48
48
 
49
+ test('a supplied negative number keeps its sign beside a minus', async () => {
50
+ const model = runtime.loadModel(`
51
+ ##! experimental.givens
52
+ given: NEG :: number
53
+ query: q is duckdb.sql("SELECT 2 as c") -> { select: x is c - $NEG }
54
+ `);
55
+ const result = await model.loadQueryByName('q').run({givens: {NEG: -5}});
56
+ expect(result.data.path(0, 'x').value).toBe(7);
57
+ });
58
+
59
+ test('membership in a supplied array is one term of a comparison', async () => {
60
+ const model = runtime.loadModel(`
61
+ ##! experimental.givens
62
+ given: ARR :: number[]
63
+ query: q is duckdb.sql("SELECT 2 as c, true as t") -> {
64
+ select: x is c in $ARR = t
65
+ }
66
+ `);
67
+ const q = model.loadQueryByName('q');
68
+ const sql = await q.getSQL({givens: {ARR: [2, -2]}});
69
+ expect(sql).toMatch(/\(base\."c" IN \(2,-2\)\)=base\."t"/);
70
+ const result = await q.run({givens: {ARR: [2, -2]}});
71
+ expect(result.data.path(0, 'x').value).toBe(true);
72
+ });
73
+
49
74
  test('number given drives a where comparison', async () => {
50
75
  const model = runtime.loadModel(`
51
76
  ##! experimental.givens
@@ -211,10 +236,9 @@ describe('givens — runtime supply path (Stage 4)', () => {
211
236
  expect(rSp.data.path(0, 'ct').value).toBe(1);
212
237
  });
213
238
 
214
- test('date-literal default morphs to timestamp and filters flights.dep_time', async () => {
215
- // Exercises the morphic default path in define-given: the declared
216
- // type is `timestamp`, the default `@2003-01-01` is a date literal,
217
- // and the AST converts it to a timestamp expression so the default
239
+ test('date-literal default is a timestamp and filters flights.dep_time', async () => {
240
+ // The declared type is `timestamp` and the default `@2003-01-01` is a
241
+ // date literal, so the default is the literal's timestamp reading and
218
242
  // can drive a timestamp-column comparison at runtime.
219
243
  const model = runtime.loadModel(`
220
244
  ##! experimental.givens
@@ -436,7 +436,7 @@ describe.each(runtimes.runtimeList)('array queries %s', (db, runtime) => {
436
436
  }
437
437
  `);
438
438
  expect(sql).toMatch(/LIST_SUM/);
439
- expect(sql).toMatch(/__by_fac_type_element_0 ->/);
439
+ expect(sql).toMatch(/lambda __by_fac_type_element_0:/);
440
440
  });
441
441
 
442
442
  test.when(duckdb)('empty and null arrays', async () => {
@@ -404,6 +404,33 @@ describe.each(runtimes.runtimeList)(
404
404
  -> { select: odd is nums.odds.each }
405
405
  `).toEqualResult(testModel, [{odd: 1}, {odd: 3}]);
406
406
  });
407
+ // Both rows hold the same array, so the aggregates are only right if
408
+ // each element's key includes the row the record belongs to.
409
+ const twoRows = `${conName}.sql("""
410
+ SELECT 1 AS ${quote('id')} UNION ALL SELECT 2
411
+ """)`;
412
+ test('aggregate through array in a record column', async () => {
413
+ await expect(`
414
+ run: ${twoRows} -> { select: id, rec is {xs is [1, 2]} }
415
+ -> { aggregate: total is rec.xs.each.sum(), n is rec.xs.count() }
416
+ `).toMatchResult(testModel, {total: 6, n: 4});
417
+ });
418
+ test('aggregate through array in a record dimension', async () => {
419
+ await expect(`
420
+ run: ${twoRows} extend { dimension: rec is {xs is [1, 2]} }
421
+ -> { aggregate: total is rec.xs.each.sum(), n is rec.xs.count() }
422
+ `).toMatchResult(testModel, {total: 6, n: 4});
423
+ });
424
+ test('aggregate through array in a record in a record', async () => {
425
+ await expect(`
426
+ run: ${twoRows} -> { select: id, rec is {mid is {xs is [1, 2]}} }
427
+ -> {
428
+ aggregate:
429
+ total is rec.mid.xs.each.sum()
430
+ n is rec.mid.xs.count()
431
+ }
432
+ `).toMatchResult(testModel, {total: 6, n: 4});
433
+ });
407
434
  const abc = "rec is {a is 'a', bc is {b is 'b', c is 'c'}}";
408
435
  test('record with a record property', async () => {
409
436
  await expect(`
@@ -967,6 +967,121 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
967
967
  }
968
968
  );
969
969
  });
970
+
971
+ // An array the filtered join's `where:` reads is unnested inside its
972
+ // subquery; read from outside, it answers as the filtered source does on
973
+ // its own.
974
+ describe('an array the filtered join reads, read outside it', () => {
975
+ // Ten values, as the result matchers read at most ten rows
976
+ const countdown = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
977
+ const readArrays = `
978
+ source: sf is ${databaseName}.table('malloytest.state_facts')
979
+ source: by_state is ${databaseName}.table('malloytest.airports') -> {
980
+ group_by: state
981
+ nest: types is { group_by: fac_type; aggregate: c is count() }
982
+ }
983
+ source: big is by_state extend { where: types.c > 100 }
984
+ source: nums is sf -> { select: state, top is [1, 2, 3] }
985
+ source: big_nums is nums extend { where: top.each > 1 }
986
+ source: long is sf -> { select: state, la is [${countdown.join(', ')}] }
987
+ source: long_f is long extend { where: la.each > 0 }
988
+ source: zero is sf extend {
989
+ join_one: b is big on b.state = state
990
+ join_one: bn is big_nums on bn.state = state
991
+ join_one: lf is long_f on lf.state = state
992
+ }
993
+ `;
994
+
995
+ test.when(
996
+ runtime.dialect.supportsComplexFilteredSources &&
997
+ runtime.dialect.requiresExplicitUnnestOrdering
998
+ )('array of values keeps its order', async () => {
999
+ await expect(`
1000
+ ${readArrays}
1001
+ run: zero -> {
1002
+ where: state = 'AL'
1003
+ select: state, e is lf.la.each
1004
+ order_by: state
1005
+ }
1006
+ `).toEqualResult(
1007
+ testModel,
1008
+ countdown.filter(n => n > 0).map(e => ({state: 'AL', e}))
1009
+ );
1010
+ });
1011
+
1012
+ test.when(runtime.dialect.supportsComplexFilteredSources)(
1013
+ 'array of records aggregated',
1014
+ async () => {
1015
+ await expect(`
1016
+ ${readArrays}
1017
+ run: zero -> {
1018
+ where: state ~ 'A%'
1019
+ group_by: state
1020
+ aggregate:
1021
+ rows is b.count()
1022
+ n is b.types.count()
1023
+ total is b.types.c.sum()
1024
+ order_by: state
1025
+ limit: 2
1026
+ }
1027
+ `).toMatchResult(
1028
+ testModel,
1029
+ {state: 'AK', rows: 1, n: 2, total: 578},
1030
+ {state: 'AL', rows: 1, n: 1, total: 180}
1031
+ );
1032
+ }
1033
+ );
1034
+
1035
+ test.when(runtime.dialect.supportsComplexFilteredSources)(
1036
+ 'array of records selected',
1037
+ async () => {
1038
+ await expect(`
1039
+ ${readArrays}
1040
+ run: zero -> {
1041
+ where: state = 'AK'
1042
+ select: state, fac_type is b.types.fac_type, c is b.types.c
1043
+ order_by: fac_type
1044
+ }
1045
+ `).toEqualResult(testModel, [
1046
+ {state: 'AK', fac_type: 'AIRPORT', c: 474},
1047
+ {state: 'AK', fac_type: 'SEAPLANE BASE', c: 104},
1048
+ ]);
1049
+ }
1050
+ );
1051
+
1052
+ test.when(runtime.dialect.supportsComplexFilteredSources)(
1053
+ 'array of values aggregated',
1054
+ async () => {
1055
+ await expect(`
1056
+ ${readArrays}
1057
+ run: zero -> {
1058
+ where: state = 'AL'
1059
+ aggregate:
1060
+ rows is bn.count()
1061
+ n is bn.top.count()
1062
+ total is bn.top.each.sum()
1063
+ }
1064
+ `).toMatchResult(testModel, {rows: 1, n: 2, total: 5});
1065
+ }
1066
+ );
1067
+
1068
+ test.when(runtime.dialect.supportsComplexFilteredSources)(
1069
+ 'array of values selected',
1070
+ async () => {
1071
+ await expect(`
1072
+ ${readArrays}
1073
+ run: zero -> {
1074
+ where: state = 'AL'
1075
+ select: state, e is bn.top.each
1076
+ order_by: e
1077
+ }
1078
+ `).toEqualResult(testModel, [
1079
+ {state: 'AL', e: 2},
1080
+ {state: 'AL', e: 3},
1081
+ ]);
1082
+ }
1083
+ );
1084
+ });
970
1085
  });
971
1086
 
972
1087
  test('joined filtered explores with NO dependencies', async () => {
@@ -1176,6 +1291,114 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
1176
1291
  no_paren: 'no',
1177
1292
  });
1178
1293
  });
1294
+
1295
+ describe('an operand with one operand of its own keeps its grouping', () => {
1296
+ const tm = mkTestModel(runtime, {nums: [{a: 7, c: 2}]});
1297
+
1298
+ test('negation beside a minus', async () => {
1299
+ await expect(`run: nums -> {
1300
+ select:
1301
+ minus_paren_neg is c - (-a)
1302
+ minus_neg is c - -a
1303
+ neg_paren_neg is -(-a)
1304
+ neg_neg is - -a
1305
+ }`).toMatchResult(tm, {
1306
+ minus_paren_neg: 9,
1307
+ minus_neg: 9,
1308
+ neg_paren_neg: 7,
1309
+ neg_neg: 7,
1310
+ });
1311
+ });
1312
+
1313
+ test.when(runtime.dialect.booleanType !== 'none')(
1314
+ 'a null check on the right of =',
1315
+ async () => {
1316
+ await expect(`run: nums -> {
1317
+ select:
1318
+ is_null is pick 'yes' when (a = 1) = (c is null) else 'no'
1319
+ is_not_null is pick 'yes' when (a = 1) = (c is not null) else 'no'
1320
+ }`).toMatchResult(tm, {is_null: 'yes', is_not_null: 'no'});
1321
+ }
1322
+ );
1323
+ });
1324
+
1325
+ describe('an expression written into other SQL keeps its grouping', () => {
1326
+ const tm = mkTestModel(runtime, {nums: [{a: 7, c: 2}]});
1327
+
1328
+ test('as the argument of a function', async () => {
1329
+ await expect(`run: nums -> {
1330
+ select:
1331
+ paren_divisor is div(10, (c + 3))
1332
+ bare_divisor is div(10, c + 3)
1333
+ dividend is div(a - 1, c)
1334
+ }`).toMatchResult(tm, {paren_divisor: 2, bare_divisor: 2, dividend: 3});
1335
+ });
1336
+
1337
+ test('as a computed field of a nested select', async () => {
1338
+ await expect(`run: nums -> {
1339
+ group_by: a
1340
+ nest: n is { select: m is a % c }
1341
+ }`).toMatchResult(tm, {a: 7, n: [{m: 1}]});
1342
+ });
1343
+
1344
+ test('as the value of a parameter', async () => {
1345
+ await expect(`
1346
+ ##! experimental.parameters
1347
+ source: nums_p(neg :: number is -5, diff :: number is 1 - 2) is nums extend {
1348
+ dimension:
1349
+ minus_neg is c - neg
1350
+ times_diff is c * diff
1351
+ }
1352
+ run: nums_p -> { select: minus_neg, times_diff }
1353
+ `).toMatchResult(tm, {minus_neg: 7, times_diff: -2});
1354
+ });
1355
+
1356
+ test('as the value of a given', async () => {
1357
+ await expect(`
1358
+ ##! experimental.givens
1359
+ given: NEG :: number is -5
1360
+ given: DIFF :: number is 1 - 2
1361
+ run: nums -> {
1362
+ select:
1363
+ minus_neg is c - $NEG
1364
+ times_diff is c * $DIFF
1365
+ }
1366
+ `).toMatchResult(tm, {minus_neg: 7, times_diff: -2});
1367
+ });
1368
+ });
1369
+
1370
+ test('a condition of a join is a single term beside the others', async () => {
1371
+ // Flags are numbers so that the same rows mean the same on every dialect
1372
+ const tm = mkTestModel(runtime, {
1373
+ rws: [
1374
+ {k: 1, ai: 1, bi: 9, fa: 0, fb: 0},
1375
+ {k: 2, ai: 2, bi: 9, fa: 1, fb: 0},
1376
+ ],
1377
+ });
1378
+ await expect(`
1379
+ source: only_a is rws extend { where: fa = 1 }
1380
+ source: two_filters is rws extend { where: (fa = 1 or fb = 1), k > 5 }
1381
+ run: rws extend {
1382
+ join_one: by_or is only_a on (by_or.k = ai or by_or.k = bi)
1383
+ join_one: filtered is two_filters on filtered.k = ai
1384
+ } -> {
1385
+ aggregate:
1386
+ or_matched is by_or.count()
1387
+ filter_matched is filtered.count()
1388
+ }
1389
+ `).toMatchResult(tm, {or_matched: 1, filter_matched: 0});
1390
+ });
1391
+
1392
+ test('a symmetric average is a single term of a larger expression', async () => {
1393
+ await expect(`
1394
+ run: ${databaseName}.table('malloytest.aircraft') extend {
1395
+ join_one: aircraft_models is ${databaseName}.table('malloytest.aircraft_models')
1396
+ on aircraft_model_code = aircraft_models.aircraft_model_code
1397
+ } -> {
1398
+ aggregate: back_to_100 is
1399
+ round(100 / aircraft_models.seats.avg() * aircraft_models.seats.avg())
1400
+ }`).toMatchResult(testModel, {back_to_100: 100});
1401
+ });
1179
1402
  });
1180
1403
 
1181
1404
  afterAll(async () => {
@@ -75,7 +75,7 @@ expressionModels.forEach((x, databaseName) => {
75
75
  const result = await run();
76
76
  expect(result.data.path(0, 'f').value).toBe(expectedSuccess);
77
77
  } else {
78
- expect(run).rejects.toThrowError(expected.error);
78
+ expect(run).rejects.toThrow(expected.error);
79
79
  }
80
80
  };
81
81
 
@@ -3,6 +3,7 @@
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';
@@ -210,6 +211,369 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
210
211
  }
211
212
  );
212
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
+
213
577
  it('activates parent join when fields in leaf join are referenced', async () => {
214
578
  await expect(`
215
579
  source: flights is ${databaseName}.table('malloytest.flights') extend {
@@ -359,20 +723,17 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
359
723
  // Carol is the customer no order matches: in the joined result she has one
360
724
  // row, in which the order is all NULLs.
361
725
  describe('aggregate at a joined source with an unmatched row', () => {
362
- // float, because Databricks overflows on the fanned-out sum of a 32 bit
363
- // integer column.
364
- const num = TV.float;
365
726
  const unmatched = extendTestModel(
366
727
  mkTestModel(runtime, {
367
728
  customers: [
368
- {customer_id: 1, name: 'Alice', credit: num(100)},
369
- {customer_id: 2, name: 'Bob', credit: num(400)},
370
- {customer_id: 3, name: 'Carol', credit: num(5000)},
729
+ {customer_id: 1, name: 'Alice', credit: 100},
730
+ {customer_id: 2, name: 'Bob', credit: 400},
731
+ {customer_id: 3, name: 'Carol', credit: 5000},
371
732
  ],
372
733
  order_rows: [
373
- {order_id: 10, customer_id: 1, amount: num(5)},
374
- {order_id: 11, customer_id: 1, amount: num(7)},
375
- {order_id: 12, customer_id: 2, amount: num(11)},
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},
376
737
  ],
377
738
  tags: [
378
739
  {customer_id: 1, tag: 'a'},
@@ -380,8 +741,8 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
380
741
  {customer_id: 2, tag: 'c'},
381
742
  ],
382
743
  profiles: [
383
- {customer_id: 1, score: num(7)},
384
- {customer_id: 2, score: num(9)},
744
+ {customer_id: 1, score: 7},
745
+ {customer_id: 2, score: 9},
385
746
  ],
386
747
  }),
387
748
  `
@@ -566,6 +927,75 @@ describe.each(runtimes.runtimeList)('%s', (databaseName, runtime) => {
566
927
  }
567
928
  );
568
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
+
569
999
  // An empty array unnests to one unmatched row.
570
1000
  it.when(databaseName === 'duckdb')(
571
1001
  'an aggregate at an array skips an empty array',
@@ -363,6 +363,23 @@ describe.each(runtimes.runtimeList)('%s date and time', (dbName, runtime) => {
363
363
  lt_digits: 'yes',
364
364
  });
365
365
  });
366
+
367
+ test.when(timestamptz)('measure to and from a timestamp', async () => {
368
+ await expect(`
369
+ run: tzdata -> {
370
+ select:
371
+ to_tstz is minutes(same_digits to tstz)
372
+ from_tstz is minutes(tstz to same_digits)
373
+ to_zoned is minutes(same_digits to @2020-01-30 20:00:00[America/Mexico_City])
374
+ from_zoned is minutes(@2020-01-30 20:00:00[America/Mexico_City] to same_digits)
375
+ }
376
+ `).toMatchResult(tzModel(), {
377
+ to_tstz: 360,
378
+ from_tstz: -360,
379
+ to_zoned: 360,
380
+ from_zoned: -360,
381
+ });
382
+ });
366
383
  });
367
384
 
368
385
  describe('date truncation', () => {
@@ -1012,6 +1029,17 @@ describe.each(runtimes.runtimeList)('%s: query tz', (dbName, runtime) => {
1012
1029
  back: 'yes',
1013
1030
  });
1014
1031
  });
1032
+
1033
+ test.when(timestamptz)('a range starting at it', async () => {
1034
+ await expect(`
1035
+ run: tzdata -> {
1036
+ timezone: '${zone}'
1037
+ select:
1038
+ before_end is pick 'in' when same_instant + 23 hours ? tstz for 1 day else 'out'
1039
+ after_end is pick 'in' when same_instant + 25 hours ? tstz for 1 day else 'out'
1040
+ }
1041
+ `).toMatchResult(tzModel(), {before_end: 'in', after_end: 'out'});
1042
+ });
1015
1043
  });
1016
1044
 
1017
1045
  // Test for timezone rendering issue with nested queries
@@ -1,4 +1,4 @@
1
- // Jest Snapshot v1, https://goo.gl/fbAQLP
1
+ // Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2
2
 
3
3
  exports[`rendering results bar chart renderer date with timezone rendered correctly 1`] = `
4
4
  <div>