@qrvey/formula-lang
Version:
QFormula support for qrvey projects
111 lines • 3.58 kB
JavaScript
import { AST_PRIMITIVES, OPERATION_SCOPE } from '../constants';
import { isDateParam, isStringParam, removeQuotes } from '../utils';
import { isAnAllowedValue } from '../utils/isAnAllowedValue';
/**
* `DAYOFWEEK` Returns a number or string representative of the weekday for a given date.
*/
export const DAYOFWEEK = {
identifier: 'DAYOFWEEK',
operationScope: OPERATION_SCOPE.RAW,
functionScope: [OPERATION_SCOPE.RAW],
parameters: [
{
identifier: 'DATE',
optional: false,
expectedPrimitive: AST_PRIMITIVES.DATE,
validator: [isDateParam],
},
{
identifier: 'FORMAT',
optional: true,
expectedPrimitive: AST_PRIMITIVES.STRING,
validator: [isStringParam, isAnAllowedValue(['Day', 'D'])],
},
],
transpiler: {
elasticsearch,
snowflake,
redshift,
postgresql,
databricks,
},
primitiveResult(args) {
var _a;
const argument = args === null || args === void 0 ? void 0 : args[1];
const format = (_a = argument === null || argument === void 0 ? void 0 : argument.value) !== null && _a !== void 0 ? _a : 'D';
if (format === 'Day')
return AST_PRIMITIVES.STRING;
return AST_PRIMITIVES.NUMBER;
},
};
function elasticsearch(date, format) {
let _format = format !== null && format !== void 0 ? format : 'D';
_format = removeQuotes(_format);
switch (_format) {
case 'D':
return `((${date}.getDayOfWeek().getValue() % 7) + 1)`;
case 'Day':
return `${date}.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)`;
default:
return '';
}
}
function SQL(date, format) {
let _format = format !== null && format !== void 0 ? format : 'D';
_format = removeQuotes(_format);
switch (_format) {
case 'Day':
return `TO_CHAR(${date}, 'Day')`;
case 'D':
return `CAST(TO_CHAR(${date}, 'D') AS NUMERIC)`;
default:
return '';
}
}
function snowflake(date, format) {
let _format = format !== null && format !== void 0 ? format : 'D';
_format = removeQuotes(_format);
switch (_format) {
case 'Day':
return `DECODE(EXTRACT('dayofweek_iso', ${date}),
1, 'Monday',
2, 'Tuesday',
3, 'Wednesday',
4, 'Thursday',
5, 'Friday',
6, 'Saturday',
7, 'Sunday')`;
case 'D':
return `DAYOFWEEK(${date}) + 1`;
default:
return '';
}
}
function redshift(date, format) {
return SQL(date, format);
}
function postgresql(date, format) {
return SQL(date, format);
}
function databricks(date, format) {
let _format = format !== null && format !== void 0 ? format : 'D';
_format = removeQuotes(_format);
const dayOfWeekQueryStr = `DAYOFWEEK(${date})`;
switch (_format) {
case 'Day':
return `CASE ${dayOfWeekQueryStr}
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END`;
case 'D':
return `DATE_PART('WEEK', DATE_ADD(DAY, (1 - CAST(DATE_PART('DAYOFWEEK', ${date}) AS INTEGER)) + 1, ${date}))`;
default:
return '';
}
}
//# sourceMappingURL=dayofweek.js.map