All files / owid-grapher/clientUtils SqlFilterSExpression.ts

96.79% Statements 422/436
96.77% Branches 60/62
91.49% Functions 43/47
96.79% Lines 422/436

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 5071x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 108x 108x 108x 108x 108x 1x 54x 54x 54x 54x 54x 1x 30x 30x 30x 30x 30x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 18x 18x 1x 8x 8x 1x 1x 3x 3x 1x 1x 1x 1x 93x 93x 1x 31x 31x 1x 1x 28x 28x 1x 1x 1x 1x 1x 1x 30x 30x 1x 1x 8x 8x 8x 8x 8x 1x 7x 7x 1x 1x 9x 9x 9x 9x 9x 1x 1x 3x 3x 3x 3x 5x 5x 5x 5x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 1x 9x 9x 9x 1x 1x 1x 3x 3x 3x 3x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x                 1x 1x 1x     1x 1x     1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 1x 1x 7x 7x 7x 7x 1x 1x 4x 4x 4x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 1x 1x 7x 7x 7x 7x 1x 1x 2x 2x 2x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 1x 1x 5x 5x 5x 5x 1x 1x 4x 4x 4x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 3x 3x 3x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 2x 1x 1x 2x 2x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 9x 1x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 154x 154x 154x 154x 154x 43x 42x 42x 42x 42x 42x 42x                                                                                                                                              
import parse = require("s-expression")
import pointer from "json8-pointer"
import { isArray, tail, without } from "lodash"
// This type models what we get from the s-expression library. This library
// transforms lists in S-Expressions into array, strings inside double quotes
// as String (note the uppercase! It really uses the rarely used String object) and
// all other tokes like numbers or symbols as normal string.
export type SExprAtom = string | String | SExprAtom[] // eslint-disable-line @typescript-eslint/ban-types
 
export enum Arity {
    nullary = "nullary",
    unary = "unary",
    binary = "binary",
    nary = "nary",
}
 
const arityToNumberMap = new Map([
    [Arity.nullary, 0],
    [Arity.unary, 1],
    [Arity.binary, 2],
    [Arity.nary, undefined],
])
 
export interface Operation {
    toSql(): string
    toSExpr(): string
    expressionType: ExpressionType
}
 
export abstract class NumericOperation implements Operation {
    abstract toSql(): string
    abstract toSExpr(): string
    expressionType: ExpressionType = ExpressionType.numeric
}
 
export abstract class BooleanOperation implements Operation {
    abstract toSql(): string
    abstract toSExpr(): string
    expressionType: ExpressionType = ExpressionType.boolean
}
 
export abstract class StringOperation implements Operation {
    abstract toSql(): string
    abstract toSExpr(): string
    expressionType: ExpressionType = ExpressionType.string
}
 
export enum ExpressionType {
    numeric = "numeric",
    boolean = "boolean",
    string = "string",
    any = "any", // This is used for values we can't type check e.g. jsonpath queries that might return anything
}
 
export class BooleanAtom extends BooleanOperation {
    constructor(public value: boolean) {
        super()
    }
    toSql(): string {
        return this.value.toString()
    }
 
    toSExpr(): string {
        return this.value.toString()
    }
}
 
export class NumberAtom extends NumericOperation {
    constructor(public value: number) {
        super()
    }
    toSql(): string {
        return this.value.toString()
    }
 
    toSExpr(): string {
        return this.value.toString()
    }
}
const quoteReplaceRegex = /'/g
const backslashReplaceRegex = /\\/g
const doubleQuoteReplaceRegex = /"/g
export class StringAtom extends StringOperation {
    constructor(public value: string) {
        super()
    }
    expressionType = ExpressionType.string
    escapedValue(): string {
        return this.value
            .toString()
            .replace(quoteReplaceRegex, "''")
            .replace(backslashReplaceRegex, "\\\\")
    }
    toSql(): string {
        return `'${this.escapedValue()}'` // escape single quotes to avoid SQL injection attacks :)
    }
 
    toSExpr(): string {
        return `"${this.value
            .toString()
            .replace(backslashReplaceRegex, "\\\\")
            .replace(doubleQuoteReplaceRegex, '\\"')}"`
    }
}
 
