UNPKG

@qrvey/formula-lang

Version:

QFormula support for qrvey projects

79 lines 2.6 kB
import { AST_PRIMITIVES, ELASTICSEARCH_SCRIPT_NAMES, OPERATION_SCOPE, } from '../constants'; import { isNumberParam, isStringParam } from '../utils'; import { greaterThanOrEqualToReference } from '../utils/greaterThanOrEqualToReference'; import { isInteger } from '../utils/isInteger'; /** * `MID` Returns a segment of a string. */ export const MID = { identifier: 'MID', operationScope: OPERATION_SCOPE.RAW, functionScope: [OPERATION_SCOPE.RAW], parameters: [ { identifier: 'CURRENT', optional: false, expectedPrimitive: AST_PRIMITIVES.STRING, validator: [isStringParam], }, { identifier: 'STARTING_AT', optional: false, expectedPrimitive: AST_PRIMITIVES.NUMBER, validator: [isNumberParam, isInteger], }, { identifier: 'EXTRACT_LENGTH', optional: false, expectedPrimitive: AST_PRIMITIVES.NUMBER, validator: [ isNumberParam, greaterThanOrEqualToReference(0), isInteger, ], }, ], transpiler: { elasticsearch, snowflake, redshift, postgresql, databricks, }, primitiveResult: AST_PRIMITIVES.STRING, }; function elasticsearch(current, start, length) { return `${ELASTICSEARCH_SCRIPT_NAMES.subString}(${current}, ${start}, ${length})`; } function sqlRound(value) { return `(FLOOR(ABS(${value})) * (CASE WHEN ${value} < 0 THEN -1 ELSE 1 END))`; } function snowflake(current, start, length) { return `SUBSTRING(${current}, ${sqlRound(start)} , ${sqlRound(length)})`; } function SQL(current, start, length) { return ` (case when ${current} IS NULL OR ${start} IS NULL OR ${length} IS NULL then NULL when (${sqlRound(length)} < 0) OR (${sqlRound(start)} * -1) > LENGTH(${current}) then '' else SUBSTRING(${current}, (case when ${sqlRound(start)} < 0 then (LENGTH(${current}) + ${sqlRound(start)} + 1) when ${sqlRound(start)} = 0 then 1 else ${sqlRound(start)} end)::INTEGER, ${sqlRound(length)}::INTEGER) end )`.trim(); } function redshift(current, start, length) { return SQL(current, start, length); } function postgresql(current, start, length) { return SQL(current, start, length); } function databricks(current, start, length) { return `SUBSTRING(${current}, ${sqlRound(start)} , ${sqlRound(length)})`; } //# sourceMappingURL=mid.js.map