@tanstack/db
Version:
A reactive client store for building super fast apps on sync
65 lines (64 loc) • 1.88 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const btreeIndex = require("./btree-index.cjs");
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.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;
}
exports.ensureIndexForExpression = ensureIndexForExpression;
//# sourceMappingURL=auto-index.cjs.map