function jsonPointerToJsonPath(jsonpointer: string): string {
    const pointerFragments = pointer.decode(jsonpointer)
    let path = "$"
    for (const fragment of pointerFragments) {
        const number = Number.parseInt(fragment)
        if (!Number.isNaN(number)) path += `[${number}]`
        else path += `.${fragment}`
    }
    return path
}
 
export class JsonPointerSymbol implements Operation {
    // Json pointer is actually less restrictive and allows pretty much all unicode
    // code points but for the foreseeable future we will only have \w and \d, _ and -
    // characters in actual use. Tilde is from json pointer to escape / inside field names
    // We also disallow empty jsonPointer for now even though they are legal (if you
    // want to enable them then make sure that the parsing decisions outside of here
    // all correctly allow this)
    static jsonPointerRegex: RegExp = /^\/[\w\d/\-~_]+$/
    static columnName: string = "grapherConfig" // TODO: this should come from context
    static isValidJsonPointer(str: string): boolean {
        return JsonPointerSymbol.jsonPointerRegex.test(str)
    }
    constructor(public value: string) {
        if (!JsonPointerSymbol.isValidJsonPointer(value))
            throw Error(`Invalid Json Pointer: ${value} - did not match regex`)
    }
    arity = Arity.nullary
    expressionType = ExpressionType.any
    toSql(): string {
        return `JSON_EXTRACT(${
            JsonPointerSymbol.columnName
        }, "${jsonPointerToJsonPath(this.value.toString())}")`
    }
 
    toSExpr(): string {
        return this.value.toString()
    }
}
 
export const SQL_COLUMN_NAME_VARIABLE_NAME = "variables.name"
export const SQL_COLUMN_NAME_DATASET_NAME = "datasets.name"
export const SQL_COLUMN_NAME_NAMESPACE_NAME = "namespaces.name"
 
export class SqlColumnName implements Operation {
    // NOTE: this is a temporary solution for the beginning of using S Expressions for filtering.
    //       Once we start using this in more places, declaring the whitelist of columns that are
    //       valid to query needs to come from the piece of code that wants to use the expression.
    //       I think we should not start allowing expressions that traverse foreign keys and instead
    //       create views and whitelist column names in those if we need more complex filters
    static allowedColumnNamesAndTypes: Map<string, ExpressionType> = new Map([
        [SQL_COLUMN_NAME_VARIABLE_NAME, ExpressionType.string],
        [SQL_COLUMN_NAME_DATASET_NAME, ExpressionType.string],
        [SQL_COLUMN_NAME_NAMESPACE_NAME, ExpressionType.string],
    ])
    static isValidSqlColumnName(str: string): boolean {
        return SqlColumnName.allowedColumnNamesAndTypes.has(str)
    }
    constructor(public value: string) {
        if (!SqlColumnName.isValidSqlColumnName(value))
            throw Error(
                `Invalid column name: ${value} - did not match the set of allowed columns`
            )
        this.expressionType = SqlColumnName.allowedColumnNamesAndTypes.get(
            this.value
        )!
    }
    arity = Arity.nullary
    expressionType: ExpressionType
    toSql(): string {
        return `${this.value}`
    }
 
    toSExpr(): string {
        return this.value.toString()
    }
}
 
export enum ArithmeticOperator {
    addition = "+",
    subtraction = "-",
    multiplication = "*",
    division = "/",
}
 
export const allArithmeticOperators = [
    ArithmeticOperator.addition,
    ArithmeticOperator.subtraction,
    ArithmeticOperator.multiplication,
    ArithmeticOperator.division,
]
 
export class ArithmeticOperation extends NumericOperation {
    constructor(
        public operator: ArithmeticOperator,
        public operands: NumericOperation[]
    ) {
        super()
    }
 
    toSql(): string {
        return `(${this.operands
            .map((operand) => operand.toSql())
            .join(this.operator)})` // we emit too many parenthesis here but don't want to deal with precedence rn
    }
 
    toSExpr(): string {
        const operands = this.operands.map((op) => op.toSExpr()).join(" ")
        return `(${this.operator} ${operands})`
    }
}
 
export enum EqualityOperator {
    equal = "=",
    unequal = "<>",
}
 
export const allEqualityOperators = [
    EqualityOperator.equal,
    EqualityOperator.unequal,
]
 
export class EqualityComparision extends BooleanOperation {
    constructor(
        public operator: EqualityOperator,
        public operands: Operation[]
    ) {
        super()
    }
 
