@malloydata/malloy 0.0.138-dev240405133532 → 0.0.138

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.
@@ -51,6 +51,7 @@ export declare abstract class Dialect {
51
51
  supportsArraysInData: boolean;
52
52
  readsNestedData: boolean;
53
53
  orderByClause: OrderByClauseType;
54
+ nullMatchesFunctionSignature: boolean;
54
55
  abstract getGlobalFunctionDef(name: string): DialectFunctionOverloadDef[] | undefined;
55
56
  abstract quoteTablePath(tablePath: string): string;
56
57
  abstract sqlGroupSetTable(groupSetCount: number): string;
@@ -70,6 +70,8 @@ class Dialect {
70
70
  this.readsNestedData = true;
71
71
  // ORDER BY 1 DESC
72
72
  this.orderByClause = 'ordinal';
73
+ // null will match in a function signature
74
+ this.nullMatchesFunctionSignature = true;
73
75
  }
74
76
  sqlFinalStage(_lastStageName, _fields) {
75
77
  throw new Error('Dialect has no final Stage but called Anyway');
@@ -15,6 +15,7 @@ export interface DialectFunctionOverloadDef {
15
15
  }
16
16
  export declare function arg(name: string): Fragment;
17
17
  export declare function spread(f: Fragment): Fragment;
18
+ export declare function spreadCast(f: Fragment, _destType: string): Fragment;
18
19
  /**
19
20
  * Prefer `sql` when possible.
20
21
  */
@@ -22,7 +22,7 @@
22
22
  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
23
  */
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.overload = exports.minAnalytic = exports.minAggregate = exports.minScalar = exports.maxAnalytic = exports.maxUngroupedAggregate = exports.anyExprType = exports.maxAggregate = exports.maxScalar = exports.makeParam = exports.param = exports.params = exports.literal = exports.output = exports.constant = exports.sql = exports.sqlFragment = exports.spread = exports.arg = void 0;
25
+ exports.overload = exports.minAnalytic = exports.minAggregate = exports.minScalar = exports.maxAnalytic = exports.maxUngroupedAggregate = exports.anyExprType = exports.maxAggregate = exports.maxScalar = exports.makeParam = exports.param = exports.params = exports.literal = exports.output = exports.constant = exports.sql = exports.sqlFragment = exports.spreadCast = exports.spread = exports.arg = void 0;
26
26
  function arg(name) {
27
27
  return {
28
28
  type: 'function_parameter',
@@ -37,6 +37,15 @@ function spread(f) {
37
37
  };
38
38
  }
39
39
  exports.spread = spread;
40
+ // LTABB: this doesn't work, needs to be rewriten in terms of function parameters.
41
+ function spreadCast(f, _destType) {
42
+ return {
43
+ type: 'spread',
44
+ e: [f],
45
+ // e: ['CAST(', f, `AS ${destType})`],
46
+ };
47
+ }
48
+ exports.spreadCast = spreadCast;
40
49
  /**
41
50
  * Prefer `sql` when possible.
42
51
  */
@@ -0,0 +1,2 @@
1
+ import { DialectFunctionOverloadDef } from '../../functions/util';
2
+ export declare function fnByteLength(): DialectFunctionOverloadDef[];
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files
7
+ * (the "Software"), to deal in the Software without restriction,
8
+ * including without limitation the rights to use, copy, modify, merge,
9
+ * publish, distribute, sublicense, and/or sell copies of the Software,
10
+ * and to permit persons to whom the Software is furnished to do so,
11
+ * subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.fnByteLength = void 0;
26
+ const util_1 = require("../../functions/util");
27
+ function fnByteLength() {
28
+ return [
29
+ (0, util_1.overload)((0, util_1.minScalar)('number'), [(0, util_1.param)('value', (0, util_1.anyExprType)('string'))], (0, util_1.sql) `(LENGTH(CAST(${(0, util_1.arg)('value')} AS VARBINARY)))`),
30
+ ];
31
+ }
32
+ exports.fnByteLength = fnByteLength;
33
+ //# sourceMappingURL=byte_length.js.map
@@ -0,0 +1,2 @@
1
+ import { DialectFunctionOverloadDef } from '../../functions/util';
2
+ export declare function fnConcat(): DialectFunctionOverloadDef[];
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files
7
+ * (the "Software"), to deal in the Software without restriction,
8
+ * including without limitation the rights to use, copy, modify, merge,
9
+ * publish, distribute, sublicense, and/or sell copies of the Software,
10
+ * and to permit persons to whom the Software is furnished to do so,
11
+ * subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.fnConcat = void 0;
26
+ const util_1 = require("../../functions/util");
27
+ function fnConcat() {
28
+ return [
29
+ // TODO: in DuckDB and Postgres, nulls are treated like "",
30
+ // but in BigQuery and Snowflake, nulls propagate and the result becomes null
31
+ (0, util_1.overload)((0, util_1.minScalar)('string'), [], [{ type: 'dialect', function: 'stringLiteral', literal: '' }]),
32
+ (0, util_1.overload)((0, util_1.minScalar)('string'), [
33
+ (0, util_1.params)('values', (0, util_1.anyExprType)('string'), (0, util_1.anyExprType)('number'), (0, util_1.anyExprType)('date'), (0, util_1.anyExprType)('timestamp'), (0, util_1.anyExprType)('boolean')),
34
+ ], (0, util_1.sql) `CONCAT(${(0, util_1.spreadCast)((0, util_1.arg)('values'), 'VARCHAR')})`),
35
+ ];
36
+ }
37
+ exports.fnConcat = fnConcat;
38
+ //# sourceMappingURL=concat.js.map
@@ -0,0 +1,2 @@
1
+ import { DialectFunctionOverloadDef } from '../../functions/util';
2
+ export declare function fnIfnull(): DialectFunctionOverloadDef[];
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files
7
+ * (the "Software"), to deal in the Software without restriction,
8
+ * including without limitation the rights to use, copy, modify, merge,
9
+ * publish, distribute, sublicense, and/or sell copies of the Software,
10
+ * and to permit persons to whom the Software is furnished to do so,
11
+ * subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.fnIfnull = void 0;
26
+ const util_1 = require("../../functions/util");
27
+ const types = [
28
+ 'string',
29
+ 'number',
30
+ 'timestamp',
31
+ 'date',
32
+ 'json',
33
+ ];
34
+ function fnIfnull() {
35
+ return types.map(type => (0, util_1.overload)((0, util_1.minScalar)(type), [(0, util_1.param)('value', (0, util_1.anyExprType)(type)), (0, util_1.param)('default', (0, util_1.anyExprType)(type))],
36
+ // Postgres doesn't have an IFNULL function, so we use COALESCE, which is equivalent.
37
+ (0, util_1.sql) `COALESCE(${(0, util_1.arg)('value')}, ${(0, util_1.arg)('default')})`));
38
+ }
39
+ exports.fnIfnull = fnIfnull;
40
+ //# sourceMappingURL=ifnull.js.map
@@ -0,0 +1,2 @@
1
+ import { DialectFunctionOverloadDef } from '../../functions/util';
2
+ export declare function fnLog(): DialectFunctionOverloadDef[];
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files
7
+ * (the "Software"), to deal in the Software without restriction,
8
+ * including without limitation the rights to use, copy, modify, merge,
9
+ * publish, distribute, sublicense, and/or sell copies of the Software,
10
+ * and to permit persons to whom the Software is furnished to do so,
11
+ * subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.fnLog = void 0;
26
+ const util_1 = require("../../functions/util");
27
+ function fnLog() {
28
+ const value = (0, util_1.makeParam)('value', (0, util_1.anyExprType)('number'));
29
+ const base = (0, util_1.makeParam)('base', (0, util_1.anyExprType)('number'));
30
+ return [
31
+ (0, util_1.overload)((0, util_1.minScalar)('number'), [value.param, base.param],
32
+ // Snowflake take base first, then value
33
+ (0, util_1.sql) `LOG(${base.arg},${value.arg})`),
34
+ ];
35
+ }
36
+ exports.fnLog = fnLog;
37
+ //# sourceMappingURL=log.js.map
@@ -24,6 +24,16 @@
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.TRINO_FUNCTIONS = void 0;
26
26
  const functions_1 = require("../../functions");
27
+ const trunc_1 = require("./trunc");
28
+ const log_1 = require("./log");
29
+ const ifnull_1 = require("./ifnull");
30
+ const concat_1 = require("./concat");
31
+ const byte_length_1 = require("./byte_length");
27
32
  exports.TRINO_FUNCTIONS = functions_1.FUNCTIONS.clone();
33
+ exports.TRINO_FUNCTIONS.add('trunc', trunc_1.fnTrunc);
34
+ exports.TRINO_FUNCTIONS.add('log', log_1.fnLog);
35
+ exports.TRINO_FUNCTIONS.add('ifnull', ifnull_1.fnIfnull);
36
+ exports.TRINO_FUNCTIONS.add('byte_length', byte_length_1.fnByteLength);
37
+ exports.TRINO_FUNCTIONS.add('concat', concat_1.fnConcat);
28
38
  exports.TRINO_FUNCTIONS.seal();
29
39
  //# sourceMappingURL=trino_functions.js.map
@@ -0,0 +1,2 @@
1
+ import { DialectFunctionOverloadDef } from '../../functions/util';
2
+ export declare function fnTrunc(): DialectFunctionOverloadDef[];
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files
7
+ * (the "Software"), to deal in the Software without restriction,
8
+ * including without limitation the rights to use, copy, modify, merge,
9
+ * publish, distribute, sublicense, and/or sell copies of the Software,
10
+ * and to permit persons to whom the Software is furnished to do so,
11
+ * subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.fnTrunc = void 0;
26
+ const util_1 = require("../../functions/util");
27
+ function fnTrunc() {
28
+ const value = (0, util_1.makeParam)('value', (0, util_1.anyExprType)('number'));
29
+ const precision = (0, util_1.makeParam)('precision', (0, util_1.anyExprType)('number'));
30
+ // Trunc function doesn't exist in DuckDB, so we emulate it.
31
+ // For both overloads, we switch between CEIL and FLOOR based on the sign of the arugment
32
+ // For the overload with precision, we multiply by a power of 10 before rounding, then divide.
33
+ return [
34
+ (0, util_1.overload)((0, util_1.minScalar)('number'), [value.param], (0, util_1.sql) `CASE WHEN ${value.arg} < 0 THEN CEIL(${value.arg}) ELSE FLOOR(${value.arg}) END`),
35
+ (0, util_1.overload)((0, util_1.minScalar)('number'), [value.param, precision.param], (0, util_1.sql) `CASE WHEN ${value.arg} < 0 THEN CEIL(${value.arg} * POW(10, ${precision.arg})) / POW(10, ${precision.arg}) ELSE FLOOR(${value.arg} * POW(10, ${precision.arg})) / POW(10, ${precision.arg}) END`),
36
+ ];
37
+ }
38
+ exports.fnTrunc = fnTrunc;
39
+ //# sourceMappingURL=trunc.js.map
@@ -1,4 +1,4 @@
1
- import { Expr, ExtractUnit, Sampling, TimeValue, TimestampUnit, TypecastFragment, FieldAtomicTypeDef, DialectFragment } from '../../model/malloy_types';
1
+ import { Expr, ExtractUnit, Sampling, TimeValue, TimestampUnit, TypecastFragment, FieldAtomicTypeDef, DialectFragment, DateUnit, TimeFieldType } from '../../model/malloy_types';
2
2
  import { DialectFunctionOverloadDef } from '../functions';
3
3
  import { Dialect, DialectFieldList, OrderByClauseType, QueryInfo } from '../dialect';
4
4
  export declare class TrinoDialect extends Dialect {
@@ -22,6 +22,7 @@ export declare class TrinoDialect extends Dialect {
22
22
  supportsNesting: boolean;
23
23
  cantPartitionWindowFunctionsOnExpressions: boolean;
24
24
  orderByClause: OrderByClauseType;
25
+ nullMatchesFunctionSignature: boolean;
25
26
  quoteTablePath(tablePath: string): string;
26
27
  sqlGroupSetTable(groupSetCount: number): string;
27
28
  dialectExpr(qi: QueryInfo, df: DialectFragment): Expr;
@@ -44,12 +45,11 @@ export declare class TrinoDialect extends Dialect {
44
45
  sqlMaybeQuoteIdentifier(identifier: string): string;
45
46
  sqlNow(): Expr;
46
47
  sqlTrunc(qi: QueryInfo, sqlTime: TimeValue, units: TimestampUnit): Expr;
47
- sqlExtract(qi: QueryInfo, expr: TimeValue, units: ExtractUnit): Expr;
48
- sqlAlterTime(op: '+' | '-', expr: TimeValue, n: Expr, timeframe: TimestampUnit): Expr;
49
- ignoreInProject(fieldName: string): boolean;
48
+ sqlExtract(qi: QueryInfo, from: TimeValue, units: ExtractUnit): Expr;
49
+ sqlAlterTime(op: '+' | '-', expr: TimeValue, n: Expr, timeframe: DateUnit): Expr;
50
50
  sqlCast(qi: QueryInfo, cast: TypecastFragment): Expr;
51
51
  sqlRegexpMatch(expr: Expr, regexp: Expr): Expr;
52
- sqlLiteralTime(qi: QueryInfo, timeString: string, type: 'date' | 'timestamp', timezone: string | undefined): string;
52
+ sqlLiteralTime(qi: QueryInfo, timeString: string, type: TimeFieldType, timezone: string | undefined): string;
53
53
  sqlMeasureTime(from: TimeValue, to: TimeValue, units: string): Expr;
54
54
  sqlSampleTable(tableSQL: string, sample: Sampling | undefined): string;
55
55
  sqlLiteralString(literal: string): string;
@@ -38,12 +38,9 @@ function timestampMeasureable(units) {
38
38
  'day',
39
39
  ].includes(units);
40
40
  }
41
- function dateMeasureable(units) {
42
- return ['day', 'week', 'month', 'quarter', 'year'].includes(units);
43
- }
44
- const extractMap = {
45
- 'day_of_week': 'dayofweek',
46
- 'day_of_year': 'dayofyear',
41
+ const pgExtractionMap = {
42
+ 'day_of_week': 'dow',
43
+ 'day_of_year': 'doy',
47
44
  };
48
45
  /**
49
46
  * Return a non UTC timezone, if one was specificed.
@@ -79,6 +76,7 @@ class TrinoDialect extends dialect_1.Dialect {
79
76
  this.supportsNesting = true;
80
77
  this.cantPartitionWindowFunctionsOnExpressions = false;
81
78
  this.orderByClause = 'output_name';
79
+ this.nullMatchesFunctionSignature = false;
82
80
  // TODO(figutierrez): update.
83
81
  this.keywords = `
84
82
  ALL
@@ -309,57 +307,66 @@ ${(0, utils_1.indent)(sql)}
309
307
  return '"' + identifier + '"';
310
308
  }
311
309
  sqlNow() {
312
- return (0, malloy_types_1.mkExpr) `CURRENT_TIMESTAMP()`;
310
+ return (0, malloy_types_1.mkExpr) `LOCALTIMESTAMP`;
313
311
  }
314
312
  sqlTrunc(qi, sqlTime, units) {
315
- const tz = qtz(qi);
316
- const tzAdd = tz ? `, "${tz}"` : '';
317
- if (sqlTime.valueType === 'date') {
318
- if (dateMeasureable(units)) {
319
- return (0, malloy_types_1.mkExpr) `DATE_TRUNC(${sqlTime.value},${units})`;
313
+ // adjusting for monday/sunday weeks
314
+ const week = units === 'week';
315
+ const truncThis = week
316
+ ? (0, malloy_types_1.mkExpr) `DATE_ADD('day', 1, ${sqlTime.value})`
317
+ : sqlTime.value;
318
+ if (sqlTime.valueType === 'timestamp') {
319
+ const tz = qtz(qi);
320
+ if (tz) {
321
+ const civilSource = (0, malloy_types_1.mkExpr) `CAST(${truncThis} AS TIMESTAMPTZ AT TIME ZONE '${tz}')`;
322
+ let civilTrunc = (0, malloy_types_1.mkExpr) `DATE_TRUNC('${units}', ${civilSource})`;
323
+ // MTOY todo ... only need to do this if this is a date ...
324
+ civilTrunc = (0, malloy_types_1.mkExpr) `CAST(${civilTrunc}, TIMESTAMP)`;
325
+ const truncTsTz = (0, malloy_types_1.mkExpr) `${civilTrunc} AT TIME ZONE '${tz}'`;
326
+ return (0, malloy_types_1.mkExpr) `CAST((${truncTsTz}),TIMESTAMP)`;
320
327
  }
321
- return (0, malloy_types_1.mkExpr) `TIMESTAMP(${sqlTime.value}${tzAdd})`;
322
328
  }
323
- return (0, malloy_types_1.mkExpr) `TIMESTAMP_TRUNC(${sqlTime.value},${units}${tzAdd})`;
324
- }
325
- sqlExtract(qi, expr, units) {
326
- const extractTo = extractMap[units] || units;
327
- const tz = expr.valueType === 'timestamp' && qtz(qi);
328
- const tzAdd = tz ? ` AT TIME ZONE '${tz}'` : '';
329
- return (0, malloy_types_1.mkExpr) `EXTRACT(${extractTo} FROM ${expr.value}${tzAdd})`;
329
+ let result = (0, malloy_types_1.mkExpr) `DATE_TRUNC('${units}', ${truncThis})`;
330
+ if (week) {
331
+ result = (0, malloy_types_1.mkExpr) `DATE_ADD('day',-1, ${result})`;
332
+ }
333
+ return result;
334
+ }
335
+ sqlExtract(qi, from, units) {
336
+ const pgUnits = pgExtractionMap[units] || units;
337
+ let extractFrom = from.value;
338
+ if (from.valueType === 'timestamp') {
339
+ const tz = qtz(qi);
340
+ if (tz) {
341
+ extractFrom = (0, malloy_types_1.mkExpr) `CAST(${extractFrom}, TIMESTAMPTZ AT TIME ZONE '${tz}')`;
342
+ }
343
+ }
344
+ const extracted = (0, malloy_types_1.mkExpr) `EXTRACT(${pgUnits} FROM ${extractFrom})`;
345
+ return units === 'day_of_week' ? (0, malloy_types_1.mkExpr) `(${extracted}+1)` : extracted;
330
346
  }
331
347
  sqlAlterTime(op, expr, n, timeframe) {
332
- let theTime = expr.value;
333
- let computeType = expr.valueType;
334
- if (timeframe !== 'day' && timestampMeasureable(timeframe)) {
335
- // The units must be done in timestamp, no matter the input type
336
- computeType = 'timestamp';
337
- if (expr.valueType !== 'timestamp') {
338
- theTime = (0, malloy_types_1.mkExpr) `TIMESTAMP(${theTime})`;
339
- }
348
+ if (timeframe === 'quarter') {
349
+ timeframe = 'month';
350
+ n = (0, malloy_types_1.mkExpr) `${n}*3`;
340
351
  }
341
- else if (expr.valueType === 'timestamp') {
342
- theTime = (0, malloy_types_1.mkExpr) `DATETIME(${theTime})`;
343
- computeType = 'datetime';
352
+ if (timeframe === 'week') {
353
+ timeframe = 'day';
354
+ n = (0, malloy_types_1.mkExpr) `${n}*7`;
344
355
  }
345
- const funcName = computeType.toUpperCase() + (op === '+' ? '_ADD' : '_SUB');
346
- const newTime = (0, malloy_types_1.mkExpr) `${funcName}(${theTime}, INTERVAL ${n} ${timeframe})`;
347
- if (computeType === expr.valueType) {
348
- return newTime;
356
+ if (op === '-') {
357
+ n = (0, malloy_types_1.mkExpr) `(${n})*-1`;
349
358
  }
350
- return (0, malloy_types_1.mkExpr) `${expr.valueType.toUpperCase()}(${newTime})`;
351
- }
352
- ignoreInProject(fieldName) {
353
- return fieldName === '_PARTITIONTIME';
359
+ return (0, malloy_types_1.mkExpr) `DATE_ADD('${timeframe}', ${n}, ${expr.value})`;
354
360
  }
355
361
  sqlCast(qi, cast) {
356
362
  const op = `${cast.srcType}::${cast.dstType}`;
357
363
  const tz = qtz(qi);
358
364
  if (op === 'timestamp::date' && tz) {
359
- return (0, malloy_types_1.mkExpr) `DATE(${cast.expr},'${tz}')`;
365
+ const tstz = (0, malloy_types_1.mkExpr) `CAST(${cast.expr} as TIMESTAMPTZ)`;
366
+ return (0, malloy_types_1.mkExpr) `CAST((${tstz}) AT TIME ZONE '${tz}' AS DATE)`;
360
367
  }
361
- if (op === 'date::timestamp' && tz) {
362
- return (0, malloy_types_1.mkExpr) `TIMESTAMP(${cast.expr}, '${tz}')`;
368
+ else if (op === 'date::timestamp' && tz) {
369
+ return (0, malloy_types_1.mkExpr) `CAST(CAST(${cast.expr}), TIMESTAMP AT TIME ZONE '${tz}') AS TIMESTAMP)`;
363
370
  }
364
371
  if (cast.srcType !== cast.dstType) {
365
372
  const dstType = typeof cast.dstType === 'string'
@@ -375,19 +382,13 @@ ${(0, utils_1.indent)(sql)}
375
382
  }
376
383
  sqlLiteralTime(qi, timeString, type, timezone) {
377
384
  if (type === 'date') {
378
- return `DATE('${timeString}')`;
385
+ return `DATE '${timeString}'`;
379
386
  }
380
- else if (type === 'timestamp') {
381
- let timestampArgs = `'${timeString}'`;
382
- const tz = timezone || qtz(qi);
383
- if (tz && tz !== 'UTC') {
384
- timestampArgs += `,'${tz}'`;
385
- }
386
- return `TIMESTAMP(${timestampArgs})`;
387
- }
388
- else {
389
- throw new Error(`Unsupported Literal time format ${type}`);
387
+ const tz = timezone || qtz(qi);
388
+ if (tz) {
389
+ return `TIMESTAMPTZ '${timeString} ${tz}'::TIMESTAMP`;
390
390
  }
391
+ return `TIMESTAMP '${timeString}'`;
391
392
  }
392
393
  sqlMeasureTime(from, to, units) {
393
394
  const measureMap = {
@@ -410,12 +411,12 @@ ${(0, utils_1.indent)(sql)}
410
411
  throw new Error("Can't measure difference between different types");
411
412
  }
412
413
  if (from.valueType === 'date') {
413
- lVal = (0, malloy_types_1.mkExpr) `TIMESTAMP(${lVal})`;
414
- rVal = (0, malloy_types_1.mkExpr) `TIMESTAMP(${rVal})`;
414
+ lVal = (0, malloy_types_1.mkExpr) `CAST(${lVal} AS TIMESTAMP)`;
415
+ rVal = (0, malloy_types_1.mkExpr) `CAST(${rVal} AS TIMESTAMP)`;
415
416
  }
416
- let measured = (0, malloy_types_1.mkExpr) `TIMESTAMP_DIFF(${rVal},${lVal},${measureIn})`;
417
+ let measured = (0, malloy_types_1.mkExpr) `DATE_DIFF('${measureIn}',${lVal},${rVal})`;
417
418
  if (ratio !== 1) {
418
- measured = (0, malloy_types_1.mkExpr) `FLOOR(${measured}/${ratio.toString()}.0)`;
419
+ measured = (0, malloy_types_1.mkExpr) `FLOOR(CAST(${measured} AS DOUBLE)/${ratio.toString()}.0)`;
419
420
  }
420
421
  return measured;
421
422
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/malloy",
3
- "version": "0.0.138-dev240405133532",
3
+ "version": "0.0.138",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": "./dist/index.js",