Spaces:
Running
Running
File size: 10,732 Bytes
aa89cb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | import { Value } from './value';
import { SmartList } from './smart-list';
import { retainQueryDiagnosticOrigin, snapshotQuery } from './query-snapshot';
import type { QueryOperation } from './request-intent';
export enum SortDirection {
Asc = 'Asc',
Desc = 'Desc'
}
export class OrderBy {
constructor(
public field: string,
public expr: any | null,
public direction: SortDirection
) {}
static new(field: string, direction: SortDirection): OrderBy {
return new OrderBy(field, null, direction);
}
static expr(expr: any, direction: SortDirection): OrderBy {
return new OrderBy('', expr, direction);
}
static asc(field: string): OrderBy { return OrderBy.new(field, SortDirection.Asc); }
static desc(field: string): OrderBy { return OrderBy.new(field, SortDirection.Desc); }
}
export class AggregationCacheOptions {
constructor(
public enabledValue: boolean,
public cacheExpiredMillis: number,
public propagateValue: boolean,
public propagateCacheExpiredMillis: number
) {}
static enabled(cacheExpiredMillis: number): AggregationCacheOptions {
return new AggregationCacheOptions(true, cacheExpiredMillis, false, 0);
}
propagate(cacheExpiredMillis: number): AggregationCacheOptions {
this.propagateValue = true;
this.propagateCacheExpiredMillis = cacheExpiredMillis;
return this;
}
}
export interface TeaQLPage<T> {
data: SmartList<T>;
totalCount: number;
offset: number;
limit: number;
}
export interface QuerySelection {
toQuery(): SelectQuery;
}
export interface FacetRequest {
facetName: string;
relationName: string;
query: SelectQuery;
includeAllFacets: boolean;
operation?: QueryOperation;
}
export interface RelationAggregate {
relationName: string;
alias: string;
query: SelectQuery;
singleResult: boolean;
operation?: QueryOperation;
}
export class SelectQuery {
private hardLimitValue: number = 10_000;
private continuousPageFetchOptions?: { namespace: string; ttlSeconds: number };
private continuousPageRuntimeContext?: any;
private idSetPaginationOptions?: { namespace: string; ttlSeconds: number; maxIds: number };
private idSetPaginationRuntimeContext?: any;
private topNProbeThreshold?: number;
public entity: string;
public filterCondition: any | null = null;
public limitValue: number = 0;
public offsetValue: number = 0;
public orderItems: OrderBy[] = [];
public selectItems: string[] = [];
public properties: string[] = [];
public joins: any[] = [];
public groupByItems: string[] = [];
public aggregateItems: any[] = [];
public aggregationCache?: AggregationCacheOptions;
public facets: FacetRequest[] = [];
public relations: Array<{
name: string;
query?: SelectQuery;
localKey?: string;
foreignKey?: string;
many?: boolean;
operation?: QueryOperation;
}> = [];
public relationAggregates: RelationAggregate[] = [];
public commentText?: string;
public purposeText?: string;
constructor(entity: string) {
this.entity = entity;
// Local runtime policy must never cross the federation JSON boundary.
Object.defineProperty(this, 'hardLimitValue', { enumerable: false, writable: true, value: 10_000 });
Object.defineProperty(this, 'continuousPageFetchOptions', { enumerable: false, writable: true, value: undefined });
Object.defineProperty(this, 'continuousPageRuntimeContext', { enumerable: false, writable: true, value: undefined });
Object.defineProperty(this, 'idSetPaginationOptions', { enumerable: false, writable: true, value: undefined });
Object.defineProperty(this, 'idSetPaginationRuntimeContext', { enumerable: false, writable: true, value: undefined });
Object.defineProperty(this, 'topNProbeThreshold', { enumerable: false, writable: true, value: undefined });
}
comment(text: string): this {
this.commentText = text;
return this;
}
purpose(text: string): this {
this.purposeText = text;
return this;
}
facetBy(
facetName: string,
relationName: string,
request: QuerySelection,
includeAllFacets = true,
operation?: QueryOperation,
): this {
this.facets.push({
facetName,
relationName,
query: request.toQuery(),
includeAllFacets,
operation,
});
return this;
}
clone(): SelectQuery {
const copy = snapshotQuery(this);
// Cloning an execution snapshot produces a mutable builder. The request
// envelope still owns immutable intent and reapplies it on derivation.
for (const field of ['commentText', 'purposeText', '_comment', '_purpose']) {
const descriptor = Object.getOwnPropertyDescriptor(copy, field);
if (descriptor && 'value' in descriptor && descriptor.configurable) {
Object.defineProperty(copy, field, { ...descriptor, writable: true });
}
}
return copy;
}
filter(condition: any): this {
this.filterCondition = condition;
return this;
}
limit(limit: number): this {
if (!Number.isSafeInteger(limit) || limit < 1) {
throw new Error('QUERY_INVALID_LIMIT: limit must be a positive safe integer');
}
this.limitValue = limit;
return this;
}
optimizeForContinuousPageFetch(): this {
return this.optimizeForContinuousPageFetchWith('default', 600);
}
optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
if (!namespace?.trim()) throw new Error('continuous page namespace must not be empty');
if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds <= 0) throw new Error('continuous page ttlSeconds must be a positive integer');
this.continuousPageFetchOptions = { namespace, ttlSeconds };
return this;
}
bindContinuousPageRuntime(runtime: any): this { this.continuousPageRuntimeContext = runtime; return this; }
localContinuousPageOptions(): { namespace: string; ttlSeconds: number } | undefined { return this.continuousPageFetchOptions; }
localContinuousPageRuntime(): any { return this.continuousPageRuntimeContext; }
clearContinuousPageRuntime(): this { this.continuousPageRuntimeContext = undefined; return this; }
optimizePaginationWithIdSet(): this {
return this.optimizePaginationWithIdSetConfig('default', 600, 3_000_000);
}
optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
if (!namespace?.trim()) throw new Error('ID set namespace must not be empty');
if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds <= 0) throw new Error('ID set ttlSeconds must be a positive integer');
if (!Number.isSafeInteger(maxIds) || maxIds <= 0) throw new Error('ID set maxIds must be a positive integer');
this.idSetPaginationOptions = { namespace, ttlSeconds, maxIds };
return this;
}
bindIdSetPaginationRuntime(runtime: any): this { this.idSetPaginationRuntimeContext = runtime; return this; }
localIdSetPaginationOptions(): { namespace: string; ttlSeconds: number; maxIds: number } | undefined { return this.idSetPaginationOptions; }
localIdSetPaginationRuntime(): any { return this.idSetPaginationRuntimeContext; }
clearIdSetPaginationRuntime(): this { this.idSetPaginationRuntimeContext = undefined; return this; }
topNProbeParentThreshold(threshold: number): this {
if (!Number.isSafeInteger(threshold) || threshold < 0) {
throw new Error('topNProbeParentThreshold must be a non-negative safe integer');
}
this.topNProbeThreshold = threshold;
return this;
}
localTopNProbeParentThreshold(): number | undefined {
return this.topNProbeThreshold;
}
prepareForList(): this {
if (!Number.isSafeInteger(this.offsetValue) || this.offsetValue < 0) {
throw new Error('QUERY_INVALID_OFFSET: offset must be a non-negative safe integer');
}
if (this.limitValue && (!Number.isSafeInteger(this.limitValue) || this.limitValue < 1)) {
throw new Error('QUERY_INVALID_LIMIT: limit must be a positive safe integer');
}
this.applyListLimit(this.hardLimitValue);
return this;
}
forExactCount(alias = '__teaql_total'): SelectQuery {
const count = new SelectQuery(this.entity);
count.filterCondition = snapshotQuery(this.filterCondition);
count.commentText = this.commentText;
count.purposeText = this.purposeText;
count.aggregate('Count', 'id', alias);
retainQueryDiagnosticOrigin(this, count);
return count;
}
private applyListLimit(ceiling: number): void {
if (!this.limitValue) this.limitValue = ceiling;
if (this.limitValue > ceiling) {
throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${ceiling}`);
}
for (const relation of this.relations) {
relation.query?.applyListLimit(10_000);
}
}
offset(offset: number): this {
if (!Number.isSafeInteger(offset) || offset < 0) {
throw new Error('QUERY_INVALID_OFFSET: offset must be a non-negative safe integer');
}
this.offsetValue = offset;
return this;
}
relation(name: string): this {
this.relations.push({ name });
return this;
}
relationQuery(
name: string,
query: SelectQuery,
localKey = 'id',
foreignKey = 'id',
many = true,
operation?: QueryOperation,
): this {
this.relations.push({ name, query, localKey, foreignKey, many, operation });
return this;
}
relationAggregate(
relationName: string,
alias: string,
query: SelectQuery,
singleResult = true,
operation?: QueryOperation,
): this {
this.relationAggregates.push({ relationName, alias, query, singleResult, operation });
return this;
}
order(orderBy: OrderBy): this {
this.orderItems.push(orderBy);
return this;
}
select(items: string[]): this {
this.selectItems.push(...items);
return this;
}
enableAggregationCacheFor(cacheExpiredMillis: number): this {
this.aggregationCache = AggregationCacheOptions.enabled(cacheExpiredMillis);
return this;
}
propagateAggregationCache(cacheExpiredMillis: number): this {
if (!this.aggregationCache) {
this.aggregationCache = AggregationCacheOptions.enabled(0);
}
this.aggregationCache.propagate(cacheExpiredMillis);
return this;
}
aggregate(functionName: string, field: string, alias: string): this {
this.aggregateItems.push({ function: functionName, field, alias });
return this;
}
groupBy(item: string): this {
this.groupByItems.push(item);
return this;
}
}
export class MutationQuery {
constructor(
public entity: string,
public action: "Create" | "Update" | "Delete",
public payload: any,
public id?: any,
public comment?: string,
public expectedVersion?: number,
) {}
}
|