import { SqlEvaluationError } from './errors.js'; import { builtins } from './functions.js'; /** * Evaluates a parsed expression AST against a JSON context object. * * Implements SQL three-valued logic: comparisons and arithmetic against `null` * propagate `null` rather than throwing or coercing, except `IS [NOT] NULL` * which always returns a real boolean. * * @param {import('./parser.js').Expr} node * @param {Record} context * @param {{functions?: Record any>}} [options] * @returns {any} */ export function evaluate(node, context, options = {}) { const functions = { ...builtins, ...uppercaseKeys(options.functions) }; return evalNode(node, context, functions); } /** * @param {import('./parser.js').Expr} node * @param {Record} ctx * @param {Record any>} functions * @returns {any} */ function evalNode(node, ctx, functions) { switch (node.type) { case 'Literal': return node.value; case 'ArrayLiteral': return node.elements.map((e) => evalNode(e, ctx, functions)); case 'ObjectLiteral': { /** @type {Record} */ const out = {}; for (const prop of node.properties) { out[prop.key] = evalNode(prop.value, ctx, functions); } return out; } case 'Identifier': case 'Member': case 'Index': case 'Unnest': return evalPathish(node, ctx, functions).value; case 'Call': return evalCall(node, ctx, functions); case 'Negate': { const v = evalNode(node.expr, ctx, functions); if (v === null) return null; if (typeof v !== 'number') throw new SqlEvaluationError(`Cannot negate ${typeName(v)}`); return -v; } case 'Not': { const v = evalNode(node.expr, ctx, functions); if (v === null) return null; if (typeof v !== 'boolean') throw new SqlEvaluationError(`NOT requires a boolean, got ${typeName(v)}`); return !v; } case 'Logical': return evalLogical(node, ctx, functions); case 'Comparison': return evalComparison(node, ctx, functions); case 'IsNull': { const v = evalNode(node.expr, ctx, functions); const isNull = v === null; return node.negate ? !isNull : isNull; } case 'Like': return evalLike(node, ctx, functions); case 'InList': return evalInList(node, ctx, functions); case 'InArray': return evalInArray(node, ctx, functions); case 'Binary': return evalBinary(node, ctx, functions); default: throw new SqlEvaluationError(`Unknown AST node type: ${/** @type {any} */ (node).type}`); } } /** * Path expressions (`Identifier`/`Member`/`Index`/`Unnest`) thread a `mapped` flag: once an * `[]` unnest is hit, every subsequent `.prop`/`[i]` in the chain maps over the resulting array * instead of applying to it directly (e.g. `items[].sku` -> `items.map(i => i.sku)`). * @param {import('./parser.js').Expr} node * @param {Record} ctx * @param {Record any>} functions * @returns {{value: any, mapped: boolean}} */ function evalPathish(node, ctx, functions) { switch (node.type) { case 'Identifier': { const v = ctx == null ? null : ctx[node.name]; return { value: v === undefined ? null : v, mapped: false }; } case 'Member': { const base = evalPathish(node.object, ctx, functions); if (base.mapped) { const arr = Array.isArray(base.value) ? base.value : []; return { value: arr.map((item) => memberGet(item, node.property)), mapped: true }; } return { value: memberGet(base.value, node.property), mapped: false }; } case 'Index': { const base = evalPathish(node.object, ctx, functions); const idx = evalNode(node.index, ctx, functions); if (base.mapped) { const arr = Array.isArray(base.value) ? base.value : []; return { value: arr.map((item) => indexGet(item, idx)), mapped: true }; } return { value: indexGet(base.value, idx), mapped: false }; } case 'Unnest': { const base = evalPathish(node.object, ctx, functions); if (base.mapped) { const arr = Array.isArray(base.value) ? base.value : []; const flattened = arr.flatMap((v) => { if (v === null || v === undefined) return []; if (Array.isArray(v)) return v; throw new SqlEvaluationError('Cannot unnest a non-array value'); }); return { value: flattened, mapped: true }; } if (base.value === null || base.value === undefined) return { value: [], mapped: true }; if (!Array.isArray(base.value)) throw new SqlEvaluationError('Cannot unnest a non-array value'); return { value: base.value, mapped: true }; } default: return { value: evalNode(node, ctx, functions), mapped: false }; } } /** @param {any} obj @param {string} prop */ function memberGet(obj, prop) { if (obj === null || obj === undefined) return null; if (typeof obj !== 'object' || Array.isArray(obj)) return null; const v = obj[prop]; return v === undefined ? null : v; } /** @param {any} obj @param {any} idx */ function indexGet(obj, idx) { if (obj === null || obj === undefined || idx === null) return null; if (Array.isArray(obj)) { if (typeof idx !== 'number' || !Number.isInteger(idx)) { throw new SqlEvaluationError('Array index must be an integer'); } const i = idx < 0 ? obj.length + idx : idx; const v = obj[i]; return v === undefined ? null : v; } if (typeof obj === 'object') { if (typeof idx !== 'string') throw new SqlEvaluationError('Object index must be a string'); const v = obj[idx]; return v === undefined ? null : v; } return null; } /** * @param {import('./parser.js').LogicalNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalLogical(node, ctx, functions) { const left = evalNode(node.left, ctx, functions); if (node.op === 'AND') { if (left === false) return false; const right = evalNode(node.right, ctx, functions); if (right === false) return false; if (left === null || right === null) return null; return true; } if (left === true) return true; const right = evalNode(node.right, ctx, functions); if (right === true) return true; if (left === null || right === null) return null; return false; } /** * @param {import('./parser.js').ComparisonNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalComparison(node, ctx, functions) { const l = evalNode(node.left, ctx, functions); const r = evalNode(node.right, ctx, functions); if (l === null || r === null) return null; switch (node.op) { case '=': return deepEqual(l, r); case '!=': return !deepEqual(l, r); case '<': case '>': case '<=': case '>=': requireOrderable(l, r, node.op); if (node.op === '<') return l < r; if (node.op === '>') return l > r; if (node.op === '<=') return l <= r; return l >= r; default: throw new SqlEvaluationError(`Unknown comparison operator: ${node.op}`); } } /** @param {any} l @param {any} r @param {string} op */ function requireOrderable(l, r, op) { const bothNumbers = typeof l === 'number' && typeof r === 'number'; const bothStrings = typeof l === 'string' && typeof r === 'string'; if (!bothNumbers && !bothStrings) { throw new SqlEvaluationError(`Cannot compare ${typeName(l)} and ${typeName(r)} with ${op}`); } } /** * @param {import('./parser.js').LikeNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalLike(node, ctx, functions) { const v = evalNode(node.expr, ctx, functions); const pattern = evalNode(node.pattern, ctx, functions); if (v === null || pattern === null) return null; if (typeof v !== 'string' || typeof pattern !== 'string') { throw new SqlEvaluationError('LIKE requires string operands'); } const matched = likeToRegExp(pattern).test(v); return node.negate ? !matched : matched; } /** @param {string} pattern */ function likeToRegExp(pattern) { let re = ''; for (const ch of pattern) { if (ch === '%') re += '.*'; else if (ch === '_') re += '.'; else re += ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } return new RegExp(`^${re}$`, 's'); } /** * @param {import('./parser.js').InListNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalInList(node, ctx, functions) { const v = evalNode(node.expr, ctx, functions); if (v === null) return null; let sawNull = false; for (const itemNode of node.items) { const item = evalNode(itemNode, ctx, functions); if (item === null) { sawNull = true; continue; } if (deepEqual(v, item)) return !node.negate; } if (sawNull) return null; return node.negate; } /** * @param {import('./parser.js').InArrayNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalInArray(node, ctx, functions) { const v = evalNode(node.expr, ctx, functions); const arr = evalNode(node.array, ctx, functions); if (v === null || arr === null) return null; if (!Array.isArray(arr)) throw new SqlEvaluationError('IN requires an array value'); let sawNull = false; for (const item of arr) { if (item === null) { sawNull = true; continue; } if (deepEqual(v, item)) return !node.negate; } if (sawNull) return null; return node.negate; } /** * @param {import('./parser.js').BinaryNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalBinary(node, ctx, functions) { const l = evalNode(node.left, ctx, functions); const r = evalNode(node.right, ctx, functions); if (node.op === '||') { if (l === null || r === null) return null; return stringify(l) + stringify(r); } if (l === null || r === null) return null; if (typeof l !== 'number' || typeof r !== 'number') { throw new SqlEvaluationError(`Operator ${node.op} requires numbers, got ${typeName(l)} and ${typeName(r)}`); } switch (node.op) { case '+': return l + r; case '-': return l - r; case '*': return l * r; case '/': if (r === 0) throw new SqlEvaluationError('Division by zero'); return l / r; case '%': if (r === 0) throw new SqlEvaluationError('Division by zero'); return l % r; default: throw new SqlEvaluationError(`Unknown operator: ${node.op}`); } } /** @param {any} v */ function stringify(v) { return typeof v === 'string' ? v : JSON.stringify(v); } /** * @param {import('./parser.js').CallNode} node * @param {Record} ctx * @param {Record any>} functions */ function evalCall(node, ctx, functions) { const fn = functions[node.name.toUpperCase()]; if (typeof fn !== 'function') { throw new SqlEvaluationError(`Unknown function: ${node.name}`); } const args = node.args.map((a) => evalNode(a, ctx, functions)); return fn(...args); } /** @param {any} a @param {any} b */ function deepEqual(a, b) { if (a === b) return true; if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; return a.every((v, i) => deepEqual(v, b[i])); } if (isPlainObject(a) && isPlainObject(b)) { const ak = Object.keys(a); const bk = Object.keys(b); if (ak.length !== bk.length) return false; return ak.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k])); } return false; } /** @param {any} v */ function isPlainObject(v) { return typeof v === 'object' && v !== null && !Array.isArray(v); } /** @param {any} v */ function typeName(v) { if (v === null) return 'null'; if (Array.isArray(v)) return 'array'; return typeof v; } /** @param {Record|undefined} obj */ function uppercaseKeys(obj) { if (!obj) return {}; /** @type {Record} */ const out = {}; for (const [k, v] of Object.entries(obj)) out[k.toUpperCase()] = v; return out; }