/** * @fileoverview Query executor for loq * @module query/executor * * Evaluates parsed queries against log entries for filtering and aggregation. * Supports comparison operators, boolean logic, and aggregation functions. */ import type { LogEntry } from '../parser/types'; import type { QueryNode, ParsedQuery, ComparisonExpr, BinaryLogicExpr, NotExpr } from './ast'; /** * Check if a log entry matches a parsed query * @param entry - Log entry to test * @param query - Parsed query to match against * @returns true if entry matches the query conditions * @example * ```ts * if (matchesQuery(entry, query)) { * console.log(formatEntry(entry, 'color')); * } * ``` */ export function matchesQuery(entry: LogEntry, query: ParsedQuery): boolean { if (!query.where) return true; return evaluateCondition(entry, query.where); } function evaluateCondition(entry: LogEntry, node: QueryNode): boolean { switch (node.type) { case 'comparison': return evaluateComparison(entry, node); case 'binary': return evaluateBinary(entry, node); case 'not': return !evaluateCondition(entry, (node as NotExpr).operand); case 'where': return evaluateCondition(entry, node.condition); default: return true; } } function evaluateComparison(entry: LogEntry, comp: ComparisonExpr): boolean { const fieldValue = getFieldValue(entry, comp.field); const compareValue = comp.value; if (fieldValue === undefined || fieldValue === null) { return false; } switch (comp.operator) { case '=': return String(fieldValue).toLowerCase() === String(compareValue).toLowerCase(); case '!=': return String(fieldValue).toLowerCase() !== String(compareValue).toLowerCase(); case '>': return Number(fieldValue) > Number(compareValue); case '<': return Number(fieldValue) < Number(compareValue); case '>=': return Number(fieldValue) >= Number(compareValue); case '<=': return Number(fieldValue) <= Number(compareValue); case 'contains': return String(fieldValue).toLowerCase().includes(String(compareValue).toLowerCase()); case 'matches': try { const regex = new RegExp(String(compareValue), 'i'); return regex.test(String(fieldValue)); } catch { return false; } default: return false; } } function evaluateBinary(entry: LogEntry, node: BinaryLogicExpr): boolean { const left = evaluateCondition(entry, node.left); if (node.operator === 'and') { return left && evaluateCondition(entry, node.right); } else { return left || evaluateCondition(entry, node.right); } } function getFieldValue(entry: LogEntry, field: string): unknown { // Check common fields first if (field === 'level') return entry.level; if (field === 'message') return entry.message; if (field === 'timestamp') return entry.timestamp; // Check in fields object if (entry.fields && field in entry.fields) { return entry.fields[field]; } // Support nested field access with dot notation if (field.includes('.') && entry.fields) { const parts = field.split('.'); let value: unknown = entry.fields; for (const part of parts) { if (value && typeof value === 'object' && part in value) { value = (value as Record)[part]; } else { return undefined; } } return value; } return undefined; } /** * Result of a count aggregation */ export interface AggregationResult { /** Map of group values to counts */ groups: Map; /** Total count across all groups */ total: number; } /** * Aggregate log entries by counting * @param entries - Log entries to aggregate * @param groupBy - Optional field to group by * @returns Aggregation result with counts * @example * ```ts * const result = aggregateCount(entries, 'level'); * // result.groups: Map { 'error' => 5, 'info' => 10 } * ``` */ export function aggregateCount(entries: LogEntry[], groupBy?: string): AggregationResult { const groups = new Map(); let total = 0; for (const entry of entries) { total++; if (groupBy) { const key = String(getFieldValue(entry, groupBy) ?? '(empty)'); groups.set(key, (groups.get(key) || 0) + 1); } } return { groups, total }; } /** * Perform numeric aggregation on log entries * @param entries - Log entries to aggregate * @param field - Numeric field to aggregate * @param func - Aggregation function (sum, avg, min, max) * @param groupBy - Optional field to group by * @returns Map of group values to aggregated results */ export function aggregateNumeric( entries: LogEntry[], field: string, func: 'sum' | 'avg' | 'min' | 'max', groupBy?: string ): Map { const groups = new Map(); for (const entry of entries) { const value = Number(getFieldValue(entry, field)); if (isNaN(value)) continue; const key = groupBy ? String(getFieldValue(entry, groupBy) ?? '(empty)') : '_total'; const arr = groups.get(key) || []; arr.push(value); groups.set(key, arr); } const result = new Map(); for (const [key, values] of groups) { switch (func) { case 'sum': result.set(key, values.reduce((a, b) => a + b, 0)); break; case 'avg': result.set(key, values.reduce((a, b) => a + b, 0) / values.length); break; case 'min': result.set(key, Math.min(...values)); break; case 'max': result.set(key, Math.max(...values)); break; } } return result; }