UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

65 lines (64 loc) 1.76 kB
import { BTreeIndex } from "./btree-index.js"; function ensureIndexForExpression(expression, collection) { if (collection.config.autoIndex !== `eager`) { return; } if (collection.status === `loading` || collection.status === `initialCommit`) { return; } const indexableExpressions = extractIndexableExpressions(expression); for (const { fieldName, fieldPath } of indexableExpressions) { const existingIndex = Array.from(collection.indexes.values()).find( (index) => index.matchesField(fieldPath) ); if (existingIndex) { continue; } try { collection.createIndex((row) => row[fieldName], { name: `auto_${fieldName}`, indexType: BTreeIndex }); } catch (error) { console.warn( `Failed to create auto-index for field "${fieldName}":`, error ); } } } function extractIndexableExpressions(expression) { const results = []; function extractFromExpression(expr) { if (expr.type !== `func`) { return; } const func = expr; if (func.name === `and`) { for (const arg of func.args) { extractFromExpression(arg); } return; } const supportedOperations = [`eq`, `gt`, `gte`, `lt`, `lte`, `in`]; if (!supportedOperations.includes(func.name)) { return; } if (func.args.length < 1 || func.args[0].type !== `ref`) { return; } const fieldRef = func.args[0]; const fieldPath = fieldRef.path; if (fieldPath.length !== 1) { return; } const fieldName = fieldPath[0]; results.push({ fieldName, fieldPath }); } extractFromExpression(expression); return results; } export { ensureIndexForExpression }; //# sourceMappingURL=auto-index.js.map