    toSql(): string {
        return `(${this.operands
            .map((operand) => operand.toSql())
            .join(" " + this.operator + " ")})` // we emit too many parenthesis here but don't want to deal with precedence rn
    }
 
    toSExpr(): string {
        const operands = this.operands.map((op) => op.toSExpr()).join(" ")
        return `(${this.operator} ${operands})`
    }
}
 
export class StringContainsOperation extends BooleanOperation {
    constructor(
        public container: StringOperation,
        public searchString: StringAtom
    ) {
        super()
    }
 
    toSql(): string {
        return `(${this.container.toSql()} LIKE '%${this.searchString.escapedValue()}%')`
    }
 
    toSExpr(): string {
        return `(CONTAINS ${this.container.toSExpr()} ${this.searchString.toSExpr()})`
    }
}
 
export enum ComparisonOperator {
    less = "<",
    lessOrEqual = "<=",
    greater = ">",
    greaterOrEqual = ">=",
}
 
export const allComparisonOperators = [
    ComparisonOperator.less,
    ComparisonOperator.lessOrEqual,
    ComparisonOperator.greater,
    ComparisonOperator.greaterOrEqual,
]
 
export class NumericComparision extends BooleanOperation {
    constructor(
        public operator: ComparisonOperator,
        public operands: [NumericOperation, NumericOperation]
    ) {
        super()
    }
 
    toSql(): string {
        return `(${this.operands[0].toSql()} ${
            this.operator
        } ${this.operands[1].toSql()})` // we emit too many parenthesis here but don't want to deal with precedence rn
    }
 
    toSExpr(): string {
        const operands = this.operands.map((op) => op.toSExpr()).join(" ")
        return `(${this.operator} ${operands})`
    }
}
 
export enum BinaryLogicOperators {
    and = "AND",
    or = "OR",
}
 
export const allBinaryLogicOperators = [
    BinaryLogicOperators.and,
    BinaryLogicOperators.or,
]
 
export class BinaryLogicOperation extends BooleanOperation {
    constructor(
        public operator: BinaryLogicOperators,
        public operands: BooleanOperation[]
    ) {
        super()
    }
 
    toSql(): string {
        return `(${this.operands
            .map((operand) => operand.toSql())
            .join(" " + this.operator + " ")})` // we emit too many parenthesis here but don't want to deal with precedence rn
    }
 
    toSExpr(): string {
        const operands = this.operands.map((op) => op.toSExpr()).join(" ")
        return `(${this.operator} ${operands})`
    }
}
 
export class Negation extends BooleanOperation {
    constructor(public operand: BooleanOperation) {
        super()
    }
 
    toSql(): string {
        return `(NOT ${this.operand.toSql()})` // we emit too many parenthesis here but don't want to deal with precedence rn
    }
 
    toSExpr(): string {
        return `(NOT ${this.operand.toSExpr()})`
    }
}
 
interface OperationInfo {
    arity: Arity
    operandsType: ExpressionType
    ctor(args: Operation[]): Operation
}
 
const arithmeticOperatorInfos = allArithmeticOperators.map(
    (op) =>
        [
            op.toString(),
            {
                arity: Arity.nary,
                operandsType: ExpressionType.numeric,
                ctor: (args: Operation[]): Operation =>
                    new ArithmeticOperation(op, args as NumericOperation[]),
            },
        ] as const
)
const equalityOperatorInfos = allEqualityOperators.map(
    (op) =>
        [
            op.toString(),
            {
                arity: Arity.binary,
                operandsType: ExpressionType.any,
                ctor: (args: Operation[]): Operation =>
                    new EqualityComparision(op, args),
            },
        ] as const
)
const comparisionOperatorInfos = allComparisonOperators.map(
    (op) =>
        [
            op.toString(),
            {
                arity: Arity.binary,
                operandsType: ExpressionType.numeric,
                ctor: (args: Operation[]): Operation =>
                    new NumericComparision(
                        op,
                        args as [NumericOperation, NumericOperation]
                    ),
            },
        ] as const
)
const binaryLogicOperatorInfos = allBinaryLogicOperators.map(
    (op) =>
        [
            op.toString(),
            {
                arity: Arity.nary,
                operandsType: ExpressionType.boolean,
                ctor: (args: Operation[]): Operation =>
                    new BinaryLogicOperation(op, args as BooleanOperation[]),
            },
        ] as const
)
const operationFactoryMap = new Map<string, OperationInfo>([
    //...(allArithmeticOperators.map(op => [op, {arity: Arity.nary, operandsType: ExpressionType.numeric, ctor: arithMeticCtor}])
    ...arithmeticOperatorInfos,
    ...equalityOperatorInfos,
    ...comparisionOperatorInfos,
    ...binaryLogicOperatorInfos,
    [
        "NOT",
        {
            arity: Arity.unary,
            operandsType: ExpressionType.boolean,
            ctor: (args: Operation[]): Operation => new Negation(args[0]),
        },
    ],
    [
        "CONTAINS",
        {
            arity: Arity.binary,
            operandsType: ExpressionType.string,
            ctor: (args: Operation[]): Operation =>
                new StringContainsOperation(args[0], args[1] as StringAtom),
        },
    ],
])
 
