import type { RowType, UntypedTableDef } from './table.ts'; import { Timestamp } from './timestamp.ts'; import { Uuid } from './uuid.ts'; export type Value = string | number | boolean | Uuid | Timestamp; export type Expr = | { type: 'eq'; key: Column; value: Value } | { type: 'and'; children: Expr[] } | { type: 'or'; children: Expr[] }; export const eq = ( key: Column, value: Value ): Expr => ({ type: 'eq', key, value }); export const and = ( ...children: Expr[] ): Expr => { const flat: Expr[] = []; for (const c of children) { if (!c) continue; if (c.type === 'and') flat.push(...c.children); else flat.push(c); } const pruned = flat.filter(Boolean); if (pruned.length === 0) return { type: 'and', children: [] }; if (pruned.length === 1) return pruned[0]; return { type: 'and', children: pruned }; }; export const or = ( ...children: Expr[] ): Expr => { const flat: Expr[] = []; for (const c of children) { if (!c) continue; if (c.type === 'or') flat.push(...c.children); else flat.push(c); } const pruned = flat.filter(Boolean); if (pruned.length === 0) return { type: 'or', children: [] }; if (pruned.length === 1) return pruned[0]; return { type: 'or', children: pruned }; }; export const isEq = ( e: Expr ): e is Extract, { type: 'eq' }> => e.type === 'eq'; export const isAnd = ( e: Expr ): e is Extract, { type: 'and' }> => e.type === 'and'; export const isOr = ( e: Expr ): e is Extract, { type: 'or' }> => e.type === 'or'; export function evaluate( expr: Expr, row: Record ): boolean { switch (expr.type) { case 'eq': { // The actual value of the Column const v = row[expr.key]; if ( typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ) { return v === expr.value; } if (typeof v === 'object') { // Value of the Column and passed Value are both a Uuid so do an integer comparison. if (v instanceof Uuid && expr.value instanceof Uuid) { return v.asBigInt() === expr.value.asBigInt(); } // Value of the Column is a Uuid but passed Value is a String so compare them via string. if (v instanceof Uuid && typeof expr.value === 'string') { return v.toString() === expr.value; } if (v instanceof Timestamp) { // Value of the Column and passed Value are both Timestamps so compare microseconds. if (expr.value instanceof Timestamp) { return v.microsSinceUnixEpoch === expr.value.microsSinceUnixEpoch; } } } return false; } case 'and': return ( expr.children.length === 0 || expr.children.every(c => evaluate(c, row)) ); case 'or': return ( expr.children.length !== 0 && expr.children.some(c => evaluate(c, row)) ); } } function formatValue(v: Value): string { switch (typeof v) { case 'string': return `'${v.replace(/'/g, "''")}'`; case 'number': return Number.isFinite(v) ? String(v) : `'${String(v)}'`; case 'boolean': return v ? 'TRUE' : 'FALSE'; case 'object': { if (v instanceof Uuid) { return `'${v.toString()}'`; } if (v instanceof Timestamp) { return `'${v.toISOString()}'`; } return ''; } } } function escapeIdent(id: string): string { if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) return id; return `"${id.replace(/"/g, '""')}"`; } function parenthesize(s: string): string { if (!s.includes(' AND ') && !s.includes(' OR ')) return s; return `(${s})`; } export function toString( tableDef: TableDef, expr: Expr>> ): string { switch (expr.type) { case 'eq': { const key = tableDef.columns[expr.key].columnMetadata.name ?? expr.key; return `${escapeIdent(key)} = ${formatValue(expr.value)}`; } case 'and': return parenthesize( expr.children.map(expr => toString(tableDef, expr)).join(' AND ') ); case 'or': return parenthesize( expr.children.map(expr => toString(tableDef, expr)).join(' OR ') ); } } /** * This is just the identity function to make things look like SQL. * @param expr * @returns */ export function where(expr: Expr): Expr { return expr; } type MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut'; export function classifyMembership< Col extends string, R extends Record, >(where: Expr | undefined, oldRow: R, newRow: R): MembershipChange { // No filter: everything is in, so updates are always "stayIn". if (!where) { return 'stayIn'; } const oldIn = evaluate(where, oldRow); const newIn = evaluate(where, newRow); if (oldIn && !newIn) { return 'leave'; } if (!oldIn && newIn) { return 'enter'; } if (oldIn && newIn) { return 'stayIn'; } return 'stayOut'; } /** * Extracts the column names from a RowType whose values are of type Value. * Note that this will exclude columns that are of type object, array, etc. */ export type ColumnsFromRow = { [K in keyof R]-?: R[K] extends Value | undefined ? K : never; }[keyof R] & string;