@tanstack/optimistic
Version:
Core optimistic updates library
95 lines (94 loc) • 2.91 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const d2ts = require("@electric-sql/d2ts");
const evaluators = require("./evaluators.cjs");
const joins = require("./joins.cjs");
const groupBy = require("./group-by.cjs");
const orderBy = require("./order-by.cjs");
const keyBy = require("./key-by.cjs");
const select = require("./select.cjs");
function compileQueryPipeline(query, inputs) {
const allInputs = { ...inputs };
if (query.with && query.with.length > 0) {
for (const withQuery of query.with) {
if (!withQuery.as) {
throw new Error(`WITH query must have an "as" property`);
}
if (withQuery.keyBy !== void 0) {
throw new Error(`WITH query cannot have a "keyBy" property`);
}
if (allInputs[withQuery.as]) {
throw new Error(`CTE with name "${withQuery.as}" already exists`);
}
const withQueryWithoutWith = { ...withQuery, with: void 0 };
const compiledWithQuery = compileQueryPipeline(
withQueryWithoutWith,
allInputs
);
allInputs[withQuery.as] = compiledWithQuery;
}
}
const tables = {};
const mainTableAlias = query.as || query.from;
const input = allInputs[query.from];
if (!input) {
throw new Error(`Input for table "${query.from}" not found in inputs map`);
}
tables[mainTableAlias] = input;
let pipeline = input.pipe(
d2ts.map((row) => {
return { [mainTableAlias]: row };
})
);
if (query.join) {
pipeline = joins.processJoinClause(
pipeline,
query,
tables,
mainTableAlias,
allInputs
);
}
if (query.where) {
pipeline = pipeline.pipe(
d2ts.filter((nestedRow) => {
const result = evaluators.evaluateConditionOnNestedRow(
nestedRow,
query.where,
mainTableAlias
);
return result;
})
);
}
if (query.groupBy) {
pipeline = groupBy.processGroupBy(pipeline, query, mainTableAlias);
}
if (query.having) {
pipeline = pipeline.pipe(
d2ts.filter((row) => {
const result = evaluators.evaluateConditionOnNestedRow(
{ [mainTableAlias]: row, ...row },
query.having,
mainTableAlias
);
return result;
})
);
}
pipeline = select.processSelect(pipeline, query, mainTableAlias, allInputs);
let resultPipeline = pipeline;
if (query.keyBy) {
resultPipeline = keyBy.processKeyBy(resultPipeline, query);
}
if (query.orderBy) {
resultPipeline = orderBy.processOrderBy(resultPipeline, query, mainTableAlias);
} else if (query.limit !== void 0 || query.offset !== void 0) {
throw new Error(
`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`
);
}
return resultPipeline;
}
exports.compileQueryPipeline = compileQueryPipeline;
//# sourceMappingURL=pipeline-compiler.cjs.map