export function parseOperationRecursive(
    sExpr: SExprAtom | undefined
): Operation | undefined {
    if (sExpr === undefined) return undefined
    if (isArray(sExpr)) {
        if (sExpr.length === 0) return undefined
        else {
            const firstElement = sExpr[0]
            // The first element of a list in an SExpression has to be a function. In our
            // parser this means that it has to be of type string which is what symbols end up as
            // (actual verbatim strings that are quoted are String instances and nested lists are arrays)
            if (typeof firstElement !== "string")
                throw Error(
                    `First element in list was not a symbol! ${firstElement}`
                )
            const op = operationFactoryMap.get(firstElement)
            if (op === undefined)
                throw Error(`Unknown function ${firstElement}!`)
 
            // Check if the arity matches the number of arguments
            const expectedArgs = arityToNumberMap.get(op.arity)
            const parsedArgs = without(
                tail(sExpr).map(parseOperationRecursive),
                undefined
            ) as Operation[]
            if (
                expectedArgs !== undefined &&
                parsedArgs.length !== expectedArgs
            )
                throw Error(
                    `Function ${firstElement} expected ${expectedArgs} arguments but got ${parsedArgs.length}`
                )
 
            // Check if the types of the arguments match the expected type for this operation unless the operation accepts type "any"
            if (
                op.operandsType !== ExpressionType.any &&
                !parsedArgs.every(
                    (item) =>
                        item.expressionType === op.operandsType ||
                        item.expressionType === ExpressionType.any
                )
            )
                throw Error(
                    `Operation ${firstElement} expected arguments of type ${op.operandsType} but not all arguments were of that type`
                )
 
            // All checks passed, construct and return the Operator
            return op.ctor(parsedArgs)
        }
    }
    // our s-expression parser library turns quoted strings like "hello" into String instances to
    // differentiate them from unquoted symbols
    else if (sExpr instanceof String) {
        if (sExpr === "") return undefined
        else return new StringAtom(sExpr.valueOf())
    } else if (typeof sExpr === "string") {
        let num: number
        if (sExpr === "") return undefined
        else if (sExpr === "true") return new BooleanAtom(true)
        else if (sExpr === "false") return new BooleanAtom(false)
        // Handling NaN correctly throught the entire DSL is hard - let's see if we can just drop it
        else if (sExpr === "NaN") return undefined
        else if ((num = Number.parseFloat(sExpr))) return new NumberAtom(num)
        else if (SqlColumnName.isValidSqlColumnName(sExpr))
            return new SqlColumnName(sExpr)
        else return new JsonPointerSymbol(sExpr) // this will throw if the symbol is not a JsonPointer which is the only valid symbol we know of
    } else throw Error(`Unexpected type in parseToOperation: ${sExpr}!`)
}
 
export function parseToOperation(
    sexpressionString: string
): Operation | undefined {
    // Use the s-expression library to turn character strings with parens into
    // nested arrays. The parsed datastructure is thus (potentially nested) arrays
    // that contain either string primitives or String instances. This is a bit odd
    // but useful - the latter is used to represent quoted strings, the primitive
    // string is used for everything, which means numbers, booleans and symbols.
    //
    const sExpr = parse(sexpressionString) as SExprAtom
    const result = parseOperationRecursive(sExpr)
    return result
}