Page MenuHomeSealhub

query-base.ts
No OneTemporary

query-base.ts

import type { QueryStage } from "./query-stage.js";
import {
type ComplexLookupBodyInput,
default as QueryStep,
Lookup,
Match,
type SimpleLookupBodyInput,
} from "./query-step.js";
export type SQLPreparedStatement = {
where: string;
join: string[];
parameters: (string | number)[];
};
export class Query {
steps: QueryStep[];
body: any;
constructor() {
this.steps = [];
}
lookup(body: SimpleLookupBodyInput | ComplexLookupBodyInput) {
const lookup_step = Lookup.fromBody(body);
this.steps.push(lookup_step);
return lookup_step.hash();
}
match(body: { [key: string]: unknown }) {
for (const key in body) {
this.steps.push(new Match({ [key]: body[key] }));
}
}
dump() {
return this.steps;
}
toPipeline(): QueryStage[] {
return this.steps
.map((step) => step.toPipeline())
.reduce((acc, cur) => acc.concat(cur), []);
}
toPreparedStatement(): SQLPreparedStatement {
const compiledStatements = this.steps.map((step) =>
step.toPreparedStatement()
);
let counter = 0;
return compiledStatements.reduce(
(finalStatement, currentStatement) => ({
where: [finalStatement.where, currentStatement.where]
.filter((statement) => !!statement)
.map((statement) => `(${statement})`)
.join(" AND ")
.replace(/\$[0-9]+/g, () => `$${++counter}`),
join: [...finalStatement.join, ...currentStatement.join],
parameters: [
...finalStatement.parameters,
...currentStatement.parameters,
],
}),
{
where: "",
join: [],
parameters: [],
}
);
}
static fromSingleMatch(body: any) {
const query = new Query();
query.match(body);
return query;
}
static fromCustomPipeline(stages: QueryStage[], rehash = false) {
const ret = new Query();
const lookup_field_to_hash: { [field_as: string]: string } = {};
for (const stage of stages) {
const query_steps = QueryStep.fromStage(stage, false, rehash);
for (const [old_name, new_name] of Object.entries(
lookup_field_to_hash
)) {
query_steps.forEach((step) =>
step.renameField(old_name, new_name)
);
}
for (const query_step of query_steps) {
if (query_step instanceof Lookup) {
lookup_field_to_hash[stage?.$lookup?.as as string] =
query_step.body.as;
}
}
ret.steps.push(...query_steps);
}
return ret;
}
_isUnwindStage(stages: QueryStage[], i: number) {
const currentStage = stages[i];
if (!currentStage) {
throw Error("stage is missing");
}
if (!currentStage.$lookup) {
return false;
}
return (stages[i + 1]?.$unwind && true) || false;
}
prefix(prefix: string): Query {
this.steps = this.steps.map((step) => step.prefix(prefix));
return this;
}
}

File Metadata

Mime Type
text/x-java
Expires
Wed, Aug 13, 17:09 (1 d, 2 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
868695
Default Alt Text
query-base.ts (2 KB)

Event Timeline