diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-bootstrap.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..20d8cf0e877ba948bad013830c2e86f9235dbdd2 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Tenant } from './generated/models/Tenant'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.tenants().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Tenant.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Tenant Name"); + await domainRoot.auditAs('create generated Domain Root Tenant').save(context); + } + context.withActiveRoot({ entity: 'Tenant', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-search-models.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b8a61d24c79df272f7d00943ad8ca01c252fac8 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated-search-models.ts @@ -0,0 +1,90 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Tenant": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "purchaseOrderList": "PurchaseOrder", + "orderItemList": "OrderItem", + }), + }), + "PurchaseOrder": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "tenant": "integer" as const, + "contact_phone": "string" as const, + "contactPhone": "string" as const, + "internal_note": "string" as const, + "internalNote": "string" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "tenant": "tenant", + "contact_phone": "contactPhone", + "contactPhone": "contactPhone", + "internal_note": "internalNote", + "internalNote": "internalNote", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "tenant": "Tenant", + "orderItemList": "OrderItem", + }), + }), + "OrderItem": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "purchase_order": "integer" as const, + "purchaseOrder": "integer" as const, + "tenant": "integer" as const, + "product_name": "string" as const, + "productName": "string" as const, + "unit_price": "decimal" as const, + "unitPrice": "decimal" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "purchase_order": "purchaseOrder", + "purchaseOrder": "purchaseOrder", + "tenant": "tenant", + "product_name": "productName", + "productName": "productName", + "unit_price": "unitPrice", + "unitPrice": "unitPrice", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "purchase_order": "PurchaseOrder", + "purchaseOrder": "PurchaseOrder", + "tenant": "Tenant", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f527a3b276f22c4ee396914d7cfec95f5867555 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts @@ -0,0 +1,985 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { OrderItem } from '../models/OrderItem'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class OrderItemRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("OrderItem"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "OrderItem" { + return "OrderItem"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableOrderItemRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableOrderItemRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "purchaseOrder", "tenant", "productName", "unitPrice", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + + selectProductName(): this { + this.query.select(["productName"]); + return this; + } + + selectUnitPrice(): this { + this.query.select(["unitPrice"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPurchaseOrderWith(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.query.select(["purchaseOrder"]); + this.query.relationQuery( + "purchaseOrder", request.toQuery(), "purchaseOrder", "id", false, + { kind: "relation-select", method: "selectPurchaseOrderWith", relation: "purchaseOrder" }); + return this; + } + selectTenantWith(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.query.select(["tenant"]); + this.query.relationQuery( + "tenant", request.toQuery(), "tenant", "id", false, + { kind: "relation-select", method: "selectTenantWith", relation: "tenant" }); + return this; + } + + withPurchaseOrderMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "purchaseOrder": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPurchaseOrderMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "purchaseOrder": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.filters.push({ + "tenant": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.filters.push({ + "tenant": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByPurchaseOrder(val: any): this { + this.filters.push({ "purchaseOrder": { "$eq": val } }); + return this; + } + + filterByPurchaseOrderIn(...vals: any[]): this { + this.filters.push({ "purchaseOrder": { "$in": vals } }); + return this; + } + + withPurchaseOrderIsKnown(): this { + this.filters.push({ "purchaseOrder": { "$isNull": false } }); + return this; + } + + withPurchaseOrderIsUnknown(): this { + this.filters.push({ "purchaseOrder": { "$isNull": true } }); + return this; + } + + filterByTenant(val: any): this { + this.filters.push({ "tenant": { "$eq": val } }); + return this; + } + + filterByTenantIn(...vals: any[]): this { + this.filters.push({ "tenant": { "$in": vals } }); + return this; + } + + withTenantIsKnown(): this { + this.filters.push({ "tenant": { "$isNull": false } }); + return this; + } + + withTenantIsUnknown(): this { + this.filters.push({ "tenant": { "$isNull": true } }); + return this; + } + + withProductNameContaining(val: string): this { + this.filters.push({ "productName": { "$contains": val } }); + return this; + } + + withProductNameIs(val: string): this { + this.filters.push({ "productName": { "$eq": val } }); + return this; + } + + withProductNameIsNot(val: string): this { + this.filters.push({ "productName": { "$ne": val } }); + return this; + } + + withProductNameIn(...vals: string[]): this { + this.filters.push({ "productName": { "$in": vals } }); + return this; + } + + withProductNameNotIn(...vals: string[]): this { + this.filters.push({ "productName": { "$notIn": vals } }); + return this; + } + + withProductNameGreaterThan(val: string): this { + this.filters.push({ "productName": { "$gt": val } }); + return this; + } + + withProductNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "productName": { "$gte": val } }); + return this; + } + + withProductNameLessThan(val: string): this { + this.filters.push({ "productName": { "$lt": val } }); + return this; + } + + withProductNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "productName": { "$lte": val } }); + return this; + } + + withProductNameBetween(lower: string, upper: string): this { + this.filters.push({ "productName": { "$between": [lower, upper] } }); + return this; + } + + withProductNameIsKnown(): this { + this.filters.push({ "productName": { "$isNull": false } }); + return this; + } + + withProductNameIsUnknown(): this { + this.filters.push({ "productName": { "$isNull": true } }); + return this; + } + withProductNameNotContaining(val: string): this { + this.filters.push({ "productName": { "$notContains": val } }); + return this; + } + + withProductNameStartingWith(val: string): this { + this.filters.push({ "productName": { "$startsWith": val } }); + return this; + } + + withProductNameNotStartingWith(val: string): this { + this.filters.push({ "productName": { "$notStartsWith": val } }); + return this; + } + + withProductNameEndingWith(val: string): this { + this.filters.push({ "productName": { "$endsWith": val } }); + return this; + } + + withProductNameNotEndingWith(val: string): this { + this.filters.push({ "productName": { "$notEndsWith": val } }); + return this; + } + + withProductNameSoundingLike(val: string): this { + this.filters.push({ "productName": { "$soundLike": val } }); + return this; + } + + withUnitPriceIs(val: Decimal): this { + this.filters.push({ "unitPrice": { "$eq": val } }); + return this; + } + + withUnitPriceIsNot(val: Decimal): this { + this.filters.push({ "unitPrice": { "$ne": val } }); + return this; + } + + withUnitPriceIn(...vals: Decimal[]): this { + this.filters.push({ "unitPrice": { "$in": vals } }); + return this; + } + + withUnitPriceNotIn(...vals: Decimal[]): this { + this.filters.push({ "unitPrice": { "$notIn": vals } }); + return this; + } + + withUnitPriceGreaterThan(val: Decimal): this { + this.filters.push({ "unitPrice": { "$gt": val } }); + return this; + } + + withUnitPriceGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "unitPrice": { "$gte": val } }); + return this; + } + + withUnitPriceLessThan(val: Decimal): this { + this.filters.push({ "unitPrice": { "$lt": val } }); + return this; + } + + withUnitPriceLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "unitPrice": { "$lte": val } }); + return this; + } + + withUnitPriceBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "unitPrice": { "$between": [lower, upper] } }); + return this; + } + + withUnitPriceIsKnown(): this { + this.filters.push({ "unitPrice": { "$isNull": false } }); + return this; + } + + withUnitPriceIsUnknown(): this { + this.filters.push({ "unitPrice": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + + orderByProductNameAscending(): this { + this.query.orderBy("productName", "asc"); + return this; + } + + orderByProductNameDescending(): this { + this.query.orderBy("productName", "desc"); + return this; + } + + orderByUnitPriceAscending(): this { + this.query.orderBy("unitPrice", "asc"); + return this; + } + + orderByUnitPriceDescending(): this { + this.query.orderBy("unitPrice", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minUnitPrice(): this { + return this.minUnitPriceAs("minOfUnitPrice"); + } + + minUnitPriceAs(retName: string): this { + this.query.aggregate("min", "unitPrice", retName); + return this; + } + maxUnitPrice(): this { + return this.maxUnitPriceAs("maxOfUnitPrice"); + } + + maxUnitPriceAs(retName: string): this { + this.query.aggregate("max", "unitPrice", retName); + return this; + } + sumUnitPrice(): this { + return this.sumUnitPriceAs("sumOfUnitPrice"); + } + + sumUnitPriceAs(retName: string): this { + this.query.aggregate("sum", "unitPrice", retName); + return this; + } + avgUnitPrice(): this { + return this.avgUnitPriceAs("avgOfUnitPrice"); + } + + avgUnitPriceAs(retName: string): this { + this.query.aggregate("avg", "unitPrice", retName); + return this; + } + standardDeviationUnitPrice(): this { + return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice"); + } + + standardDeviationUnitPriceAs(retName: string): this { + this.query.aggregate("stddev", "unitPrice", retName); + return this; + } + squareRootOfPopulationStandardDeviationUnitPrice(): this { + return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice"); + } + + squareRootOfPopulationStandardDeviationUnitPriceAs(retName: string): this { + this.query.aggregate("stddev_pop", "unitPrice", retName); + return this; + } + sampleVarianceUnitPrice(): this { + return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice"); + } + + sampleVarianceUnitPriceAs(retName: string): this { + this.query.aggregate("var_samp", "unitPrice", retName); + return this; + } + samplePopulationVarianceUnitPrice(): this { + return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice"); + } + + samplePopulationVarianceUnitPriceAs(retName: string): this { + this.query.aggregate("var_pop", "unitPrice", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByPurchaseOrder(): this { + this.query.groupBy("purchaseOrder"); + return this; + } + + groupByPurchaseOrderAs(retName: string): this { + this.query.groupBy("purchaseOrder", retName); + return this; + } + groupByTenant(): this { + this.query.groupBy("tenant"); + return this; + } + + groupByTenantAs(retName: string): this { + this.query.groupBy("tenant", retName); + return this; + } + groupByProductName(): this { + this.query.groupBy("productName"); + return this; + } + + groupByProductNameAs(retName: string): this { + this.query.groupBy("productName", retName); + return this; + } + groupByUnitPrice(): this { + this.query.groupBy("unitPrice"); + return this; + } + + groupByUnitPriceAs(retName: string): this { + this.query.groupBy("unitPrice", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByPurchaseOrderAs( + facetName: string, + request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "purchaseOrder", request, includeAllFacets, + { kind: "facet", method: "facetByPurchaseOrderAs", relation: "purchaseOrder", alias: facetName }); + return this; + } + + facetByTenantAs( + facetName: string, + request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "tenant", request, includeAllFacets, + { kind: "facet", method: "facetByTenantAs", relation: "tenant", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof OrderItem + ? row + : OrderItem.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof OrderItem + ? row + : OrderItem.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof OrderItem + ? entity + : OrderItem.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableOrderItemRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderItem.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..5088eed5a2eabe328cd506f2b5687660dbbd79bd --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts @@ -0,0 +1,1064 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { PurchaseOrder } from '../models/PurchaseOrder'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class PurchaseOrderRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("PurchaseOrder"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "PurchaseOrder" { + return "PurchaseOrder"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePurchaseOrderRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutablePurchaseOrderRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "tenant", "contactPhone", "internalNote", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectContactPhone(): this { + this.query.select(["contactPhone"]); + return this; + } + + selectInternalNote(): this { + this.query.select(["internalNote"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTenantWith(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.query.select(["tenant"]); + this.query.relationQuery( + "tenant", request.toQuery(), "tenant", "id", false, + { kind: "relation-select", method: "selectTenantWith", relation: "tenant" }); + return this; + } + + withTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.filters.push({ + "tenant": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this { + this.filters.push({ + "tenant": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderItemList", request.toQuery(), "id", "purchaseOrder", true, + { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" }); + return this; + } + + haveOrderItems(): this { + return this.withOrderItemListMatching({ + entityName: "OrderItem", + toQuery: () => new SelectQuery("OrderItem"), + }); + } + + haveNoOrderItems(): this { + return this.withoutOrderItemListMatching({ + entityName: "OrderItem", + toQuery: () => new SelectQuery("OrderItem"), + }); + } + + withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "purchaseOrder", + }, + }, + }); + return this; + } + + withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "purchaseOrder", + }, + }, + }); + return this; + } + + countOrderItems(): this { + return this.countOrderItemsAs("countOrderItems"); + } + + countOrderItemsAs(alias: string): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias }; + return this; + } + + countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "relation-count", method: "countOrderItemsWith", relation: "orderItemList", alias }); + return this; + } + + minUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.minUnitPriceOfOrderItemsAs( + "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "minUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + maxUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.maxUnitPriceOfOrderItemsAs( + "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "maxUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + sumUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.sumUnitPriceOfOrderItemsAs( + "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "sumUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + avgUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.avgUnitPriceOfOrderItemsAs( + "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "avgUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + standardDeviationUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.standardDeviationUnitPriceOfOrderItemsAs( + "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "standardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs( + "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + sampleVarianceUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceUnitPriceOfOrderItemsAs( + "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + samplePopulationVarianceUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceUnitPriceOfOrderItemsAs( + "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTenant(val: any): this { + this.filters.push({ "tenant": { "$eq": val } }); + return this; + } + + filterByTenantIn(...vals: any[]): this { + this.filters.push({ "tenant": { "$in": vals } }); + return this; + } + + withTenantIsKnown(): this { + this.filters.push({ "tenant": { "$isNull": false } }); + return this; + } + + withTenantIsUnknown(): this { + this.filters.push({ "tenant": { "$isNull": true } }); + return this; + } + + withContactPhoneContaining(val: string): this { + this.filters.push({ "contactPhone": { "$contains": val } }); + return this; + } + + withContactPhoneIs(val: string): this { + this.filters.push({ "contactPhone": { "$eq": val } }); + return this; + } + + withContactPhoneIsNot(val: string): this { + this.filters.push({ "contactPhone": { "$ne": val } }); + return this; + } + + withContactPhoneIn(...vals: string[]): this { + this.filters.push({ "contactPhone": { "$in": vals } }); + return this; + } + + withContactPhoneNotIn(...vals: string[]): this { + this.filters.push({ "contactPhone": { "$notIn": vals } }); + return this; + } + + withContactPhoneGreaterThan(val: string): this { + this.filters.push({ "contactPhone": { "$gt": val } }); + return this; + } + + withContactPhoneGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "contactPhone": { "$gte": val } }); + return this; + } + + withContactPhoneLessThan(val: string): this { + this.filters.push({ "contactPhone": { "$lt": val } }); + return this; + } + + withContactPhoneLessThanOrEqualTo(val: string): this { + this.filters.push({ "contactPhone": { "$lte": val } }); + return this; + } + + withContactPhoneBetween(lower: string, upper: string): this { + this.filters.push({ "contactPhone": { "$between": [lower, upper] } }); + return this; + } + + withContactPhoneIsKnown(): this { + this.filters.push({ "contactPhone": { "$isNull": false } }); + return this; + } + + withContactPhoneIsUnknown(): this { + this.filters.push({ "contactPhone": { "$isNull": true } }); + return this; + } + withContactPhoneNotContaining(val: string): this { + this.filters.push({ "contactPhone": { "$notContains": val } }); + return this; + } + + withContactPhoneStartingWith(val: string): this { + this.filters.push({ "contactPhone": { "$startsWith": val } }); + return this; + } + + withContactPhoneNotStartingWith(val: string): this { + this.filters.push({ "contactPhone": { "$notStartsWith": val } }); + return this; + } + + withContactPhoneEndingWith(val: string): this { + this.filters.push({ "contactPhone": { "$endsWith": val } }); + return this; + } + + withContactPhoneNotEndingWith(val: string): this { + this.filters.push({ "contactPhone": { "$notEndsWith": val } }); + return this; + } + + withContactPhoneSoundingLike(val: string): this { + this.filters.push({ "contactPhone": { "$soundLike": val } }); + return this; + } + + withInternalNoteContaining(val: string): this { + this.filters.push({ "internalNote": { "$contains": val } }); + return this; + } + + withInternalNoteIs(val: string): this { + this.filters.push({ "internalNote": { "$eq": val } }); + return this; + } + + withInternalNoteIsNot(val: string): this { + this.filters.push({ "internalNote": { "$ne": val } }); + return this; + } + + withInternalNoteIn(...vals: string[]): this { + this.filters.push({ "internalNote": { "$in": vals } }); + return this; + } + + withInternalNoteNotIn(...vals: string[]): this { + this.filters.push({ "internalNote": { "$notIn": vals } }); + return this; + } + + withInternalNoteGreaterThan(val: string): this { + this.filters.push({ "internalNote": { "$gt": val } }); + return this; + } + + withInternalNoteGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "internalNote": { "$gte": val } }); + return this; + } + + withInternalNoteLessThan(val: string): this { + this.filters.push({ "internalNote": { "$lt": val } }); + return this; + } + + withInternalNoteLessThanOrEqualTo(val: string): this { + this.filters.push({ "internalNote": { "$lte": val } }); + return this; + } + + withInternalNoteBetween(lower: string, upper: string): this { + this.filters.push({ "internalNote": { "$between": [lower, upper] } }); + return this; + } + + withInternalNoteIsKnown(): this { + this.filters.push({ "internalNote": { "$isNull": false } }); + return this; + } + + withInternalNoteIsUnknown(): this { + this.filters.push({ "internalNote": { "$isNull": true } }); + return this; + } + withInternalNoteNotContaining(val: string): this { + this.filters.push({ "internalNote": { "$notContains": val } }); + return this; + } + + withInternalNoteStartingWith(val: string): this { + this.filters.push({ "internalNote": { "$startsWith": val } }); + return this; + } + + withInternalNoteNotStartingWith(val: string): this { + this.filters.push({ "internalNote": { "$notStartsWith": val } }); + return this; + } + + withInternalNoteEndingWith(val: string): this { + this.filters.push({ "internalNote": { "$endsWith": val } }); + return this; + } + + withInternalNoteNotEndingWith(val: string): this { + this.filters.push({ "internalNote": { "$notEndsWith": val } }); + return this; + } + + withInternalNoteSoundingLike(val: string): this { + this.filters.push({ "internalNote": { "$soundLike": val } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByContactPhoneAscending(): this { + this.query.orderBy("contactPhone", "asc"); + return this; + } + + orderByContactPhoneDescending(): this { + this.query.orderBy("contactPhone", "desc"); + return this; + } + + orderByInternalNoteAscending(): this { + this.query.orderBy("internalNote", "asc"); + return this; + } + + orderByInternalNoteDescending(): this { + this.query.orderBy("internalNote", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByTenant(): this { + this.query.groupBy("tenant"); + return this; + } + + groupByTenantAs(retName: string): this { + this.query.groupBy("tenant", retName); + return this; + } + groupByContactPhone(): this { + this.query.groupBy("contactPhone"); + return this; + } + + groupByContactPhoneAs(retName: string): this { + this.query.groupBy("contactPhone", retName); + return this; + } + groupByInternalNote(): this { + this.query.groupBy("internalNote"); + return this; + } + + groupByInternalNoteAs(retName: string): this { + this.query.groupBy("internalNote", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByTenantAs( + facetName: string, + request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "tenant", request, includeAllFacets, + { kind: "facet", method: "facetByTenantAs", relation: "tenant", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof PurchaseOrder + ? row + : PurchaseOrder.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof PurchaseOrder + ? row + : PurchaseOrder.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof PurchaseOrder + ? entity + : PurchaseOrder.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePurchaseOrderRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return PurchaseOrder.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1034747d7f4d70394f283a2d783d93a3dc18ae2f --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts @@ -0,0 +1,791 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Tenant } from '../models/Tenant'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class TenantRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Tenant"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "Tenant" { + return "Tenant"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTenantRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableTenantRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectPurchaseOrderListWith(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "purchaseOrderList", request.toQuery(), "id", "tenant", true, + { kind: "relation-select", method: "selectPurchaseOrderListWith", relation: "purchaseOrderList" }); + return this; + } + selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderItemList", request.toQuery(), "id", "tenant", true, + { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" }); + return this; + } + + havePurchaseOrders(): this { + return this.withPurchaseOrderListMatching({ + entityName: "PurchaseOrder", + toQuery: () => new SelectQuery("PurchaseOrder"), + }); + } + + haveNoPurchaseOrders(): this { + return this.withoutPurchaseOrderListMatching({ + entityName: "PurchaseOrder", + toQuery: () => new SelectQuery("PurchaseOrder"), + }); + } + + withPurchaseOrderListMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "tenant", + }, + }, + }); + return this; + } + + withoutPurchaseOrderListMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "tenant", + }, + }, + }); + return this; + } + haveOrderItems(): this { + return this.withOrderItemListMatching({ + entityName: "OrderItem", + toQuery: () => new SelectQuery("OrderItem"), + }); + } + + haveNoOrderItems(): this { + return this.withoutOrderItemListMatching({ + entityName: "OrderItem", + toQuery: () => new SelectQuery("OrderItem"), + }); + } + + withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "tenant", + }, + }, + }); + return this; + } + + withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "tenant", + }, + }, + }); + return this; + } + + countPurchaseOrders(): this { + return this.countPurchaseOrdersAs("countPurchaseOrders"); + } + + countPurchaseOrdersAs(alias: string): this { + const query = new SelectQuery("PurchaseOrder").filter({ version: { "$gte": 1 } }); + this.countPurchaseOrdersWith(alias, { entityName: "PurchaseOrder", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countPurchaseOrdersAs", relation: "purchaseOrderList", alias }; + return this; + } + + countPurchaseOrdersWith(alias: string, child: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("purchaseOrderList", alias, query, true, + { kind: "relation-count", method: "countPurchaseOrdersWith", relation: "purchaseOrderList", alias }); + return this; + } + + + countOrderItems(): this { + return this.countOrderItemsAs("countOrderItems"); + } + + countOrderItemsAs(alias: string): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias }; + return this; + } + + countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "relation-count", method: "countOrderItemsWith", relation: "orderItemList", alias }); + return this; + } + + minUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.minUnitPriceOfOrderItemsAs( + "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "minUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + maxUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.maxUnitPriceOfOrderItemsAs( + "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "maxUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + sumUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.sumUnitPriceOfOrderItemsAs( + "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "sumUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + avgUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.avgUnitPriceOfOrderItemsAs( + "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "avgUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + standardDeviationUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.standardDeviationUnitPriceOfOrderItemsAs( + "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "standardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs( + "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + sampleVarianceUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceUnitPriceOfOrderItemsAs( + "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + samplePopulationVarianceUnitPriceOfOrderItems(): this { + const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceUnitPriceOfOrderItemsAs( + "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); + } + + samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "unitPrice", alias); + this.query.relationAggregate("orderItemList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Tenant + ? row + : Tenant.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Tenant + ? row + : Tenant.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Tenant + ? entity + : Tenant.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTenantRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Tenant.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/runtime-module.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..ece4ea758f51082985b0718923392910c44b12a6 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/runtime-module.ts @@ -0,0 +1,170 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Tenant": Object.freeze({ + entityType: "Tenant", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "PurchaseOrder": Object.freeze({ + entityType: "PurchaseOrder", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "tenant": Object.freeze({ canonicalName: "tenant", wireName: "tenant", aliases: Object.freeze([] as string[]) }), + "contact_phone": Object.freeze({ canonicalName: "contact_phone", wireName: "contactPhone", aliases: Object.freeze([] as string[]) }), + "internal_note": Object.freeze({ canonicalName: "internal_note", wireName: "internalNote", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "OrderItem": Object.freeze({ + entityType: "OrderItem", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "purchase_order": Object.freeze({ canonicalName: "purchase_order", wireName: "purchaseOrder", aliases: Object.freeze([] as string[]) }), + "tenant": Object.freeze({ canonicalName: "tenant", wireName: "tenant", aliases: Object.freeze([] as string[]) }), + "product_name": Object.freeze({ canonicalName: "product_name", wireName: "productName", aliases: Object.freeze([] as string[]) }), + "unit_price": Object.freeze({ canonicalName: "unit_price", wireName: "unitPrice", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Tenant": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && !([...String(mutation.payload["name"])].length >= 1)) results.push({ ruleId: "min_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 1 }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 80) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 80 }); + + + }, + }, + "PurchaseOrder": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create") { + const root = context.requireActiveRoot("Tenant"); + const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"]; + if (supplied == null) { + mutation.payload["tenant"] = root.id; + context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "tenant", source: "context", sourceLabel: "activeRoot:Tenant" }); + } + else if (String(supplied) !== String(root.id)) results.push({ ruleId: "context_root_mismatch", location: ObjectLocation.property("tenant"), inputValue: supplied, systemValue: root.id, message: "Context-bound root must match the active context" }); + } else if (mutation.action === "Update" || mutation.action === "Delete" || mutation.action === "Recover") { + const root = context.requireActiveRoot("Tenant"); + const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"]; + const original = mutation.loadedValues?.["tenant"]?.id ?? mutation.loadedValues?.["tenant"]; + if (original == null) results.push({ ruleId: "invalid_type", location: ObjectLocation.property("tenant"), message: "Mutation requires a loaded context-bound root" }); + else if (String(original) !== String(root.id) || (supplied != null && String(supplied) !== String(root.id))) results.push({ ruleId: "context_root_mismatch", location: ObjectLocation.property("tenant"), inputValue: supplied ?? original, systemValue: root.id, message: "Context-bound root must match the active context" }); + } + + + + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["tenant"] === undefined) || mutation.payload["tenant"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("tenant") }); + + if ((mutation.action === "Create" && mutation.payload["contact_phone"] === undefined) || mutation.payload["contact_phone"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("contact_phone") }); + if (mutation.payload["contact_phone"] != null && !([...String(mutation.payload["contact_phone"])].length >= 1)) results.push({ ruleId: "min_length", location: ObjectLocation.property("contact_phone"), inputValue: mutation.payload["contact_phone"], systemValue: 1 }); + if (mutation.payload["contact_phone"] != null && [...String(mutation.payload["contact_phone"])].length > 32) results.push({ ruleId: "max_length", location: ObjectLocation.property("contact_phone"), inputValue: mutation.payload["contact_phone"], systemValue: 32 }); + + if (mutation.payload["internal_note"] != null && [...String(mutation.payload["internal_note"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("internal_note"), inputValue: mutation.payload["internal_note"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "OrderItem": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create") { + const root = context.requireActiveRoot("Tenant"); + const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"]; + if (supplied == null) { + mutation.payload["tenant"] = root.id; + context.recordFixEvidence({ entityType: "OrderItem", modelPath: "tenant", source: "context", sourceLabel: "activeRoot:Tenant" }); + } + else if (String(supplied) !== String(root.id)) results.push({ ruleId: "context_root_mismatch", location: ObjectLocation.property("tenant"), inputValue: supplied, systemValue: root.id, message: "Context-bound root must match the active context" }); + } else if (mutation.action === "Update" || mutation.action === "Delete" || mutation.action === "Recover") { + const root = context.requireActiveRoot("Tenant"); + const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"]; + const original = mutation.loadedValues?.["tenant"]?.id ?? mutation.loadedValues?.["tenant"]; + if (original == null) results.push({ ruleId: "invalid_type", location: ObjectLocation.property("tenant"), message: "Mutation requires a loaded context-bound root" }); + else if (String(original) !== String(root.id) || (supplied != null && String(supplied) !== String(root.id))) results.push({ ruleId: "context_root_mismatch", location: ObjectLocation.property("tenant"), inputValue: supplied ?? original, systemValue: root.id, message: "Context-bound root must match the active context" }); + } + + + + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "OrderItem", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "OrderItem", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "OrderItem", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["purchase_order"] === undefined) || mutation.payload["purchase_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("purchase_order") }); + + if ((mutation.action === "Create" && mutation.payload["tenant"] === undefined) || mutation.payload["tenant"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("tenant") }); + + if ((mutation.action === "Create" && mutation.payload["product_name"] === undefined) || mutation.payload["product_name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("product_name") }); + if (mutation.payload["product_name"] != null && !([...String(mutation.payload["product_name"])].length >= 1)) results.push({ ruleId: "min_length", location: ObjectLocation.property("product_name"), inputValue: mutation.payload["product_name"], systemValue: 1 }); + if (mutation.payload["product_name"] != null && [...String(mutation.payload["product_name"])].length > 80) results.push({ ruleId: "max_length", location: ObjectLocation.property("product_name"), inputValue: mutation.payload["product_name"], systemValue: 80 }); + + if ((mutation.action === "Create" && mutation.payload["unit_price"] === undefined) || mutation.payload["unit_price"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("unit_price") }); + if (mutation.payload["unit_price"] != null && compareDecimals(String(mutation.payload["unit_price"]), "0.01") === -1) results.push({ ruleId: "min", location: ObjectLocation.property("unit_price"), inputValue: mutation.payload["unit_price"], systemValue: 0.01 }); + if (mutation.payload["unit_price"] != null && compareDecimals(String(mutation.payload["unit_price"]), "1000000") > 0) results.push({ ruleId: "max", location: ObjectLocation.property("unit_price"), inputValue: mutation.payload["unit_price"], systemValue: 1000000 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Tenant", id: "1", values: { "name": "Tenant Name" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sql.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..415f2afaf8499d5e22d76cb24fd41d5419bb4b06 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sql.ts @@ -0,0 +1,22 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Tenant": { + table: "tenant_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"purchaseOrderList": { targetEntity: "PurchaseOrder", localKey: "id", foreignKey: "tenant", many: true }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "tenant", many: true }} +}, +"PurchaseOrder": { + table: "purchase_order_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "tenant": { columnName: "tenant", modelName: "tenant", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "contactPhone": { columnName: "contact_phone", modelName: "contact_phone", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "internalNote": { columnName: "internal_note", modelName: "internal_note", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"tenant": { targetEntity: "Tenant", localKey: "tenant", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "purchaseOrder", many: true }} +}, +"OrderItem": { + table: "order_item_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "purchaseOrder": { columnName: "purchase_order", modelName: "purchase_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "tenant": { columnName: "tenant", modelName: "tenant", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"purchaseOrder": { targetEntity: "PurchaseOrder", localKey: "purchaseOrder", foreignKey: "id", many: false }, "tenant": { targetEntity: "Tenant", localKey: "tenant", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-ts.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/teaql-i18n.json b/source/teaql-ts/examples/fix-e-alignment/generated/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..9964fc5dc1df5011d3efc62e938482fd173e75c1 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/teaql-i18n.json @@ -0,0 +1,117 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.orderItem.id": "Id", + "property.orderItem.createTime": "Create Time", + "property.purchaseOrder.id": "Id", + "property.orderItem.purchaseOrder": "Purchase Order", + "entity.orderItem": "Order Item", + "property.purchaseOrder.tenant": "Tenant", + "property.purchaseOrder.updateTime": "Update Time", + "property.orderItem.unitPrice": "Unit Price", + "property.purchaseOrder.internalNote": "Internal Note", + "property.tenant.id": "Id", + "property.orderItem.productName": "Product Name", + "entity.purchaseOrder": "Purchase Order", + "property.orderItem.tenant": "Tenant", + "property.orderItem.version": "Version", + "property.orderItem.updateTime": "Update Time", + "property.purchaseOrder.contactPhone": "Contact Phone", + "property.purchaseOrder.version": "Version", + "property.purchaseOrder.createTime": "Create Time", + "property.tenant.name": "Name", + "property.tenant.version": "Version", + "entity.tenant": "Tenant" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/tsconfig.json b/source/teaql-ts/examples/fix-e-alignment/generated/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/graph-fix-idempotence.test.ts b/source/teaql-ts/examples/fix-e-alignment/graph-fix-idempotence.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..73e4dbe967f737e593c936f6a0abbe0bec4e3527 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/graph-fix-idempotence.test.ts @@ -0,0 +1,112 @@ +import {CheckException, decimal, FixedBusinessClock, UserContext} from '../../src'; +import {Q} from 'generated/generated/Q'; +import {E} from 'generated/generated/E'; +import {SQLiteTeaQLClient} from 'generated/teaql-node-sqlite'; + +const emit = (name: string, facts: unknown) => process.stdout.write('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE=' + JSON.stringify({case: name, facts}) + '\n'); +const database = process.env.TEAQL_FIX_E_DB! + '.idempotence.sqlite'; +const instant = Date.parse('2033-01-02T03:04:05Z'); +async function setup(filename: string) { + const context = new UserContext().withActiveRoot({entity: 'Tenant', id: '1'}) + .withBusinessClock(new FixedBusinessClock(new Date(instant))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context).setDiagnosticSQLLogSink(undefined); + context.insertResource('dataService', client); await context.ensureSchema(); + return {context, client, driver: (client as any).driver}; +} +async function make(context: UserContext, label: string) { + const parent = (await Q.purchaseOrders().comment('Prepare the graph owner ' + label).purpose('Verify Fix traversal identity') + .newEntity(context)).updateContactPhone('5550140'); + const child = (await Q.orderItems().comment('Prepare the graph child ' + label).purpose('Verify one entity Fix per graph') + .newEntity(context)).updateProductName(label).updateUnitPrice(decimal('12.34')); + parent.orderItemList().push(child); return {parent, child}; +} +function observe(client: SQLiteTeaQLClient, context: UserContext) { + const driver = (client as any).driver, checkers = (client as any).checkers; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'), allocation = jest.spyOn(driver, 'nextId'); + const effects = () => [query.mock.calls.length, transaction.mock.calls.length, allocation.mock.calls.length]; + const visits: Array<{entity: string; action: string; time: number; providerCallsDuringFix: number}> = []; + for (const type of ['PurchaseOrder', 'OrderItem']) { + const delegate = checkers[type]; checkers[type] = {checkAndFix(ctx: UserContext, mutation: any, results: any[]) { + const before = effects(); delegate.checkAndFix(ctx, mutation, results); + expect(effects()).toEqual(before); + visits.push({entity: type, action: mutation.action, time: context.requireResource('fixTime').getTime(), providerCallsDuringFix: 0}); + }}; + } + return {visits, effects, transaction, clear: () => {visits.length = 0; query.mockClear(); transaction.mockClear(); allocation.mockClear();}}; +} + +test('the same child instance reached twice is fixed and persisted once per invocation', async () => { + const filename = database, round = Number(process.env.TEAQL_FIX_E_ROUND); + const {client, context} = await setup(filename), observed = observe(client, context); + let tick = instant + round * 1000; const created = tick; + context.withBusinessClock({now: () => new Date(tick++)}); + try { + const {parent, child} = (await make(context, 'Repeated child')); parent.orderItemList().push(child); + let failure: unknown; + try {await parent.auditAs('Create with repeated references to one child instance').save(context);} catch (error) {failure = error;} + const createFacts = {round, visits: [...observed.visits], clockCaptures: tick - created, providerEffects: observed.effects(), + error: failure instanceof Error ? {name: failure.name, code: (failure as any).code ?? null, + violations: failure instanceof CheckException ? failure.violations.map(v => ({ruleId: v.ruleId, path: v.location.modelPath()})) : []} : null, + scopeReleased: context.getResource('fixTime') === undefined && context.getResource('fixEvidenceCurrent') === undefined}; + emit('duplicate-create', createFacts); + if (failure) throw failure; + expect(createFacts.visits.map(v => v.entity)).toEqual(['PurchaseOrder', 'OrderItem']); + expect(createFacts.visits.every(v => v.time === created && v.providerCallsDuringFix === 0)).toBe(true); + expect(tick).toBe(created + 1); expect(createFacts.scopeReleased).toBe(true); + parent.updateContactPhone('5550141'); child.updateUnitPrice(decimal('23.45')); observed.clear(); const updated = tick; + await parent.auditAs('Update the same repeated child once at a new graph instant').save(context); + expect(observed.visits.map(v => v.entity)).toEqual(['PurchaseOrder', 'OrderItem']); expect(observed.visits.every(v => v.time === updated)).toBe(true); + expect(tick).toBe(created + 2); expect(context.getResource('fixTime')).toBeUndefined(); expect(context.getResource('fixEvidenceCurrent')).toBeUndefined(); + const owner = (await Q.purchaseOrders().withIdIs(parent.id!).limit(1).comment('Reload the deduplicated owner').purpose('Verify persisted Fix values').executeForList(context))[0]; + const item = (await Q.orderItems().withIdIs(child.id!).limit(1).comment('Reload the deduplicated child').purpose('Verify once-only persistence').executeForList(context))[0]; + expect(E.purchaseOrder(owner).version().eval()).toBe(2); expect(E.orderItem(item).version().eval()).toBe(2); + expect(new Date(E.orderItem(item).createTime().eval()!).getTime()).toBe(created); expect(new Date(E.orderItem(item).updateTime().eval()!).getTime()).toBe(updated); + expect(E.orderItem(item).productName().eval()).toBe('Repeated child'); expect(E.purchaseOrder(owner).contactPhone().eval()).toBe('5550141'); + emit('duplicate-update', {round, visits: [...observed.visits], clockCaptures: 1, created, updated, parentId: parent.id, childId: child.id, version: 2}); + } finally {await client.close();} +}); + +test('overlapping real generated graphs on separate contexts keep their own snapshot and receipt', async () => { + const filename = database, round = Number(process.env.TEAQL_FIX_E_ROUND); + const first = await setup(filename + '.first.sqlite'), second = await setup(filename + '.second.sqlite'); + const a = observe(first.client, first.context), b = observe(second.client, second.context); + let tick = instant + round * 2000; const firstInstant = tick; + const clock = {now: () => new Date(tick++)}; first.context.withBusinessClock(clock); second.context.withBusinessClock(clock); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => {entered = resolve;}), hold = new Promise(resolve => {release = resolve;}); + const transaction = first.driver.transaction.bind(first.driver); + let pending: Promise | undefined; + try { + const left = (await make(first.context, 'First context')), right = (await make(second.context, 'Second context')); + // Creation reserves IDs in its own transaction. Hold only the save boundary. + a.transaction.mockImplementationOnce(async (work: any) => {entered(); await hold; return transaction(work);}); + pending = left.parent.auditAs('Hold the first generated graph before provider entry').save(first.context); + await Promise.race([ready, pending.then(() => {throw Error('first graph finished without reaching the held transaction');})]); + const receipt = first.context.getResource('fixEvidenceCurrent'); expect(receipt).toBeDefined(); + await right.parent.auditAs('Commit another generated graph on an independent context').save(second.context); + expect(first.context.requireResource('fixTime').getTime()).toBe(firstInstant); expect(first.context.getResource('fixEvidenceCurrent')).toBe(receipt); + release(); await pending; + expect(a.visits.map(v => v.time)).toEqual([firstInstant, firstInstant]); expect(b.visits.map(v => v.time)).toEqual([firstInstant + 1, firstInstant + 1]); expect(tick).toBe(firstInstant + 2); + for (const c of [first.context, second.context]) {expect(c.getResource('fixTime')).toBeUndefined(); expect(c.getResource('fixEvidenceCurrent')).toBeUndefined(); expect(Object.isFrozen(c.lastFixEvidence())).toBe(true);} + emit('independent-real-graphs', {round, first: [...a.visits], second: [...b.visits], clockCaptures: 2, heldEvidencePreserved: true, scopesReleased: true, + receiptsIndependent: first.context.lastFixEvidence() !== second.context.lastFixEvidence()}); + } finally {release(); if (pending) await pending.catch(() => undefined); await first.client.close(); await second.client.close();} +}); + +test('different object views of one ID are not silently skipped by the identity traversal guard', async () => { + const {client, context} = await setup(database + '.identity.sqlite'); + const observed = observe(client, context), {parent, child} = (await make(context, 'Distinct views')); + try { + await parent.auditAs('Create a baseline for duplicate identity protection').save(context); + const other = (await Q.orderItems().withIdIs(child.id!).limit(1).comment('Load a separate child view').purpose('Do not confuse object identity with entity ID').executeForList(context))[0]; + expect(other).not.toBe(child); expect(other.id).toBe(child.id); + child.updateUnitPrice(decimal('23.45')); other.updateUnitPrice(decimal('34.56')); parent.orderItemList().push(other); observed.clear(); + let failure: unknown; + try {await parent.auditAs('Reject two conflicting views rather than skip by ID').save(context);} catch (error) {failure = error;} + expect(failure).toBeInstanceOf(CheckException); expect((failure as CheckException).violations.some(v => v.ruleId === 'mutation_changed_after_preparation')).toBe(true); + expect(observed.effects()).toEqual([0, 0, 0]); + const persisted = (await Q.orderItems().withIdIs(child.id!).limit(1).comment('Verify rejected duplicate identity left storage intact').purpose('Validate the traversal guard does not hide conflicting views').executeForList(context))[0]; + expect(E.orderItem(persisted).version().eval()).toBe(1); expect(String(E.orderItem(persisted).unitPrice().eval())).toBe('12.34'); + emit('distinct-views-same-id-rejected', {round: Number(process.env.TEAQL_FIX_E_ROUND), rejectedBeforeProvider: true, sameEntityId: true, distinctObjectInstances: true, persistedVersion: 1, persistedPrice: '12.34'}); + } finally {await client.close();} +}); diff --git a/source/teaql-ts/examples/fix-e-alignment/loading-probe.ts b/source/teaql-ts/examples/fix-e-alignment/loading-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b60064381e508709d8433efcc1b5c0ee8f3b6bf --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/loading-probe.ts @@ -0,0 +1,55 @@ +import { CheckException, TeaQLNotLoadedError, UserContext } from '../../src'; +import { E } from 'generated/generated/E'; +import { Q } from 'generated/generated/Q'; + +export async function verifyLoading(context: UserContext, + orderId: Parameters['withIdIs']>[0]): Promise { + const rows = await Q.purchaseOrders().withIdIs(orderId) + .selectTenantWith(Q.tenantsWithMinimalFields().withIdIs('2').limit(1) + .comment("Load only a different tenant's detail")) + .limit(1).comment('Keep the selected FK when target detail is filtered out') + .purpose('Verify filtered target detail is NotLoaded rather than loaded null').executeForList(context); + expect(rows).toHaveLength(1); + const owner = rows[0]; + expect(String(E.purchaseOrder(owner).tenantId().eval())).toBe('1'); + let detail: ReturnType | undefined; + try { E.purchaseOrder(owner).tenant().name().eval(); } + catch (error) { + if (!(error instanceof TeaQLNotLoadedError)) throw error; + detail = error.toWire(); + expect(detail.code).toBe('NOT_LOADED'); + expect(detail.attemptedInstancePath).toBe('/tenant/name'); + } + expect(detail).toBeDefined(); + owner.updateContactPhone('5550102'); + await owner.auditAs('Change only the complete owner').save(context); + const complete = await Q.purchaseOrders().withIdIs(orderId).limit(1) + .comment('Reload the successful owner update') + .purpose('Verify untouched partial targets do not prevent saving the owner').executeForList(context); + expect(complete).toHaveLength(1); + expect(E.purchaseOrder(complete[0]).contactPhone().eval()).toBe('5550102'); + const version = E.purchaseOrder(complete[0]).version().eval(); + const partial = await Q.purchaseOrdersWithMinimalFields().withIdIs(orderId).limit(1) + .comment('Load an identity-only owner') + .purpose('Reject changes to an incomplete owner before persistence').executeForList(context); + expect(partial).toHaveLength(1); + partial[0].updateContactPhone('5550103'); + let rejected = false; + try { await partial[0].auditAs('Attempt to modify an incomplete owner').save(context); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + expect(error.violations.some(result => result.ruleId === 'invalid_type')).toBe(true); + rejected = true; + } + expect(rejected).toBe(true); + const unchanged = await Q.purchaseOrders().withIdIs(orderId).limit(1) + .comment('Reload after the rejected incomplete mutation') + .purpose('Verify persisted values and optimistic version remain unchanged').executeForList(context); + expect(unchanged).toHaveLength(1); + expect(E.purchaseOrder(unchanged[0]).contactPhone().eval()).toBe('5550102'); + expect(E.purchaseOrder(unchanged[0]).version().eval()).toEqual(version); + process.stdout.write('CORE_LOAD_EXAMPLE=' + JSON.stringify({ + language: 'typescript', passed: true, foreignKeyPreserved: true, filteredDetailNotLoaded: detail, + untouchedPartialTargetSave: true, modifiedPartialOwnerRejected: true, rejectedVersionUnchanged: true, + }) + '\n'); +} diff --git a/source/teaql-ts/examples/fix-e-alignment/model.xml b/source/teaql-ts/examples/fix-e-alignment/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..72bd684f70bf30bc88754ffef4e0a008a259865f --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/model.xml @@ -0,0 +1,17 @@ + + + + + + diff --git a/source/teaql-ts/examples/fix-e-alignment/owned-command.cjs b/source/teaql-ts/examples/fix-e-alignment/owned-command.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8470e4157ce4ea2e2a8c86108714b4353f6f1e0a --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/owned-command.cjs @@ -0,0 +1,79 @@ +"use strict"; +// POSIX compiler/test runner. The detached group belongs only to this command; +// no service, shared cache or other session is a termination target. +const cp = require('node:child_process'); +const fs = require('node:fs'), path = require('node:path'); +const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)); +function alive(pid) { + try { process.kill(-pid, 0); return true; } + catch (error) { if (error.code === 'ESRCH') return false; throw error; } +} +function signal(pid, name) { + if (!pid) return; + try { process.kill(-pid, name); } + catch (error) { if (error.code !== 'ESRCH') throw error; } +} +function createOwnedRunner() { + let active, interrupted, unsafeGroup, killer; + const terminateActive = () => { + if (!active?.pid) return; + signal(active.pid, 'SIGTERM'); + killer ||= setTimeout(() => { if (active?.pid) signal(active.pid, 'SIGKILL'); }, 500); + }; + const cancel = name => { + interrupted ||= name; + terminateActive(); + }; + const onInt = () => cancel('SIGINT'), onTerm = () => cancel('SIGTERM'); + process.on('SIGINT', onInt); process.on('SIGTERM', onTerm); + return { + get interrupted() { return interrupted; }, + get unsafeGroup() { return unsafeGroup; }, + get safeToClean() { return !active && !unsafeGroup; }, + cancel, + async run(command, options) { + if (active) throw new Error('owned commands must be awaited, not overlapped'); + if (interrupted) return {status: interrupted === 'SIGINT' ? 130 : 143, signal: interrupted}; + let timedOut = false, timer; + const {timeout, ...spawnOptions} = options; + const child = cp.spawn(command[0], command.slice(1), {...spawnOptions, detached: true}); + active = child; + try { + const result = await new Promise(resolve => { + child.once('error', error => resolve({status: null, signal: null, error: error.message})); + child.once('close', (status, childSignal) => resolve({status, signal: childSignal})); + timer = setTimeout(() => { timedOut = true; terminateActive(); }, timeout); + }); + clearTimeout(timer); + // Reap the direct child and stop any compiler descendants which outlive + // it. Keep signal handlers installed until the complete owned group ends. + if (child.pid && alive(child.pid)) { + signal(child.pid, 'SIGTERM'); + for (let attempt = 0; attempt < 100 && alive(child.pid); attempt++) { + if (attempt === 10) signal(child.pid, 'SIGKILL'); + await delay(25); + } + if (alive(child.pid)) { unsafeGroup = child.pid; throw new Error('owned process group remains live: ' + child.pid); } + } + if (timedOut) return {...result, status: 124}; + if (interrupted) return {...result, status: interrupted === 'SIGINT' ? 130 : 143}; + return result; + } finally { clearTimeout(timer); clearTimeout(killer); killer = undefined; active = undefined; } + }, + dispose() { + if (active) throw new Error('cannot dispose a live owned command'); + process.off('SIGINT', onInt); process.off('SIGTERM', onTerm); + }, + }; +} +function ownedBytes(directory) { + const seen = new Set(); + function visit(file) { + const stat = fs.lstatSync(file), key = stat.dev + ':' + stat.ino; + if (seen.has(key)) return 0; + seen.add(key); + return stat.size + (stat.isDirectory() ? fs.readdirSync(file).reduce((sum, name) => sum + visit(path.join(file, name)), 0) : 0); + } + return visit(directory); +} +module.exports = {createOwnedRunner, alive, ownedBytes}; diff --git a/source/teaql-ts/examples/fix-e-alignment/ownership-probe.ts b/source/teaql-ts/examples/fix-e-alignment/ownership-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..6caad8df9b89121efb5ad1af9a5737969933c50b --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/ownership-probe.ts @@ -0,0 +1,41 @@ +import { UserContext } from '../../src'; +import { E } from 'generated/generated/E'; +import { Q } from 'generated/generated/Q'; +import { verifyPageStream } from './paged-ownership'; + +export async function verifyOwnership(context: UserContext): Promise { + const before = await Q.purchaseOrders().limit(20).comment('Inspect the initial ownership fixture') + .purpose('Verify Context and multi-root results do not own shared mutation ledgers').executeForList(context); + const first = (await Q.purchaseOrders().comment('Prepare independent new owner A') + .purpose('Verify Context does not own mutation ledgers').newEntity(context)); + const second = (await Q.purchaseOrders().comment('Prepare independent new owner B') + .purpose('Verify Context does not own mutation ledgers').newEntity(context)); + first.updateContactPhone('5550300'); second.updateContactPhone('5550400'); + const savedA = await first.auditAs('Save only independent new owner A').save(context); + const initial = await Q.purchaseOrders().limit(20).comment("Inspect A's save before saving B") + .purpose('Verify an independent new owner did not leak into persistence').executeForList(context); + expect(initial).toHaveLength(before.length + 1); + const savedB = await second.auditAs('Explicitly save independent new owner B').save(context); + const batch = await Q.purchaseOrders().limit(20).comment('Load independent owners in one batch') + .purpose('Verify independently saveable list roots retain separate mutation boundaries').executeForList(context); + expect(batch).toHaveLength(before.length + 2); + const ownerA = batch.find(row => row.id === savedA.id)!; + const ownerB = batch.find(row => row.id === savedB.id)!; + expect(ownerA).toBeDefined(); expect(ownerB).toBeDefined(); + ownerA.updateContactPhone('5550301'); ownerB.updateContactPhone('5550401'); + await ownerA.auditAs('Save only A from a multi-root query result').save(context); + const unchanged = (await Q.purchaseOrders().withIdIs(savedB.id!).limit(1) + .comment('Inspect B after saving only A').purpose('Verify A neither persists nor commits B').executeForList(context))[0]; + expect(E.purchaseOrder(unchanged).contactPhone().eval()).toBe('5550400'); + expect(E.purchaseOrder(unchanged).version().eval()).toBe(1); + await ownerB.auditAs('Save B after A without discarding its pending mutation').save(context); + const changed = (await Q.purchaseOrders().withIdIs(savedB.id!).limit(1) + .comment('Inspect the later independent B save').purpose("Verify B's pending mutation survived A's save").executeForList(context))[0]; + expect(E.purchaseOrder(changed).contactPhone().eval()).toBe('5550401'); + expect(E.purchaseOrder(changed).version().eval()).toBe(2); + await verifyPageStream(context, savedA.id!, savedB.id!); + process.stdout.write('CORE_MUTATION_OWNERSHIP=' + JSON.stringify({ + language: 'typescript', passed: true, independentNewRoots: true, + batchRootIsolation: true, siblingVersionUnchanged: true, siblingPendingMutationRetained: true, + }) + '\n'); +} diff --git a/source/teaql-ts/examples/fix-e-alignment/paged-ownership.ts b/source/teaql-ts/examples/fix-e-alignment/paged-ownership.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fd79abdeaff48dd8d5dc5148e77eed15f527eac --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/paged-ownership.ts @@ -0,0 +1,50 @@ +import { UserContext } from '../../src'; +import { E } from 'generated/generated/E'; +import { Q } from 'generated/generated/Q'; +import { PurchaseOrder } from 'generated/generated/models/PurchaseOrder'; + +export async function verifyPageStream(context: UserContext, + idA: Parameters['withIdIs']>[0], + idB: Parameters['withIdIs']>[0]): Promise { + const before = await Q.purchaseOrders().limit(20).comment('Inspect the page ownership fixture') + .purpose('Establish the bounded exact total').executeForList(context); + const sentinel = (await Q.purchaseOrders().comment('Prepare a page-offset sentinel') + .purpose('Exercise a genuine nonzero page offset').newEntity(context)); + sentinel.updateContactPhone('5550500'); + await sentinel.auditAs('Save the synthetic page sentinel').save(context); + const exercise = async (rows: Iterable, label: string, previous: string, next: string, version: number) => { + const values = Array.from(rows); + const a = values.find(row => row.id === idA)!; const b = values.find(row => row.id === idB)!; + expect(a).toBeDefined(); expect(b).toBeDefined(); + a.updateContactPhone('55503' + next.slice(-2)); b.updateContactPhone(next); + await Q.tenantsWithMinimalFields().limit(1).comment('Run an unrelated query before deferred saves') + .purpose('Verify deferred ownership survives Context reuse').executeForList(context); + await a.auditAs('Save only A from ' + label).save(context); + let persisted = await Q.purchaseOrders().withIdIs(idB).limit(1).comment('Inspect B after deferred A save') + .purpose('Verify unrelated root value and version remain untouched').executeForList(context); + expect(persisted).toHaveLength(1); + expect(E.purchaseOrder(persisted[0]).contactPhone().eval()).toBe(previous); + expect(E.purchaseOrder(persisted[0]).version().eval()).toBe(version); + await b.auditAs('Save B later from ' + label).save(context); + persisted = await Q.purchaseOrders().withIdIs(idB).limit(1).comment('Inspect the later deferred B save') + .purpose("Verify B's pending mutation survived A's commit").executeForList(context); + expect(persisted).toHaveLength(1); + expect(E.purchaseOrder(persisted[0]).contactPhone().eval()).toBe(next); + expect(E.purchaseOrder(persisted[0]).version().eval()).toBe(version + 1); + }; + const page = await Q.purchaseOrders().orderByIdDescending().offset(1).limit(2).count() + .comment('Load a nonzero-offset page of independent roots').purpose('Verify exact count and page ownership').executeForList(context); + expect(page).toHaveLength(2); expect(page.totalCount).toBe(before.length + 1); + await exercise(page, 'a nonzero-offset page', '5550401', '5550402', 2); + const streamed: PurchaseOrder[] = []; + for await (const row of Q.purchaseOrders().orderByIdAscending().limit(20) + .comment('Stream independent roots across single-row chunks').purpose('Verify cross-chunk deferred-save ownership') + .executeForStream(context, 1)) streamed.push(row); + expect(streamed).toHaveLength(before.length + 1); + await exercise(streamed, 'a fully consumed scalar stream', '5550402', '5550403', 3); + process.stdout.write('CORE_MUTATION_PAGING=' + JSON.stringify({ + language: 'typescript', passed: true, pageOffset: 1, pageSize: 2, exactCount: before.length + 1, + pageRootIsolation: true, deferredSaveAfterContextReuse: true, streamProfile: 'scalar-typed', + streamChunkSize: 1, streamRootIsolation: true, siblingPendingMutationRetained: true, + }) + '\n'); +} diff --git a/source/teaql-ts/examples/fix-e-alignment/partial-ancestors-probe.ts b/source/teaql-ts/examples/fix-e-alignment/partial-ancestors-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6037ca81a0e7ecf6649b4ef2774fe66cfd05d78 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/partial-ancestors-probe.ts @@ -0,0 +1,142 @@ +import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src'; +import { checkResultToWire } from '../../src/core/i18n'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import Database from 'better-sqlite3'; + +/** Generated Q/E and audited save; no generated implementations are edited. */ +export async function verifyPartialAncestors(filename: string): Promise { + const createdAt = new Date('2032-02-29T10:15:30Z'); + const updatedAt = new Date(createdAt.getTime() + 24 * 60 * 60 * 1000); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt)); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy'); + const review = jest.fn(() => undefined); + context.withMutationPolicyRegistry({resolve: review}); + let auditStart = 0; + const effects = () => ({queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + allocations: allocation.mock.calls.length, policies: policy.mock.calls.length, reviews: review.mock.calls.length, + audits: client.auditTrace.length - auditStart, + mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i + .test(String(call[0]).replace(/"/g, ''))).length}); + const reset = () => {query.mockClear(); transaction.mockClear(); allocation.mockClear(); + policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length;}; + const zero = {queries: 0, transactions: 0, allocations: 0, policies: 0, reviews: 0, audits: 0, mutations: 0}; + try { + await context.ensureSchema(); + reset(); + const order = (await Q.purchaseOrders().comment('Prepare the partial-ancestor fixture') + .purpose('Validate only modified business objects for graph saves').newEntity(context)) + .updateContactPhone('5550600').updateInternalNote(null); + const child = (await Q.orderItems().comment('Prepare one complete leaf') + .purpose('Use the generated relation and audited save').newEntity(context)) + .updateProductName('Partial graph original').updateUnitPrice(decimal('10.00')); + order.orderItemList().push(child); + const reservations = effects(); + expect(reservations.transactions).toBe(2); expect(reservations.allocations).toBe(2); + expect(reservations.mutations).toBe(0); expect(reservations.audits).toBe(0); + reset(); + await order.auditAs('Create the partial-ancestor graph').save(context); + const calibration = effects(); + expect(calibration.transactions).toBe(1); expect(calibration.allocations).toBe(0); + expect(calibration.mutations).toBe(2); expect(calibration.audits).toBe(2); + expect(calibration.policies).toBeGreaterThan(0); expect(calibration.reviews).toBeGreaterThan(0); + if (!order.id) throw new Error('the saved order has no real identity'); + const orderId = order.id, active = context.requireActiveRoot('Tenant'); + const seeded = (await Q.purchaseOrders().withIdIs(orderId) + .selectOrderItemListWith(Q.orderItems().limit(1).comment('Read the persisted fixture leaf')) + .limit(1).comment('Read the saved graph identity').purpose('Do not infer a child ID from allocation order') + .executeForList(context))[0]; + expect(E.purchaseOrder(seeded).orderItemList().size().eval()).toBe(1); + const childId = E.purchaseOrder(seeded).orderItemList().first().id().eval(); + if (!childId) throw new Error('the saved leaf has no real identity'); + const load = async (complete: boolean) => { + const leaf = (complete ? Q.orderItems() : Q.orderItemsWithMinimalFields()).withIdIs(childId) + .limit(1).comment(complete ? 'Load every scalar of the modified leaf' : 'Load an incomplete modified leaf'); + const root = (await Q.tenantsWithMinimalFields().withIdIs(String(active.id)) + .selectPurchaseOrderListWith(Q.purchaseOrdersWithMinimalFields().withIdIs(orderId) + .selectOrderItemListWith(leaf).limit(1).comment('Keep the untouched parent partial')) + .limit(1).comment('Load two untouched partial ancestors above one leaf') + .purpose('Exercise Q E JSON and graph mutation in one bounded example').executeForList(context))[0]; + expect(root).toBeDefined(); expect(E.tenant(root).purchaseOrderList().size().eval()).toBe(1); + const parent = root.purchaseOrderList()[0]; + expect(E.purchaseOrder(parent).orderItemList().size().eval()).toBe(1); + return {root, parent, leaf: parent.orderItemList()[0]}; + }; + const graph = await load(true); + const empty = (await Q.purchaseOrdersWithMinimalFields().withIdIs(orderId) + .selectOrderItemListWith(Q.orderItemsWithMinimalFields().withIdIs('0').limit(1) + .comment('Explicitly select an empty child list')) + .limit(1).comment('Distinguish selected empty from an unselected reverse relation') + .purpose('Native JSON must preserve relation availability without querying').executeForList(context))[0]; + expect(E.purchaseOrder(empty).orderItemList().size().eval()).toBe(0); + reset(); + const missing = (read: () => unknown, pointer: string) => { + let failure: unknown; try {read();} catch (error) {failure = error;} + expect(failure).toBeInstanceOf(TeaQLNotLoadedError); + expect((failure as TeaQLNotLoadedError).toWire().instancePath).toBe(pointer); + }; + missing(() => E.tenant(graph.root).name().eval(), '/name'); + missing(() => E.tenant(graph.root).purchaseOrderList().first().contactPhone().eval(), '/purchaseOrderList/0/contactPhone'); + expect(String(E.orderItem(graph.leaf).unitPrice().eval())).toBe(String(decimal('10.00'))); + const json = JSON.parse(JSON.stringify(graph.root)); + expect(json).not.toHaveProperty('name'); expect(json.purchaseOrderList).toHaveLength(1); + expect(json).not.toHaveProperty('orderItemList'); + expect(json.purchaseOrderList[0]).not.toHaveProperty('contactPhone'); + expect(json.purchaseOrderList[0].orderItemList).toHaveLength(1); + expect(JSON.parse(JSON.stringify(empty)).orderItemList).toEqual([]); + expect(effects()).toEqual(zero); const guardEffects = effects(); + context.withBusinessClock(new FixedBusinessClock(updatedAt)); + graph.leaf.updateProductName('Partial graph updated'); + await graph.root.auditAs('Save the complete modified leaf through untouched partial ancestors').save(context); + const saveEffects = effects(); + expect(saveEffects.transactions).toBe(1); expect(saveEffects.allocations).toBe(0); + expect(saveEffects.mutations).toBe(1); expect(saveEffects.audits).toBe(1); + expect(saveEffects.policies).toBeGreaterThan(0); expect(saveEffects.reviews).toBeGreaterThan(0); + const physical = () => { + const db = new Database(filename, {readonly: true, fileMustExist: true}); + try {return { + roots: db.prepare('SELECT id,name,version FROM tenant_data ORDER BY id').all(), + parents: db.prepare('SELECT id,tenant,contact_phone,internal_note,version,create_time,update_time FROM purchase_order_data WHERE id = ?').all(orderId), + leaves: db.prepare('SELECT id,purchase_order,tenant,product_name,unit_price,version,create_time,update_time FROM order_item_data WHERE id = ?').all(childId), + };} finally {db.close();} + }; + const stored = physical(); + expect(stored.roots).toEqual([{id: Number(active.id), name: 'Tenant Name', version: 1}]); + expect(stored.parents).toEqual([expect.objectContaining({id: Number(orderId), tenant: Number(active.id), contact_phone: '5550600', internal_note: null, + version: 1, create_time: createdAt.getTime(), update_time: createdAt.getTime()})]); + expect(stored.leaves).toEqual([expect.objectContaining({id: Number(childId), purchase_order: Number(orderId), tenant: Number(active.id), + product_name: 'Partial graph updated', unit_price: String(decimal('10.00')), version: 2, + create_time: createdAt.getTime(), update_time: updatedAt.getTime()})]); + const partial = await load(false); + partial.leaf.updateProductName('Rejected partial leaf'); + const key = {entity: 'OrderItem', id: (partial.leaf as any)._ledgerId}; + const pending = () => JSON.stringify((partial.leaf as any)._root.change(key)); + const before = pending(), rejections: unknown[][] = [], rejectionEffects: Array> = []; + for (let attempt = 0; attempt < 2; attempt++) { + reset(); let failure: unknown; + try {await partial.root.auditAs('Reject the incomplete modified leaf before any provider work').save(context);} + catch (error) {failure = error;} + expect(failure).toBeInstanceOf(CheckException); + const violations = (failure as CheckException).violations.map(result => checkResultToWire(result)); + expect(violations.length).toBeGreaterThan(0); + for (const violation of violations) { + expect(violation.ruleId).toBe('invalid_type'); expect(violation.entityType).toBe('OrderItem'); + expect(violation.instancePath).toMatch(/^\/purchaseOrderList\/0\/orderItemList\/0\//); + } + expect(effects()).toEqual(zero); expect(pending()).toBe(before); expect(physical()).toEqual(stored); + rejections.push(violations); rejectionEffects.push(effects()); + } + process.stdout.write('CORE_TS_PARTIAL_ANCESTORS_RESULT=' + JSON.stringify({language: 'typescript', passed: true, + orderId: String(orderId), leafId: String(childId), ancestorVersions: [1, 1], leafVersion: 2, calibration, guardEffects, saveEffects, + cases: ['partial-ancestor-guards-and-JSON-no-I/O', 'complete-leaf-saved-through-two-untouched-partial-ancestors', + 'partial-leaf-rejected-twice-before-provider-with-intent-retained'], rejections, rejectionEffects, + intentRetained: true, selectedEmptySerialized: true, unselectedListOmitted: true, generatedImplementationsModified: false}) + '\n'); + } finally { + query.mockRestore(); transaction.mockRestore(); allocation.mockRestore(); policy.mockRestore(); await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/partial-root-probe.ts b/source/teaql-ts/examples/fix-e-alignment/partial-root-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..0da4c4267ac311effab3f4f68ccde131cd1345c2 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/partial-root-probe.ts @@ -0,0 +1,140 @@ +import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src'; +import { checkResultToWire } from '../../src/core/i18n'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import Database from 'better-sqlite3'; + +/** Application-owned regression; all business preparation uses generated Q/E/save. */ +export async function verifyPartialRoot(filename: string): Promise { + const createdAt = new Date('2032-04-01T10:15:30Z'); + const updatedAt = new Date(createdAt.getTime() + 86400000); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt)); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const exec = jest.spyOn(driver.database as Database.Database, 'exec'); + const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy'); + const review = jest.fn(() => undefined); + context.withMutationPolicyRegistry({resolve: review}); + let auditStart = 0; + const effects = () => ({ + queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + begins: exec.mock.calls.filter(call => /^BEGIN\b/i.test(call[0])).length, + commits: exec.mock.calls.filter(call => /^COMMIT\b/i.test(call[0])).length, + rollbacks: exec.mock.calls.filter(call => /^ROLLBACK\b/i.test(call[0])).length, + allocations: allocation.mock.calls.length, policyLookups: policy.mock.calls.length, + policyReviews: review.mock.calls.length, audits: client.auditTrace.length - auditStart, + mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i + .test(String(call[0]).replace(/"/g, ''))).length, + rootLookups: query.mock.calls.filter(call => /\bFROM\s+tenant_data\b/i.test(String(call[0]).replace(/"/g, ''))).length, + }); + const reset = () => { + query.mockClear(); transaction.mockClear(); exec.mockClear(); allocation.mockClear(); + policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length; + }; + const zero = {queries: 0, transactions: 0, begins: 0, commits: 0, rollbacks: 0, + allocations: 0, policyLookups: 0, policyReviews: 0, audits: 0, mutations: 0, rootLookups: 0}; + const physical = () => { + const db = new Database(filename, {readonly: true, fileMustExist: true}); + try { return { + tenant_data: db.prepare('SELECT id,version,name FROM tenant_data ORDER BY id').all(), + purchase_order_data: db.prepare('SELECT id,version,tenant,contact_phone,internal_note,create_time,update_time FROM purchase_order_data ORDER BY id').all(), + order_item_data: db.prepare('SELECT id,version,tenant,purchase_order,product_name,unit_price,create_time,update_time FROM order_item_data ORDER BY id').all(), + }; } finally { db.close(); } + }; + try { + await context.ensureSchema(); + const active = context.requireActiveRoot('Tenant'); + reset(); + const other = (await Q.tenants().comment('Prepare another persisted domain root') + .purpose('Test wrong context with a real root, not an invented ID').newEntity(context)) + .updateName('Independent partial root'); + await other.auditAs('Create an independent root for managed-root verification').save(context); + expect(other.id).toBeTruthy(); expect(String(other.id)).not.toBe(String(active.id)); + const order = (await Q.purchaseOrders().comment('Prepare the managed partial-ancestor fixture') + .purpose('Verify ownership through an unchanged sparse graph').newEntity(context)) + .updateContactPhone('5550801').updateInternalNote(null); + const child = (await Q.orderItems().comment('Prepare the complete managed leaf') + .purpose('Persist a leaf owned by the original domain root').newEntity(context)) + .updateProductName('Managed partial original').updateUnitPrice(decimal('10.00')); + order.orderItemList().push(child); + await order.auditAs('Create the owned graph for partial-ancestor admission').save(context); + expect(order.id).toBeTruthy(); expect(child.id).toBeTruthy(); + const orderId = order.id!, childId = child.id!; + await Q.tenants().withIdIs(String(other.id)).limit(1).comment('Calibrate root SELECT observation') + .purpose('Prove that admission would detect provider root lookups').executeForList(context); + const rollback = new Error('intentional observer calibration'); + await expect(driver.transaction(async () => { throw rollback; })).rejects.toBe(rollback); + const calibration = effects(); + for (const count of Object.values(calibration)) expect(count).toBeGreaterThan(0); + const root = (await Q.tenantsWithMinimalFields().withIdIs(String(active.id)) + .selectPurchaseOrderListWith(Q.purchaseOrdersWithMinimalFields().withIdIs(orderId) + .selectOrderItemListWith(Q.orderItems().withIdIs(childId).limit(1) + .comment('Load the complete leaf, including its unchanged owner')) + .limit(1).comment('Keep the unmodified parent partial')) + .limit(1).comment('Load two partial ancestors above the owned complete leaf') + .purpose('Prove admission checks unchanged loaded ownership at a deep graph node') + .executeForList(context))[0]; + expect(E.tenant(root).purchaseOrderList().size().eval()).toBe(1); + const parent = root.purchaseOrderList()[0]; + expect(E.purchaseOrder(parent).orderItemList().size().eval()).toBe(1); + const leaf = parent.orderItemList()[0]; + expect(String(E.orderItem(leaf).tenantId().eval())).toBe(String(active.id)); + const sparse = () => { + for (const read of [() => E.tenant(root).name().eval(), () => E.purchaseOrder(parent).contactPhone().eval()]) { + let error: unknown; try { read(); } catch (caught) { error = caught; } + expect(error).toBeInstanceOf(TeaQLNotLoadedError); + } + const value = JSON.parse(JSON.stringify(root)); + expect(value).not.toHaveProperty('name'); + expect(value.purchaseOrderList[0]).not.toHaveProperty('contactPhone'); + return JSON.stringify({rootVersion: root.version, parentVersion: parent.version, + keys: Object.keys(value).sort(), parentKeys: Object.keys(value.purchaseOrderList[0]).sort()}); + }; + const projection = sparse(), beforeStorage = physical(); + context.withBusinessClock(new FixedBusinessClock(updatedAt)); + leaf.updateProductName('Managed partial retry'); + const key = {entity: 'OrderItem', id: (leaf as any)._ledgerId}; + const pending = () => JSON.stringify((leaf as any)._root.change(key)); + const intent = pending(); expect(JSON.parse(intent)).not.toHaveProperty('tenant'); + context.insertResource('activeRoot', {entity: 'Tenant', id: other.id!}); + const denials: Array> = []; + for (let attempt = 1; attempt <= 2; attempt++) { + reset(); let failure: unknown; + try { await root.auditAs('Reject the complete leaf under another active root').save(context); } + catch (error) { failure = error; } + const denied = effects(), storageUnchanged = JSON.stringify(physical()) === JSON.stringify(beforeStorage); + const observation = {attempt, effects: denied, intentRetained: pending() === intent, + sparseViewUnchanged: sparse() === projection, storageUnchanged, + violations: failure instanceof CheckException ? failure.violations.map(result => checkResultToWire(result)) : []}; + denials.push(observation); + process.stdout.write('CORE_TS_PARTIAL_ROOT_DENIAL=' + JSON.stringify(observation) + '\n'); + expect(failure).toBeInstanceOf(CheckException); expect(denied).toEqual(zero); + expect(observation.intentRetained && observation.sparseViewUnchanged && storageUnchanged).toBe(true); + expect(observation.violations).toEqual([expect.objectContaining({ruleId: 'context_root_mismatch', entityType: 'OrderItem', + instancePath: '/purchaseOrderList/0/orderItemList/0/tenant', message: 'Context-bound root must match the active context'})]); + } + context.insertResource('activeRoot', active); reset(); + await root.auditAs('Save the same complete leaf under its original active root').save(context); + const acceptedEffects = effects(); + expect(acceptedEffects).toEqual({...zero, queries: 2, transactions: 1, begins: 1, commits: 1, + policyLookups: 1, policyReviews: 1, audits: 1, mutations: 1}); + expect((leaf as any)._root.change(key)).toEqual({}); expect(sparse()).toBe(projection); + const stored = physical(); + expect(stored.purchase_order_data.find((row: any) => String(row.id) === String(orderId))).toEqual({ + id: Number(orderId), version: 1, tenant: Number(active.id), contact_phone: '5550801', internal_note: null, + create_time: createdAt.getTime(), update_time: createdAt.getTime()}); + expect(stored.order_item_data.find((row: any) => String(row.id) === String(childId))).toEqual({ + id: Number(childId), version: 2, tenant: Number(active.id), purchase_order: Number(orderId), + product_name: 'Managed partial retry', unit_price: '10.00', create_time: createdAt.getTime(), update_time: updatedAt.getTime()}); + process.stdout.write('CORE_TS_PARTIAL_ROOT_RESULT=' + JSON.stringify({language: 'typescript', passed: true, + orderId: String(orderId), leafId: String(childId), activeRootId: String(active.id), otherRootId: String(other.id), + calibration, denials, acceptedEffects, ancestorVersions: [root.version, parent.version], leafVersion: leaf.version, + sameGraphRetry: true, intentClearedAfterCommit: true, generatedImplementationsModified: false}) + '\n'); + } finally { + query.mockRestore(); transaction.mockRestore(); exec.mockRestore(); allocation.mockRestore(); policy.mockRestore(); + await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/unchanged-views-probe.ts b/source/teaql-ts/examples/fix-e-alignment/unchanged-views-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..5eb96b4eb16d92eb9532124a02294d3ff41467f3 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/unchanged-views-probe.ts @@ -0,0 +1,167 @@ +import { FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import Database from 'better-sqlite3'; + +export const unchangedViewCases = [ + 'sparse-null-forward', 'complete-independent-other', 'empty-reverse', + 'rollback-after-write', 'rollback-before-commit', +] as const; +export type UnchangedViewCase = typeof unchangedViewCases[number]; + +/** Business preparation uses Q/E/mutation; spies and readonly SQL are test oracles. */ +export async function verifyUnchangedView(filename: string, scenario: UnchangedViewCase): Promise { + const round = Number(process.env.TEAQL_FIX_E_ROUND); + if (![1, 2].includes(round)) throw new Error('An explicit retained-example round is required'); + const createdAt = new Date(Date.parse('2032-02-29T10:15:30Z') + (round - 1) * 86400000); + const updatedAt = new Date(createdAt.getTime() + 7200000); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt)); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const driver = (client as any).driver; + const actualQuery = driver.query.bind(driver), actualExec = driver.database.exec.bind(driver.database); + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const exec = jest.spyOn(driver.database as Database.Database, 'exec'); + const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy'); + const review = jest.fn(() => undefined); context.withMutationPolicyRegistry({resolve: review}); + let auditStart = client.auditTrace.length; + const effects = () => ({ + queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + begins: exec.mock.calls.filter(call => /^BEGIN\b/i.test(call[0])).length, + commits: exec.mock.calls.filter(call => /^COMMIT\b/i.test(call[0])).length, + rollbacks: exec.mock.calls.filter(call => /^ROLLBACK\b/i.test(call[0])).length, + allocations: allocation.mock.calls.length, policyLookups: policy.mock.calls.length, + policyReviews: review.mock.calls.length, audits: client.auditTrace.length - auditStart, + mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i + .test(String(call[0]).replace(/"/g, ''))).length, + rootLookups: query.mock.calls.filter(call => /\bFROM\s+tenant_data\b/i.test(String(call[0]).replace(/"/g, ''))).length, + }); + const zero = {queries: 0, transactions: 0, begins: 0, commits: 0, rollbacks: 0, + allocations: 0, policyLookups: 0, policyReviews: 0, audits: 0, mutations: 0, rootLookups: 0}; + const reset = () => { + query.mockClear(); transaction.mockClear(); exec.mockClear(); allocation.mockClear(); + policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length; + }; + const physical = (id: unknown) => { + const oracle = new Database(filename, {readonly: true, fileMustExist: true}); + try {return oracle.prepare('SELECT id,version,contact_phone,internal_note,create_time,update_time FROM purchase_order_data WHERE id = ?').get(id);} + finally {oracle.close();} + }; + try { + await context.ensureSchema(); reset(); + const original = (await Q.purchaseOrders().comment('Prepare the unchanged-view graph fixture') + .purpose('Verify no-op geometry and genuine transaction rollback through generated APIs').newEntity(context)) + .updateContactPhone('5550800').updateInternalNote(null); + await original.auditAs('Create one unchanged-view control').save(context); + const id = original.id!; + await Q.tenants().withIdIs('1').limit(1).comment('Calibrate root SELECT observation') + .purpose('Prove the root-lookup spy observes real provider work').executeForList(context); + const calibrationFailure = new Error('owned rollback observer calibration'); + await expect(driver.transaction(async () => {throw calibrationFailure;})).rejects.toBe(calibrationFailure); + const calibration = effects(); + for (const value of Object.values(calibration)) expect(value).toBeGreaterThan(0); + + const sparse = scenario === 'sparse-null-forward'; + let request = sparse ? Q.purchaseOrdersWithMinimalFields().selectContactPhone().selectInternalNote() : Q.purchaseOrders(); + if (scenario === 'empty-reverse') { + request = request.selectOrderItemListWith(Q.orderItemsWithMinimalFields().limit(1) + .comment('Load an explicitly empty child list')); + } else { + request = request.selectTenantWith(Q.tenantsWithMinimalFields().limit(1) + .comment('Load a sparse forward edge without the target name')); + } + const row = (await request.withIdIs(id).limit(1).comment('Load the bounded original object view') + .purpose('Retain selected nulls, sparse fields and explicit relation geometry across saves').executeForList(context))[0]; + expect(row).toBeDefined(); + const key = {entity: 'PurchaseOrder', id: (row as any)._ledgerId}; + const pending = () => (row as any)._root.change(key); + const root = (row as any)._root; + const geometry = () => { + expect(E.purchaseOrder(row).internalNote().eval()).toBeNull(); + const json = JSON.parse(JSON.stringify(row)); expect(json).toHaveProperty('internalNote', null); + if (sparse) { + expect(() => E.purchaseOrder(row).createTime().eval()).toThrow(TeaQLNotLoadedError); + expect(json).not.toHaveProperty('createTime'); + } + if (scenario === 'empty-reverse') { + expect(E.purchaseOrder(row).orderItemList().size().eval()).toBe(0); + expect(json).toHaveProperty('orderItemList', []); + } else { + expect(String(E.purchaseOrder(row).tenantId().eval())).toBe('1'); + expect(String(E.purchaseOrder(row).tenant().eval()!.id)).toBe('1'); + expect(() => E.purchaseOrder(row).tenant().name().eval()).toThrow(TeaQLNotLoadedError); + expect(json.tenant).not.toHaveProperty('name'); + } + return JSON.stringify({keys: Object.keys(json).sort(), tenant: json.tenant, children: json.orderItemList}); + }; + const beforeGeometry = geometry(), beforeJSON = JSON.stringify(row), beforeStorage = physical(id); + const baselineVersion = root.originalVersion(key); expect(baselineVersion).toBe(1); + let other: typeof row | undefined; + if (scenario === 'complete-independent-other') { + other = (await Q.purchaseOrders().withIdIs(id).limit(1).comment('Load a separate mutable view') + .purpose('A no-op must not consume another view mutation ledger').executeForList(context))[0]; + expect(other).not.toBe(row); other.updateInternalNote('another view remains pending'); + } + const otherPending = () => other ? (other as any)._root.change({entity: 'PurchaseOrder', id: (other as any)._ledgerId}) : undefined; + const beforeOther = JSON.stringify(otherPending()); + context.withBusinessClock(new FixedBusinessClock(updatedAt)); + const rollback = scenario.startsWith('rollback-'); + if (!rollback) { + row.updateContactPhone('5550899').updateContactPhone('5550800'); reset(); + await row.auditAs('Save a restored field without refreshing the object view').save(context); + const observed = effects(); expect(observed).toEqual(zero); + expect(JSON.stringify(row)).toBe(beforeJSON); expect(geometry()).toBe(beforeGeometry); + expect((row as any)._root).toBe(root); expect(pending()).toEqual({}); + expect(root.originalVersion(key)).toBe(baselineVersion); expect(row.version).toBe(1); + expect(JSON.stringify(otherPending())).toBe(beforeOther); expect(physical(id)).toEqual(beforeStorage); + process.stdout.write('CORE_TS_UNCHANGED_VIEW_CASE=' + JSON.stringify({scenario, round, id: String(id), + passed: true, effects: observed, calibration, geometryRetained: true, selectedNullRetained: true, + independentIntentRetained: true, sameLedger: true, version: row.version, physical: physical(id)}) + '\n'); + return; + } + + row.updateContactPhone('5550801'); + const failure = new Error('owned transaction fault: ' + scenario); + let injected = 0, uncommitted: unknown; + const observeWritten = () => { + uncommitted = driver.database.prepare('SELECT contact_phone,version FROM purchase_order_data WHERE id = ?').get(id); + expect(uncommitted).toEqual({contact_phone: '5550801', version: 2}); + injected++; throw failure; + }; + if (scenario === 'rollback-after-write') { + query.mockImplementation(async (sql: unknown, values: unknown) => { + const result = await actualQuery(sql, values); + if (/^\s*UPDATE\s+purchase_order_data\b/i.test(String(sql).replace(/"/g, ''))) observeWritten(); + return result; + }); + } else { + exec.mockImplementation((sql: string) => {if (/^COMMIT\b/i.test(sql)) observeWritten(); return actualExec(sql);}); + } + reset(); + await expect(row.auditAs('Roll back a real write without losing the original view or retry intent').save(context)).rejects.toBe(failure); + const denied = effects(); + expect(injected).toBe(1); expect(denied).toMatchObject({transactions: 1, begins: 1, rollbacks: 1, mutations: 1, audits: 0}); + expect(physical(id)).toEqual(beforeStorage); expect(geometry()).toBe(beforeGeometry); + expect(row.version).toBe(1); expect((row as any)._root).toBe(root); + expect(root.originalVersion(key)).toBe(baselineVersion); expect(pending()).toHaveProperty('contact_phone', '5550801'); + expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550801'); + const retainedIntent = {...pending()}; + query.mockImplementation(actualQuery); exec.mockImplementation(actualExec); reset(); + await row.auditAs('Retry the same rolled-back object without querying or rebasing it').save(context); + const accepted = effects(); + expect(accepted).toMatchObject({queries: 2, transactions: 1, begins: 1, commits: 1, rollbacks: 0, + mutations: 1, audits: 1, allocations: 0, policyLookups: 1, policyReviews: 1, rootLookups: 0}); + expect(row.version).toBe(2); expect(pending()).toEqual({}); expect(root.originalVersion(key)).toBe(2); + expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550801'); + expect(new Date(E.purchaseOrder(row).updateTime().eval()!).getTime()).toBe(updatedAt.getTime()); + expect(physical(id)).toEqual({id: Number(id), version: 2, contact_phone: '5550801', internal_note: null, + create_time: createdAt.getTime(), update_time: updatedAt.getTime()}); + process.stdout.write('CORE_TS_UNCHANGED_VIEW_CASE=' + JSON.stringify({scenario, round, id: String(id), passed: true, + calibration, injected, uncommitted, denied, accepted, retainedIntent, geometryRetained: true, + sameObjectRetry: true, originalOptimisticVersionRetained: true, physical: physical(id)}) + '\n'); + } finally { + query.mockRestore(); transaction.mockRestore(); exec.mockRestore(); allocation.mockRestore(); policy.mockRestore(); + await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/verify-local.cjs b/source/teaql-ts/examples/fix-e-alignment/verify-local.cjs new file mode 100644 index 0000000000000000000000000000000000000000..80308ec1bcf2f928136ce9d39d025fbcab2d5867 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/verify-local.cjs @@ -0,0 +1,138 @@ +#!/usr/bin/env node +"use strict"; +// Run after npm ci at the runtime root. No remote TeaQL package is substituted. +const fs = require("node:fs"), path = require("node:path"), os = require("node:os"), cp = require("node:child_process"), crypto = require("node:crypto"), assert = require("node:assert/strict"); +const example = __dirname, repo = path.resolve(example, "../.."); +const sha = bytes => crypto.createHash("sha256").update(bytes).digest("hex"); +function fingerprint() { + const manifest = JSON.parse(fs.readFileSync(path.join(example, "fixture-manifest.json"))); + assert.equal(manifest.language, "typescript"); assert.equal(manifest.evaluationErrors, 0); + assert.equal(sha(fs.readFileSync(path.join(example, "model.xml"))), manifest.modelSha256); + const actual = []; + function visit(directory, prefix = "") { + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { + const name = path.join(prefix, entry.name), original = path.join(directory, entry.name); + assert(!entry.isSymbolicLink(), "generated fixture cannot be a symlink"); + if (entry.isDirectory()) visit(original, name); else { assert(entry.isFile()); actual.push(name); } + } + } + visit(path.join(example, "generated")); + assert.deepEqual(actual.sort(), Object.keys(manifest.files).sort()); + for (const [name, expected] of Object.entries(manifest.files)) assert.equal(sha(fs.readFileSync(path.join(example, "generated", name))), expected, name); + return manifest; +} +const requested = process.env.TEAQL_FIX_E_EVIDENCE_DIR; +const evidence = requested ? path.resolve(requested) : fs.mkdtempSync(path.join(os.tmpdir(), "teaql-ts-fix-e-evidence-")); +if (requested) { assert(path.isAbsolute(requested) && !fs.existsSync(evidence)); fs.mkdirSync(evidence, {recursive: true}); } +const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "teaql-ts-fix-e-build-")); +const report = {schema: "teaql.typescript-fix-e-example/v1", passed: false, rounds: [], sameDatabase: true, + runtimeSource: path.join(repo, "src"), databaseRetained: true}; +const {createOwnedRunner, ownedBytes} = require('./owned-command.cjs'), runner = createOwnedRunner(); +async function main() { +try { + const manifest = fingerprint(); report.modelSha256 = manifest.modelSha256; + report.contextRootApplicationSha256 = sha(fs.readFileSync(path.join(example, 'context-root-probe.ts'))); + report.partialAncestorApplicationSha256 = sha(fs.readFileSync(path.join(example, 'partial-ancestors-probe.ts'))); + report.partialRootApplicationSha256 = sha(fs.readFileSync(path.join(example, 'partial-root-probe.ts'))); + report.unchangedViewsApplicationSha256 = sha(fs.readFileSync(path.join(example, 'unchanged-views-probe.ts'))); + report.checkerBoundaryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'checker-boundaries-probe.ts'))); + report.graphFixApplicationSha256 = sha(fs.readFileSync(path.join(example, 'graph-fix-idempotence.test.ts'))); + report.concurrentQueryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'concurrent-query-probe.ts'))); + report.deleteRetryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'delete-retry.test.ts'))); + assert(fs.existsSync(path.join(repo, "node_modules/jest/bin/jest.js")), "run npm ci at the runtime root first"); + const tsconfig = path.join(scratch, "tsconfig.json"), config = path.join(scratch, "jest.cjs"); + fs.writeFileSync(tsconfig, JSON.stringify({extends: path.join(repo, "tsconfig.json"), compilerOptions: { + types: ["node", "jest"], typeRoots: [path.join(repo, "node_modules/@types")], lib: ["ES2022", "DOM"], + baseUrl: repo, paths: {"teaql-ts": [path.join(repo, "src/index.ts")], "teaql-ts/*": [path.join(repo, "src/*")], + "generated/*": [path.join(example, "generated/src/*")]}}})); + fs.writeFileSync(config, "module.exports = " + JSON.stringify({rootDir: repo, roots: [example], testEnvironment: "node", + testMatch: ["**/examples/fix-e-alignment/verify.test.ts", "**/examples/fix-e-alignment/graph-fix-idempotence.test.ts", "**/examples/fix-e-alignment/delete-retry.test.ts", "**/examples/fix-e-alignment/creation-identity.test.ts"], + moduleNameMapper: {"^teaql-ts$": path.join(repo, "src/index.ts"), "^teaql-ts/(.*)$": path.join(repo, "src/$1"), + "^generated/(.*)$": path.join(example, "generated/src/$1")}, + transform: {"^.+\\.tsx?$": ["ts-jest", {tsconfig}]}}) + ";\n"); + for (const round of [1, 2]) { + const creationDatabases = path.join(evidence, "creation-round-" + round); + fs.mkdirSync(creationDatabases); + const command = [path.join(repo, "node_modules/jest/bin/jest.js"), "--config", config, + "--runInBand", "--cacheDirectory", path.join(scratch, "jest")]; + const log = path.join(evidence, "round-" + round + ".log"), fd = fs.openSync(log, "w"); + let result; + try { result = await runner.run([process.execPath, ...command], {cwd: repo, timeout: 120000, + env: {...process.env, TEAQL_FIX_E_DB: path.join(evidence, "fixture.sqlite"), TEAQL_FIX_E_ROUND: String(round), TEAQL_CREATION_DATABASES: creationDatabases}, stdio: ["ignore", fd, fd]}); } + finally { fs.closeSync(fd); } + report.rounds.push({command, exitCode: result.status, signal: result.signal, logSha256: sha(fs.readFileSync(log))}); + if (result.status !== 0) process.exitCode = result.status || 1; + assert.equal(result.status, 0, fs.readFileSync(log, "utf8").slice(-12000)); + const lines = fs.readFileSync(log, "utf8").split(/\r?\n/); + const deletes = lines.filter(line => line.startsWith('CORE_TS_FILE_DELETE_RETRY=')) + .map(line => JSON.parse(line.slice('CORE_TS_FILE_DELETE_RETRY='.length))); + assert.equal(deletes.length, 1); assert.equal(deletes[0].round, round); assert.equal(deletes[0].retryError, null); + assert.deepEqual(deletes[0].rollback.ledgerFields, []); assert.equal(deletes[0].retryMutations, 1); + assert.equal(deletes[0].retryPersists, 1); assert.equal(deletes[0].auditDelta, 1); + report.rounds[report.rounds.length - 1].deleteRetry = deletes[0]; + const viewCases = lines.filter(line => line.startsWith('CORE_TS_UNCHANGED_VIEW_CASE=')) + .map(line => JSON.parse(line.slice('CORE_TS_UNCHANGED_VIEW_CASE='.length))); + assert.deepEqual(viewCases.map(value => value.scenario).sort(), [ + 'sparse-null-forward', 'complete-independent-other', 'empty-reverse', 'rollback-after-write', 'rollback-before-commit', + ].sort()); + for (const value of viewCases) {assert.equal(value.passed, true); assert.equal(value.round, round);} + report.rounds[report.rounds.length - 1].unchangedViewCases = viewCases; + const checkerCases = lines.filter(line => line.startsWith('CORE_TS_CHECKER_BOUNDARY_CASE=')) + .map(line => JSON.parse(line.slice('CORE_TS_CHECKER_BOUNDARY_CASE='.length))); + assert.equal(checkerCases.length, 32); + for (const value of checkerCases) {assert.equal(value.passed, true); assert.equal(value.round, round);} + const checkerSummary = lines.filter(line => line.startsWith('CORE_TS_CHECKER_BOUNDARY_RESULT=')) + .map(line => JSON.parse(line.slice('CORE_TS_CHECKER_BOUNDARY_RESULT='.length))); + assert.equal(checkerSummary.length, 1); assert.equal(checkerSummary[0].passed, true); + assert.equal(checkerSummary[0].round, round); assert.equal(checkerSummary[0].observations, 32); + report.rounds[report.rounds.length - 1].checkerBoundaryCases = checkerCases; + const graphCases = lines.filter(line => line.startsWith('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE=')) + .map(line => JSON.parse(line.slice('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE='.length))); + assert.deepEqual(graphCases.map(value => value.case).sort(), [ + 'duplicate-create', 'duplicate-update', 'independent-real-graphs', 'distinct-views-same-id-rejected', + ].sort()); + for (const value of graphCases) assert.equal(value.facts.round, round); + report.rounds[report.rounds.length - 1].graphFixCases = graphCases; + const concurrent = lines.filter(line => line.startsWith('TYPESCRIPT_CONCURRENT_QUERY=')) + .map(line => JSON.parse(line.slice('TYPESCRIPT_CONCURRENT_QUERY='.length))); + assert.equal(concurrent.length, 1); assert(concurrent[0].passed && concurrent[0].observation.round === round); + assert(concurrent[0].observation.bothLive && concurrent[0].observation.sameContext && concurrent[0].observation.distinctRoots); + report.rounds[report.rounds.length - 1].concurrentQuery = concurrent[0].observation; + for (const marker of ["FIX_E_EXAMPLE=", "CORE_LOAD_EXAMPLE=", "CORE_MUTATION_OWNERSHIP=", "CORE_MUTATION_PAGING=", "CORE_CHECKER_METADATA=", "CORE_FILE_CHECKER_METADATA=", "CORE_TS_E_BOUNDARY_RESULT=", "CORE_TS_ROOT_RESULT=", "CORE_TS_ROOT_FILE_RESULT=", "CORE_TS_PARTIAL_ANCESTORS_RESULT=", "CORE_TS_PARTIAL_ROOT_RESULT="]) { + const values = lines.filter(line => line.startsWith(marker)).map(line => JSON.parse(line.slice(marker.length))); + assert.equal(values.length, 1, marker); assert.equal(values[0].passed, true, marker); + } + assert.deepEqual(fingerprint(), manifest); + } + report.databaseSha256 = sha(fs.readFileSync(path.join(evidence, "fixture.sqlite"))); + report.deleteRetryFile = {file: 'fixture.sqlite.delete-retry.json', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.delete-retry.json')))}; + report.contextRootDatabase = {file: 'fixture.sqlite.context-root.sqlite', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.context-root.sqlite')))}; + report.contextRootFile = {file: 'fixture.sqlite.context-root.json', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.context-root.json')))}; + report.partialAncestorDatabase = {file: 'fixture.sqlite.partial-ancestors.sqlite', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.partial-ancestors.sqlite')))}; + report.partialRootDatabase = {file: 'fixture.sqlite.partial-root.sqlite', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.partial-root.sqlite')))}; + report.checkerBoundaryDatabases = ['fixture.sqlite.checker-boundaries.sqlite', 'fixture.sqlite.checker-boundaries.sqlite.no-schema.sqlite'] + .map(file => ({file, sha256: sha(fs.readFileSync(path.join(evidence, file)))})); + report.graphFixDatabases = ['', '.first.sqlite', '.second.sqlite', '.identity.sqlite'] + .map(suffix => {const file = 'fixture.sqlite.idempotence.sqlite' + suffix; + return {file, sha256: sha(fs.readFileSync(path.join(evidence, file)))};}); + report.concurrentQueryDatabase = {file: 'fixture.sqlite.concurrent-query.sqlite', + sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.concurrent-query.sqlite')))}; + report.passed = true; + console.log("PASS TypeScript retained Fix/E/loading/ownership example twice on one database"); +} catch (error) { console.error(error.stack); process.exitCode ||= 1; } +finally { + // The awaited runner reaps its owned process group before cache/config cleanup. + report.disposedOwnedBytes = runner.safeToClean ? ownedBytes(scratch) : 0; + if (runner.safeToClean) fs.rmSync(scratch, {recursive: true}); + else report.unsafeBuildRetention = {path: scratch, processGroup: runner.unsafeGroup}; + report.scratchRemoved = !fs.existsSync(scratch); runner.dispose(); + fs.writeFileSync(path.join(evidence, "receipt.json"), JSON.stringify(report, null, 2) + "\n"); + console.log("Retained compact example evidence: " + evidence); +} +} +main().catch(error => { console.error(error.stack); process.exitCode ||= 1; }); diff --git a/source/teaql-ts/examples/fix-e-alignment/verify.test.ts b/source/teaql-ts/examples/fix-e-alignment/verify.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51fa8d289a40af5d7c9c973fa3777aa60e6f891 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/verify.test.ts @@ -0,0 +1,286 @@ +import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src'; +import { E } from 'generated/generated/E'; +import { Q } from 'generated/generated/Q'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import { RuntimeOperation, RuntimeOperationCompletion } from '../../src/core/telemetry'; +import { verifyLoading } from './loading-probe'; +import { verifyOwnership } from './ownership-probe'; +import Database from 'better-sqlite3'; +import { verifyCheckerMetadata, verifyFileCheckerMetadata } from './checker-metadata-probe'; +import { verifyExpressionBoundaries } from './expression-boundary-probe'; +import { verifyContextRoot, verifyFileContextRoot } from './context-root-probe'; +import { verifyPartialAncestors } from './partial-ancestors-probe'; +import { verifyPartialRoot } from './partial-root-probe'; +import { unchangedViewCases, verifyUnchangedView } from './unchanged-views-probe'; +import { verifyCheckerBoundaries } from './checker-boundaries-probe'; +import { verifyConcurrentQuery } from './concurrent-query-probe'; + +test('concurrent generated queries retain independent live request ownership on one Context', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('Retained SQLite path required for concurrent-query verification'); + await verifyConcurrentQuery(filename + '.concurrent-query.sqlite'); +}, 15000); + +test('Checker admission covers required relations, exact completeness, post-Fix values and object-local wire inputs', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('Retained SQLite path required for Checker boundary verification'); + await verifyCheckerBoundaries(filename + '.checker-boundaries.sqlite'); +}); + +test.each(unchangedViewCases)('unchanged view and rollback contract: %s', async scenario => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('Retained SQLite path required for view restoration verification'); + await verifyUnchangedView(filename + '.unchanged.' + scenario + '.sqlite', scenario); +}); + +test('a complete modified leaf retains root admission through two untouched partial ancestors', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite path required for managed partial-root verification'); + await verifyPartialRoot(filename + '.partial-root.sqlite'); +}); + +test('only modified objects need completeness through two untouched partial ancestors', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite path required for partial-ancestor verification'); + await verifyPartialAncestors(filename + '.partial-ancestors.sqlite'); +}); + +test('the file-backed generated client protects loaded root ownership too', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained file path required for file-backed root verification'); + await verifyFileContextRoot(filename + '.context-root.json'); +}); + +test('generated audited graph saves reject invalid or mismatched context roots before provider work', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite database required for root identity verification'); + await verifyContextRoot(filename + '.context-root.sqlite'); +}); + +test('generated E boundaries preserve NotLoaded, absence, native terminals and state without I/O', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite database required for E boundary verification'); + await verifyExpressionBoundaries(filename + '.expression-boundaries.sqlite'); +}); + +test('generated Checker violations retain their declaring entity and wire locations', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite database required for Checker metadata'); + await verifyCheckerMetadata(filename); + await verifyFileCheckerMetadata(filename + '.checker-file.json'); +}); + +test('unmodified generated Q/E and audited SQLite saves consume the local Business Clock', async () => { + const first = new Date('2032-02-29T10:15:30.000Z'); + const second = new Date('2032-03-01T11:16:31.000Z'); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(first)); + const client = new SQLiteTeaQLClient(process.env.TEAQL_FIX_E_DB || ':memory:').setUserContext(context); + const telemetry: Array<{operation: RuntimeOperation; completion?: RuntimeOperationCompletion}> = []; + client.setRuntimeTelemetry({start: operation => ({ + success: completion => { telemetry.push({operation, completion}); }, + failure: () => undefined, + })}); + context.insertResource('dataService', client); + const diagnostics: ReturnType[] = []; + const humanMessages: string[] = []; + const missing = (read: () => unknown, location: string, attempted: string, expression: string) => { + try { read(); } + catch (error) { + if (!(error instanceof TeaQLNotLoadedError)) throw error; + const wire = error.toWire(); + expect(wire.code).toBe('NOT_LOADED'); + expect(wire.instancePath).toBe(location); + expect(wire.attemptedInstancePath).toBe(attempted); + expect(wire.expressionWithBrokenPoint).toBe(expression); + expect(wire.expressionWithBrokenPoint.match(//g)).toHaveLength(1); + expect(error.message).not.toContain('PRIVATE-FALLBACK'); + diagnostics.push(wire); + humanMessages.push(error.message); + return; + } + throw new Error('NotLoaded must not be treated as null or fallback'); + }; + try { + await context.ensureSchema(); + const order = (await Q.purchaseOrders().comment('Prepare the synthetic clock fixture') + .purpose('Verify generated Fix and expression diagnostics').newEntity(context)); + order.updateContactPhone('5550100'); + const saved = await order.auditAs('Create the synthetic Fix order').save(context); + expect(new Date(E.purchaseOrder(saved).createTime().eval()!).getTime()).toBe(first.getTime()); + expect(new Date(E.purchaseOrder(saved).updateTime().eval()!).getTime()).toBe(first.getTime()); + expect(String(E.purchaseOrder(saved).tenantId().eval())).toBe('1'); + expect(E.purchaseOrder(saved).internalNote().orElse('fallback')).toBe('fallback'); + + const partial = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1) + .comment('Load scalar fields without eager relations').purpose('Verify E requires explicit relation loading') + .executeForList(context))[0]; + expect(String(E.purchaseOrder(partial).tenantId().eval())).toBe('1'); + missing(() => E.purchaseOrder(partial).tenant().name().eval(), '/tenant', '/tenant/name', + 'E.purchaseOrder().tenant().name().eval()'); + missing(() => E.purchaseOrder(partial).tenant().purchaseOrderList().first().tenant().name().eval(), + '/tenant', '/tenant/purchaseOrderList/0/tenant/name', + 'E.purchaseOrder().tenant().purchaseOrderList().first().tenant().name().eval()'); + missing(() => E.purchaseOrder(partial).orderItemList().get(2).productName().eval(), + '/orderItemList', '/orderItemList/2/productName', + 'E.purchaseOrder().orderItemList().get(2).productName().eval()'); + missing(() => E.purchaseOrder(partial).tenant().name().orElse('PRIVATE-FALLBACK'), + '/tenant', '/tenant/name', + 'E.purchaseOrder().tenant().name().orElse()'); + + context.withBusinessClock(new FixedBusinessClock(second)); + const loaded = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1) + .comment('Reload the complete order before changing it') + .purpose('Verify update Fix preserves the original create time').executeForList(context))[0]; + loaded.updateContactPhone('5550101'); + await loaded.auditAs('Update the synthetic Fix order').save(context); + const persisted = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1) + .comment('Reload the persisted update').purpose('Verify Business Clock values using E') + .executeForList(context))[0]; + expect(new Date(E.purchaseOrder(persisted).createTime().eval()!).getTime()).toBe(first.getTime()); + expect(new Date(E.purchaseOrder(persisted).updateTime().eval()!).getTime()).toBe(second.getTime()); + expect(E.purchaseOrder(persisted).contactPhone().eval()).toBe('5550101'); + expect(context.getResource('fixTime')).toBeUndefined(); + const requests = telemetry.filter(event => event.operation.name === 'PurchaseOrder.request'); + expect(requests.length).toBeGreaterThanOrEqual(3); + for (const request of requests) expect(request.completion?.attributes?.['teaql.result.cardinality']).toBe(1); + const statements = telemetry.filter(event => /\.(select|readback)$/.test(event.operation.name)); + expect(statements.length).toBeGreaterThan(0); + for (const statement of statements) expect(statement.operation.attributes?.['teaql.provider.execution']).toBe('statement'); + process.stdout.write('GENERATED_QUERY_METADATA_PASS language=typescript requestRows=1 providerExecution=statement\n'); + await verifyLoading(context, saved.id!); + await verifyOwnership(context); + process.stdout.write('FIX_E_EXAMPLE=' + JSON.stringify({ language: 'typescript', passed: true, + normalGeneratedSave: true, createTimePreserved: true, updateTimeAdvanced: true, + declaredContextRootInjected: true, diagnostics, humanMessages }) + '\n'); + } finally { await client.close(); } +}); + +test('a generated persisted field restored to its baseline has no provider, policy or audit effects', async () => { + const filename = process.env.TEAQL_FIX_E_DB; + if (!filename) throw new Error('retained SQLite database required for the independent oracle'); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-03-01T12:30:00Z'))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + try { + await context.ensureSchema(); + const entity = (await Q.purchaseOrders().comment('Prepare the known baseline restoration fixture') + .purpose('Verify a restored field does not become a business write').newEntity(context)); + entity.updateContactPhone('5550700'); + await entity.auditAs('Create the known baseline restoration fixture').save(context); + const row = (await Q.purchaseOrders().withIdIs(entity.id!).limit(1) + .comment('Load the persisted restoration baseline').purpose('Capture actual generated Q provenance') + .executeForList(context))[0]; + const json = JSON.stringify(row), version = row.version; + row.updateContactPhone('5550799').updateContactPhone('5550700'); + const driver = (client as any).driver; + const transaction = jest.spyOn(driver, 'transaction'); + const query = jest.spyOn(driver, 'query'); + const policy = jest.spyOn(context, 'enterMutationPolicy'); + const audits = client.auditTrace.length; + await row.auditAs('Save the restored baseline without writing').save(context); + const schema = (client as any).schemas.PurchaseOrder; + const oracle = new Database(filename, { readonly: true, fileMustExist: true }); + let stored: { contact_phone: string; version: number }; + try { stored = oracle.prepare(`SELECT contact_phone, version FROM "${schema.table}" WHERE id = ?`).get(row.id) as typeof stored; } + finally { oracle.close(); } + const result = {language: 'typescript', value: stored.contact_phone, versionBefore: version, + versionAfter: stored.version, transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length, + policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - audits, + projectionUnchanged: JSON.stringify(row) === json}; + process.stdout.write('CORE_BASELINE_RESTORATION=' + JSON.stringify(result) + '\n'); + expect(result).toMatchObject({value: '5550700', versionAfter: version, transactions: 0, + providerQueries: 0, policyReviews: 0, auditEvents: 0, projectionUnchanged: true}); + expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550700'); + + const noIO = (scenario: string, auditStart: number) => { + const effects = {scenario, transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length, + policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - auditStart}; + process.stdout.write('CORE_BASELINE_RESTORATION_CASE=' + JSON.stringify(effects) + '\n'); + expect(effects).toMatchObject({transactions: 0, providerQueries: 0, policyReviews: 0, auditEvents: 0}); + }; + const reset = () => { transaction.mockClear(); query.mockClear(); policy.mockClear(); return client.auditTrace.length; }; + const rawKey = {entity: 'PurchaseOrder', id: (row as any)._ledgerId}; + (row as any)._root.set(rawKey, 'contact_phone', '5550799'); + (row as any)._root.set(rawKey, 'contact_phone', '5550700'); + const rawAudits = reset(); + await row.auditAs('Save an admitted raw canonical field restored to baseline').save(context); + const rawResult = {transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length, + policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - rawAudits, + version: row.version, projectionUnchanged: JSON.stringify(row) === json}; + expect(rawResult).toEqual({transactions: 0, providerQueries: 0, policyReviews: 0, auditEvents: 0, version: 1, projectionUnchanged: true}); + process.stdout.write('CORE_BASELINE_RESTORATION_RAW=' + JSON.stringify(rawResult) + '\n'); + const nullBefore = JSON.stringify(row); + expect(E.purchaseOrder(row).internalNote().eval()).toBeNull(); + row.updateInternalNote('intermediate note').updateInternalNote(null); + let auditStart = reset(); + await row.auditAs('Save a restored loaded null').save(context); + noIO('known-null', auditStart); expect(JSON.stringify(row)).toBe(nullBefore); + + const sparse = (await Q.purchaseOrdersWithMinimalFields().withIdIs(row.id!).selectContactPhone().limit(1) + .comment('Load only the field needed for the restoration probe').purpose('Preserve the original sparse view') + .executeForList(context))[0]; + const sparseBefore = JSON.stringify(sparse); + sparse.updateContactPhone('5550799').updateContactPhone('5550700'); auditStart = reset(); + await sparse.auditAs('Save a restored known field in a sparse view').save(context); + noIO('known-sparse-field', auditStart); expect(JSON.stringify(sparse)).toBe(sparseBefore); + expect(() => E.purchaseOrder(sparse).internalNote().eval()).toThrow(TeaQLNotLoadedError); + + const unknown = (await Q.purchaseOrdersWithMinimalFields().withIdIs(row.id!).limit(1) + .comment('Load identity without the original phone').purpose('Unknown provenance is not loaded null') + .executeForList(context))[0]; + unknown.updateContactPhone('5550700'); auditStart = reset(); + await expect(unknown.auditAs('Reject an edit with an unknown original').save(context)).rejects.toThrow(CheckException); + noIO('unknown-original-rejected', auditStart); + + const invalid = (await Q.purchaseOrders().withIdIs(row.id!).limit(1) + .comment('Load the raw admission negative control').purpose('Invalid native keys cannot disappear as no-ops') + .executeForList(context))[0]; + const invalidKey = {entity: 'PurchaseOrder', id: (invalid as any)._ledgerId}; + (invalid as any)._root.set(invalidKey, 'contact_phone', '5550700'); + (invalid as any)._root.set(invalidKey, 'contactPhone', '5550700'); auditStart = reset(); + await expect(invalid.auditAs('Reject a raw native-member field').save(context)).rejects.toThrow('canonical'); + noIO('invalid-key-before-discard', auditStart); + expect((invalid as any)._root.change(invalidKey)).toHaveProperty('contact_phone', '5550700'); + + context.withBusinessClock(new FixedBusinessClock(new Date('2032-04-01T09:15:00Z'))); + row.updateContactPhone('5550799').updateContactPhone('5550700').updateInternalNote('genuine remaining edit'); + auditStart = reset(); await row.auditAs('Persist the genuine edit after cancelling the phone change').save(context); + expect(transaction).toHaveBeenCalledTimes(1); expect(policy).toHaveBeenCalledTimes(1); + expect(client.auditTrace.length - auditStart).toBe(1); + expect(row.version).toBe(2); expect(E.purchaseOrder(row).internalNote().eval()).toBe('genuine remaining edit'); + expect(new Date(E.purchaseOrder(row).updateTime().eval()!).toISOString()).toBe('2032-04-01T09:15:00.000Z'); + const remainingOracle = new Database(filename, {readonly: true, fileMustExist: true}); + try { + expect(remainingOracle.prepare(`SELECT contact_phone, internal_note, version, update_time FROM "${schema.table}" WHERE id = ?`).get(row.id)) + .toEqual({contact_phone: '5550700', internal_note: 'genuine remaining edit', version: 2, update_time: 1964423700000}); + } finally { remainingOracle.close(); } + + // The complete plan, not only the parent's ledger, controls no-op handling. + const child = (await Q.orderItems().comment('Prepare a genuine new child on a clean parent') + .purpose('Verify clean parents still traverse pending child work').newEntity(context)); + child.updateProductName('Widget').updateUnitPrice(decimal('10')); + entity.orderItemList().push(child); + auditStart = reset(); await entity.auditAs('Save only the dirty child through its clean parent').save(context); + expect(entity.version).toBe(1); expect(child.version).toBe(1); expect(transaction).toHaveBeenCalledTimes(1); + expect(client.auditTrace.length - auditStart).toBe(1); + const childOracle = new Database(filename, {readonly: true, fileMustExist: true}); + try { + expect(childOracle.prepare('SELECT purchase_order, product_name, version FROM order_item_data WHERE id = ?').get(child.id)) + .toEqual({purchase_order: Number(entity.id), product_name: 'Widget', version: 1}); + } finally { childOracle.close(); } + row.updateContactPhone('5550799').updateContactPhone('5550700').markForDeletion(); + auditStart = reset(); await row.auditAs('Keep pending deletion after a restored scalar edit').save(context); + expect(row.version).toBe(-3); expect(transaction).toHaveBeenCalledTimes(1); expect(policy).toHaveBeenCalledTimes(1); + expect(client.auditTrace.length - auditStart).toBe(1); + const deletionOracle = new Database(filename, {readonly: true, fileMustExist: true}); + let deleted; + try {deleted = deletionOracle.prepare(`SELECT contact_phone, version FROM "${schema.table}" WHERE id = ?`).get(row.id);} + finally {deletionOracle.close();} + expect(deleted).toEqual({contact_phone: '5550700', version: -3}); + process.stdout.write('CORE_BASELINE_RESTORATION_DELETE=' + JSON.stringify({version: row.version, transactions: transaction.mock.calls.length, + policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - auditStart, physical: deleted}) + '\n'); + process.stdout.write('CORE_BASELINE_RESTORATION_COMPLETE=' + JSON.stringify({language: 'typescript', passed: true, + knownValue: true, knownNull: true, sparseGeometry: true, unknownOriginal: true, rawAdmission: true, + genuineEdit: true, cleanParentDirtyChild: true, independentReadOnlyOracle: true}) + '\n'); + } finally { jest.restoreAllMocks(); await client.close(); } +}); diff --git a/source/teaql-ts/examples/managed-creation-fixtures.json b/source/teaql-ts/examples/managed-creation-fixtures.json new file mode 100644 index 0000000000000000000000000000000000000000..50007b721d55073744ab79a16ea47802e98f64f4 --- /dev/null +++ b/source/teaql-ts/examples/managed-creation-fixtures.json @@ -0,0 +1,1649 @@ +{ + "schema": "teaql.typescript-managed-fixture-import/v1", + "generatorCommit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "generatorSourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937", + "producerReportSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "rawExport": "typescript-managed-fixtures-v1", + "generatedImplementationHandEdited": false, + "fixtures": [ + { + "id": "conformance", + "model": "examples/conformance/model.xml", + "modelSha256": "0a59f66db2487fdd0430087dd5985ae780225c088ad800679cb57c593c6bcee7", + "target": "examples/conformance", + "files": { + "src/generated/Q.ts": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "src/generated/requests/PlatformRequest.ts": "9a6c8e75b393b977c6b53517f222104e67b1ea0c8dfba773f2fd770f22b124db", + "src/generated/requests/WorkItemRequest.ts": "8c2d20df65964c9a0ab1775fbb3c482fa54e7634032f34828c231e1954f2bd82", + "src/generated/E.ts": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "src/teaql-schemas.ts": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "src/runtime-module.ts": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "src/generated-bootstrap.ts": "10a1133555d160947deb5c2a2756cc28162ff7e75627aeb77029be345ad523e7", + "src/generated/models/Platform.ts": "edfcd2aa09444125e319036c2dd223b1c254bcd4b2047f7c25a5f9c30cd9c877", + "src/generated/models/WorkItem.ts": "d921e1a9eda92d6feb4ecae49beb14db642be0cc25c624aa103b5a33a7254066" + }, + "assist": { + "create/work_item.md": "b9007d48bf208f1fa4380f1f86acb559ceae0475fadad9d462b3d9197e234495", + "query/work_item.md": "66f5ac5d324caa312a70324bf254fe2bb9d6c5d57a748379fe0eff7f4b9fb4da" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "trace-chain", + "model": "examples/trace-chain/model.xml", + "modelSha256": "95502038a66686580e7399dc4252df51f95cc0dc10a54657f5779dc2a5dd1e76", + "target": "examples/trace-chain/lib", + "files": { + "src/generated/Q.ts": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "src/generated/requests/PlatformRequest.ts": "bf715386dbfab4a40c2d88395b3064b7d251aae937b84392ea2f560a76d1554f", + "src/generated/requests/CustomerOrderRequest.ts": "e64907788e78c69e08ad6b6b6ae26fb7b915485d515ed4aa7feb101ef9907a9a", + "src/generated/requests/OrderItemRequest.ts": "93fb78c68c36862b7d80c0a18be71c8583d90db11d5fc2b736ce56a319a678da", + "src/generated/requests/PaymentRequest.ts": "cc7f103a76a67ea8807f32b581ba99e8bc0eb6d239309c3babcdacf9a409261c", + "src/generated/requests/PaymentAttemptRequest.ts": "273917f4319a4e9aec6f1f73be9acef7f78f9f9a19cac3da58cfff45df7ea2f0", + "src/generated/requests/ShipmentRequest.ts": "db8469db7de78791ca038f9de5b611c1b85b2abcfafdfb32303353b54b3133b3", + "src/generated/E.ts": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "src/teaql-schemas.ts": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "src/runtime-module.ts": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "src/generated-bootstrap.ts": "f84c9d8c86c682447690a2b241585b31955b4d3148dbc6cb8bf9e377f1d32ac0", + "src/generated/models/Platform.ts": "b04b4b8b8ea31d6ccac778a4ae9a20cc9e0708184ffcb8fee4f4c86b7e2b0d92", + "src/generated/models/CustomerOrder.ts": "81d7d74139cae387dced64323c62eeb13fbe14dd180a5b5d5ca62559a734c22b", + "src/generated/models/OrderItem.ts": "070bfbe18ef19145e123d79b3c2164783b087175d1e05a4c2186f22d7405b86c", + "src/generated/models/Payment.ts": "e46099d4829efc8e5fcadbe657f325d445bc3c68e06c31d5ba5b3f4ff1581084", + "src/generated/models/PaymentAttempt.ts": "65ad7d3f61b28b304c019868c346b12b7f83bec9d130a8395a00ca9d53eb3e9c", + "src/generated/models/Shipment.ts": "060aaf762614b09d596b61f9d78e3813fcd0b4c9e59935d6f4b3966ada8df474" + }, + "assist": {}, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "facet-trace", + "model": "examples/facet-trace/model.xml", + "modelSha256": "9fc6724c828e10aca8cea9f53b65460f26577f74ba5396f04376ad4f20ddc30e", + "target": "examples/facet-trace/lib", + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "src/generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "src/generated/requests/SchoolRequest.ts": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "src/generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "src/generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "src/generated/models/School.ts": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + "assist": {}, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "school-management", + "model": "examples/school-management/model.xml", + "modelSha256": "b5cd06ae44464fc29ed24de82654b47c80f546110496756aa15923cee1c511b4", + "target": "examples/school-management", + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "src/generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "src/generated/requests/SchoolRequest.ts": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "src/generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "src/generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "src/generated/models/School.ts": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + "assist": {}, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "school-reconciled", + "model": "examples/school-management/model-reconciled.xml", + "modelSha256": "896c579f3c9dded55c9728cb4af23cc8b920776e93ddcb95c8b0e95efdbcb451", + "target": "examples/school-management/src/reconciled", + "files": { + "generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "generated/requests/SchoolRequest.ts": "d3325cc673acf6e25c847f57e5a6912a0135c1a8cf675c1d5cd3548d8d54c76b", + "generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "runtime-module.ts": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "generated-bootstrap.ts": "6a29d81e4bbc4c5fd76ed3fa5e87f79b9e4ace4fc02a0afa29cfefc12e32b323", + "generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "generated/models/School.ts": "63cc850cdd588ff0b83185e608183381aca7ffc63d41bb6cf381a13eecb095f2" + }, + "assist": {}, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "browser-orders", + "model": "examples/browser-sqlite/order-model.xml", + "modelSha256": "44d20c0d236de9c79f767054deba773e11aa6ae4eaed1ede98cf7c6ed8d18495", + "target": "examples/browser-sqlite/orders-lib", + "files": { + "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "src/generated/requests/PlatformRequest.ts": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22", + "src/generated/requests/OrderStatusRequest.ts": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77", + "src/generated/requests/CustomerRequest.ts": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf", + "src/generated/requests/CustomerOrderRequest.ts": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244", + "src/generated/requests/OrderItemRequest.ts": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b", + "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "src/generated-bootstrap.ts": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c", + "src/generated/models/Platform.ts": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415", + "src/generated/models/OrderStatus.ts": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e", + "src/generated/models/Customer.ts": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a", + "src/generated/models/CustomerOrder.ts": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c", + "src/generated/models/OrderItem.ts": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64" + }, + "assist": {}, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } + }, + { + "id": "fix-e-alignment", + "model": "examples/fix-e-alignment/model.xml", + "modelSha256": "a2cf4c907cb084cb0946e993eeba586c8c0701a89fdc4a849808aa743be033b7", + "target": "examples/fix-e-alignment/generated", + "files": { + "src/generated/Q.ts": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "src/generated/requests/TenantRequest.ts": "ef0a19b22463fa587329c6dbac02ab0a36c1c0a028df8a55ae18ba9f3b5682d3", + "src/generated/requests/PurchaseOrderRequest.ts": "ff9abb76e676c2896aba610b7aec8d5aa59ee70bbfb4927a87f11e7de3ddf9b5", + "src/generated/requests/OrderItemRequest.ts": "d34f38b4b08026fd7037d7c6e4dd9aea3d2f9201fa5c775bc90ff849c765c17f", + "teaql-i18n.json": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "src/generated/E.ts": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "package.json": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "src/teaql-node-sql.ts": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "src/runtime-module.ts": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "src/generated-bootstrap.ts": "71cc3c025cf32f6e05626cb661a3fedaeccc7bf3be189a9e5c6d3facb5bc6056", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Tenant.ts": "46774bc45834a3c033c1e7da26abec9af272a768f1831728313bef4f57f8fcfd", + "src/generated/models/PurchaseOrder.ts": "07159c49037a18eb9c8cedb1e0413dc6e2dc89e1ea27d08478e30d2cf29311b2", + "src/generated/models/OrderItem.ts": "f2234d0ffe17b0f2bd9a481326125d77150921f0ac312fe893a991e0613d0405" + }, + "assist": {}, + "dependencyBindings": [] + }, + { + "id": "scalar-type-probe", + "model": "examples/scalar-type-probe/model.xml", + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762", + "target": "examples/scalar-type-probe/generated", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "assist": { + "create/scalar_type_probe.md": "ee144d03c89fe2a81e60c33fa9870aa2b68ba1fce22ad22fdf69cd6aee877871", + "expression/scalar_type_probe.md": "908cf3beebf63cea71f3a89e60e985957fa79cbc769e6a35da28db6398afa8ba" + }, + "dependencyBindings": [] + }, + { + "id": "order-management", + "model": "examples/order-management/model.xml", + "modelSha256": "a50951aa0df35cac1f4ed64ef0646860941916aed1ec0919b5b299ef4ad6a303", + "target": "examples/order-management/typescript-node-lib-core", + "files": { + "src/generated/Q.ts": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a", + "src/generated/requests/CommercePlatformRequest.ts": "bb321283f5211715fdda57fd9d002ffce07de09c7f62ad6acf82b44b5b245dac", + "src/generated/requests/CustomerRequest.ts": "eee68ef2f5729c4b7c6859b6025480cf109182ae0d87464996ab9189e966c3be", + "src/generated/requests/OrderStatusRequest.ts": "03e36b6c3605404ce8c8f45c5d17f15d8af296217d81b60202c65d65a1ad87c9", + "src/generated/requests/CustomerOrderRequest.ts": "1377852a538bae2b1be0c1332586c4af09b24d803e508f36c10c1b1026faa8b0", + "src/generated/requests/ProductRequest.ts": "42ca7706d38898b971963d20e7d28c3f8a82a2c9bb56aab6892f55ddc27f8029", + "src/generated/requests/OrderLineRequest.ts": "f6a7b5ae18de560ae7f51fd66c09f86db7c5dcac0df8f611caee696ffccc9dac", + "src/generated/requests/OrderSearchPresetRequest.ts": "73c34276b4d415f424f3222020eb5730e00aab9489ef8fc3e2108925a85d0c63", + "teaql-i18n.json": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135", + "src/generated/E.ts": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae", + "package.json": "81de7f3d7b09de596d3462ddbdd148e1a7b4b889680186efc52a3b5ae0918b11", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5", + "src/teaql-node-sql.ts": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf", + "src/runtime-module.ts": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c", + "src/generated-bootstrap.ts": "6aca696efbe1a792d3a2034c2a91272b63bee6c2f8901845a49d6c0989964b96", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/CommercePlatform.ts": "03474ffc86ad0ff40135007fca3cc5fce9aac98b6dcf3a4481e55903e82bb063", + "src/generated/models/Customer.ts": "f9559bc455bb18d82a4e7fb5d8063fc25a056861cf6c9eea30d0a0f0ee8885c9", + "src/generated/models/OrderStatus.ts": "09870c39c7120c5156035dfa2284221086a41e606ba8e575121da066615a8563", + "src/generated/models/CustomerOrder.ts": "327156068a71c8046a4a621493865b83dea9828a0ce13fbfa2cdded9d2bedebb", + "src/generated/models/Product.ts": "6b7938d74b6af15cb32c3c46f5bf6feef5f944dea564ac110665147b9f82a9e5", + "src/generated/models/OrderLine.ts": "c950492a984cbe84d318d79dd2aac7786b4c470801ba1970b2ac5c11b1c77e4f", + "src/generated/models/OrderSearchPreset.ts": "f283ee931c89cf98cd5fa4f13a3ec900e2bba5c25db1e613ae0acddda5ad0f3f" + }, + "assist": {}, + "dependencyBindings": [ + { + "name": "teaql-ts", + "generated": "npm:@teaql/teaql@0.3.1", + "selected": "file:../../.." + } + ] + }, + { + "id": "task-board", + "model": "examples/task-board/model.xml", + "modelSha256": "4a1ec513cb362e4c25a5bc9479fe27a2034558633a9e5760245919af7c601856", + "target": "examples/task-board/ts-lib-core", + "files": { + "src/generated/Q.ts": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "src/generated/requests/PlatformRequest.ts": "c20d7cdee9394dba4103a64cd5d8b44a9f9714d8a752d561f6bea13bb39d53a3", + "src/generated/requests/TaskStatusRequest.ts": "6cb4081eecc35f10aa66fa7d56ac66a406d438d60a96e6d84e5d38669faaa3c8", + "src/generated/requests/TaskRequest.ts": "312c7a5b30f86e4d656daee7cf1075d6e6388f010b2f3d46c41fd73427f9003a", + "src/generated/requests/TaskExecutionLogRequest.ts": "1484d5c9e07fe4cd46688e0fa40976091b335d2ecc736a1cd99d1e0457714b5f", + "teaql-i18n.json": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "src/generated/E.ts": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "package.json": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "src/teaql-node-sql.ts": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "src/runtime-module.ts": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "src/generated-bootstrap.ts": "a0444cc739c1a3c8cd3bc89127c2db056ca2aedf3293990c2b7fe5bfdf44afc3", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Platform.ts": "c455434e212c63a95e789131400ceba113800d6ab045778d96f142f54c014da2", + "src/generated/models/TaskStatus.ts": "8610b1aa0156f0b1dba7f6ba691b2b490dbdb2f489fa17b9894cc994e20156a4", + "src/generated/models/Task.ts": "efea9096e07268c6b0eb5fa711c397fc40d104a5e67840c6e067d01c4e83b5a8", + "src/generated/models/TaskExecutionLog.ts": "2a100aea505f12a86fd7c87ee8ead1a3313d8d7515ab5e3b4388eb31c14dd03a" + }, + "assist": { + "query/task.md": "6f99a202ad68381ffc852ed4501eac7be6194a81548850326219866fa856f9fe", + "query/task.status.md": "872774d3e3581fba58c57d5dc44cff58c7622cfb11d4da7233a28a4f41792ef4", + "query/task.name.md": "4fb7e7850b255421d55cf492132a0ca62679f5d42dff064d5fed3cc549628c41", + "query/task.task_execution_log_list.md": "1cc26492cf73ed75c5da580ffbc6b07384040356f179c06fca8dd418efba912b", + "create/task.md": "b620c41b95af918ac72c91dbc47684d3a94221af968cbd9bc60dc56fa0fff3b0", + "update/task.md": "0b5d1112589194f63315c8870f81a95aead57f1a45d730e9ef53cfabdba715bc", + "delete/task.md": "c6224e940d802fd6effa2571dc79677e061bae8cefdf1acbebbe4066423da910", + "expression/task.md": "7f215920d1eb7c00b078ed56a0d5bd2264528a3d66c4078ec1e0adaced727d48", + "expression/task_status.md": "3a2ad50910b2b656ea66156be2c26f66411b48382f4e105607dd7a3dd9b468a0", + "expression/task_execution_log.md": "11ab48e064804bb253f6543c085519ca6dd00b4c5cd59ae90fae909cfb85a4f4", + "create/task_execution_log.md": "278d1e82d28f44a5958746e0d33f2383b7f851f94ab0aa1636d636e5dc1af523", + "query/task_execution_log.md": "7942681172082053820be0f583e3fef63f7682c73aa390361ed83f41061ec4c3", + "query/task_status.md": "f0076bfcfb1e67fa745eb3c02fc1a065ee1bb02974e627d5aeb388d1c85ba0b6", + "query/platform.md": "f27fa3606997cc8312c42ec570ff42f008beeb7d1207420c4d190b30962ca211" + }, + "dependencyBindings": [] + }, + { + "id": "expression-camelcase", + "model": "examples/expression-profiles/generated/camelCase/model.xml", + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762", + "target": "examples/expression-profiles/generated/camelCase", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "assist": {}, + "dependencyBindings": [] + }, + { + "id": "expression-snake-case", + "model": "examples/expression-profiles/generated/snake_case/model.xml", + "modelSha256": "2dbbcfea6057a5dc7c7c356ea4d0dacec5d5165538f6a9c5903d4d3b64ee13c6", + "target": "examples/expression-profiles/generated/snake_case", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "assist": {}, + "dependencyBindings": [] + }, + { + "id": "expression-pascalcase", + "model": "examples/expression-profiles/generated/PascalCase/model.xml", + "modelSha256": "f836540a765f8c372bd7103a25a83ca316797253079ac63f8a1ef5ee4ded027d", + "target": "examples/expression-profiles/generated/PascalCase", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "assist": {}, + "dependencyBindings": [] + } + ], + "applied": [ + { + "relative": "examples/conformance/src/generated/Q.ts", + "beforeSha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "generatedSha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "sha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027" + }, + { + "relative": "examples/conformance/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "fe5a1387d2f630767a6aa1e076382f00f55adaf1ab26716c6f7e46b0ce6f3bd5", + "generatedSha256": "9a6c8e75b393b977c6b53517f222104e67b1ea0c8dfba773f2fd770f22b124db", + "sha256": "9a6c8e75b393b977c6b53517f222104e67b1ea0c8dfba773f2fd770f22b124db" + }, + { + "relative": "examples/conformance/src/generated/requests/WorkItemRequest.ts", + "beforeSha256": "0641a721e4a0c718a52a16ab6c097e3095fa906b62bb5d2794e8d72cac86bbeb", + "generatedSha256": "8c2d20df65964c9a0ab1775fbb3c482fa54e7634032f34828c231e1954f2bd82", + "sha256": "8c2d20df65964c9a0ab1775fbb3c482fa54e7634032f34828c231e1954f2bd82" + }, + { + "relative": "examples/conformance/src/generated/E.ts", + "beforeSha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "generatedSha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "sha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7" + }, + { + "relative": "examples/conformance/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/conformance/src/generated-search-models.ts", + "beforeSha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "generatedSha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "sha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39" + }, + { + "relative": "examples/conformance/src/teaql-schemas.ts", + "beforeSha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "generatedSha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "sha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83" + }, + { + "relative": "examples/conformance/src/runtime-module.ts", + "beforeSha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "generatedSha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "sha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e" + }, + { + "relative": "examples/conformance/src/generated-bootstrap.ts", + "beforeSha256": "3a760a0942f5e1c9a6767a319d1d3b5f217c06b065f0b1af3ba93157f98b1510", + "generatedSha256": "10a1133555d160947deb5c2a2756cc28162ff7e75627aeb77029be345ad523e7", + "sha256": "10a1133555d160947deb5c2a2756cc28162ff7e75627aeb77029be345ad523e7" + }, + { + "relative": "examples/conformance/src/generated/models/Platform.ts", + "beforeSha256": "378bf89701194d94aa3ca2fe6eb89331c2a77943bbad30bd607d02ac39125c89", + "generatedSha256": "edfcd2aa09444125e319036c2dd223b1c254bcd4b2047f7c25a5f9c30cd9c877", + "sha256": "edfcd2aa09444125e319036c2dd223b1c254bcd4b2047f7c25a5f9c30cd9c877" + }, + { + "relative": "examples/conformance/src/generated/models/WorkItem.ts", + "beforeSha256": "3739c2602861a6e1c96287af8f6f682b151dfcf6c422d862c4c046d25c288f41", + "generatedSha256": "d921e1a9eda92d6feb4ecae49beb14db642be0cc25c624aa103b5a33a7254066", + "sha256": "d921e1a9eda92d6feb4ecae49beb14db642be0cc25c624aa103b5a33a7254066" + }, + { + "relative": "examples/trace-chain/lib/src/generated/Q.ts", + "beforeSha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "generatedSha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "sha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "39c046990fca0f78bff7f061fb8f80df445e38299c58a68fb2ada753b6eebcc8", + "generatedSha256": "bf715386dbfab4a40c2d88395b3064b7d251aae937b84392ea2f560a76d1554f", + "sha256": "bf715386dbfab4a40c2d88395b3064b7d251aae937b84392ea2f560a76d1554f" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "f28f1c1c7143a7e9708bd19df338eb09cb766e89ba9bb3b0b6f2752e632c3028", + "generatedSha256": "e64907788e78c69e08ad6b6b6ae26fb7b915485d515ed4aa7feb101ef9907a9a", + "sha256": "e64907788e78c69e08ad6b6b6ae26fb7b915485d515ed4aa7feb101ef9907a9a" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "20030ab7968e281b5705ce617762af9447d2ec31f3d7d662b1f9c94d40cdabe9", + "generatedSha256": "93fb78c68c36862b7d80c0a18be71c8583d90db11d5fc2b736ce56a319a678da", + "sha256": "93fb78c68c36862b7d80c0a18be71c8583d90db11d5fc2b736ce56a319a678da" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts", + "beforeSha256": "9a710f503ddc386e0902f47a3caaef932b69c7fe4fb9e8a83b7a28a3d7e119b4", + "generatedSha256": "cc7f103a76a67ea8807f32b581ba99e8bc0eb6d239309c3babcdacf9a409261c", + "sha256": "cc7f103a76a67ea8807f32b581ba99e8bc0eb6d239309c3babcdacf9a409261c" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts", + "beforeSha256": "4aac4c415a27f4007ee0ba7468e6739ce6775be0b59b6c2cda9c2bdb0c1ea981", + "generatedSha256": "273917f4319a4e9aec6f1f73be9acef7f78f9f9a19cac3da58cfff45df7ea2f0", + "sha256": "273917f4319a4e9aec6f1f73be9acef7f78f9f9a19cac3da58cfff45df7ea2f0" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts", + "beforeSha256": "6846607eca4b581798563ca5f4e99cd739bb90b5d1d109a7809919807bf2aedd", + "generatedSha256": "db8469db7de78791ca038f9de5b611c1b85b2abcfafdfb32303353b54b3133b3", + "sha256": "db8469db7de78791ca038f9de5b611c1b85b2abcfafdfb32303353b54b3133b3" + }, + { + "relative": "examples/trace-chain/lib/src/generated/E.ts", + "beforeSha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "generatedSha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "sha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0" + }, + { + "relative": "examples/trace-chain/lib/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/trace-chain/lib/src/generated-search-models.ts", + "beforeSha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "generatedSha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "sha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820" + }, + { + "relative": "examples/trace-chain/lib/src/teaql-schemas.ts", + "beforeSha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "generatedSha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "sha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8" + }, + { + "relative": "examples/trace-chain/lib/src/runtime-module.ts", + "beforeSha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "generatedSha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "sha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33" + }, + { + "relative": "examples/trace-chain/lib/src/generated-bootstrap.ts", + "beforeSha256": "91e1f178624c29d92475497b27f522ad20963694494e2541a48e5b01f21a31d0", + "generatedSha256": "f84c9d8c86c682447690a2b241585b31955b4d3148dbc6cb8bf9e377f1d32ac0", + "sha256": "f84c9d8c86c682447690a2b241585b31955b4d3148dbc6cb8bf9e377f1d32ac0" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Platform.ts", + "beforeSha256": "cddc3065ef5203d8eb0425d35bfb953c15cf9b921e9d715749e0c497bab92b45", + "generatedSha256": "b04b4b8b8ea31d6ccac778a4ae9a20cc9e0708184ffcb8fee4f4c86b7e2b0d92", + "sha256": "b04b4b8b8ea31d6ccac778a4ae9a20cc9e0708184ffcb8fee4f4c86b7e2b0d92" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/CustomerOrder.ts", + "beforeSha256": "d2b76f37907186c454c4f4e01af784f19efc1f8fc9fe30752feb7cb1744bbc55", + "generatedSha256": "81d7d74139cae387dced64323c62eeb13fbe14dd180a5b5d5ca62559a734c22b", + "sha256": "81d7d74139cae387dced64323c62eeb13fbe14dd180a5b5d5ca62559a734c22b" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/OrderItem.ts", + "beforeSha256": "b3dbbb4be23b9f491f53b086e5a6116712dbffea94f9ac3ca21fa9c79418acd7", + "generatedSha256": "070bfbe18ef19145e123d79b3c2164783b087175d1e05a4c2186f22d7405b86c", + "sha256": "070bfbe18ef19145e123d79b3c2164783b087175d1e05a4c2186f22d7405b86c" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Payment.ts", + "beforeSha256": "195c5647261abc1f375e799b4cec94ab59a2c542b06d9730ff88fa769a1b4542", + "generatedSha256": "e46099d4829efc8e5fcadbe657f325d445bc3c68e06c31d5ba5b3f4ff1581084", + "sha256": "e46099d4829efc8e5fcadbe657f325d445bc3c68e06c31d5ba5b3f4ff1581084" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts", + "beforeSha256": "3eaf48d693743c8a8d8441c74a5d397322ddbb6cda39b5df602523c5947a1c3f", + "generatedSha256": "65ad7d3f61b28b304c019868c346b12b7f83bec9d130a8395a00ca9d53eb3e9c", + "sha256": "65ad7d3f61b28b304c019868c346b12b7f83bec9d130a8395a00ca9d53eb3e9c" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Shipment.ts", + "beforeSha256": "5654989bcd567954872a6c08800a5a564698a20a6dd90e453e2f85e445f0d390", + "generatedSha256": "060aaf762614b09d596b61f9d78e3813fcd0b4c9e59935d6f4b3966ada8df474", + "sha256": "060aaf762614b09d596b61f9d78e3813fcd0b4c9e59935d6f4b3966ada8df474" + }, + { + "relative": "examples/facet-trace/lib/src/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "generatedSha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "sha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "generatedSha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "sha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts", + "beforeSha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "generatedSha256": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "sha256": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5" + }, + { + "relative": "examples/facet-trace/lib/src/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/facet-trace/lib/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/facet-trace/lib/src/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/facet-trace/lib/src/teaql-schemas.ts", + "beforeSha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "generatedSha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "sha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9" + }, + { + "relative": "examples/facet-trace/lib/src/runtime-module.ts", + "beforeSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "generatedSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "sha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae" + }, + { + "relative": "examples/facet-trace/lib/src/generated-bootstrap.ts", + "beforeSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "generatedSha256": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "sha256": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/Platform.ts", + "beforeSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "generatedSha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "sha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/SchoolType.ts", + "beforeSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "generatedSha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "sha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/School.ts", + "beforeSha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a", + "generatedSha256": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7", + "sha256": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + { + "relative": "examples/school-management/src/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/school-management/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "generatedSha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "sha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60" + }, + { + "relative": "examples/school-management/src/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "generatedSha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "sha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118" + }, + { + "relative": "examples/school-management/src/generated/requests/SchoolRequest.ts", + "beforeSha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "generatedSha256": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "sha256": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5" + }, + { + "relative": "examples/school-management/src/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/school-management/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/school-management/src/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/school-management/src/teaql-schemas.ts", + "beforeSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "generatedSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "sha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c" + }, + { + "relative": "examples/school-management/src/runtime-module.ts", + "beforeSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "generatedSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "sha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae" + }, + { + "relative": "examples/school-management/src/generated-bootstrap.ts", + "beforeSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "generatedSha256": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "sha256": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5" + }, + { + "relative": "examples/school-management/src/generated/models/Platform.ts", + "beforeSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "generatedSha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "sha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d" + }, + { + "relative": "examples/school-management/src/generated/models/SchoolType.ts", + "beforeSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "generatedSha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "sha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08" + }, + { + "relative": "examples/school-management/src/generated/models/School.ts", + "beforeSha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a", + "generatedSha256": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7", + "sha256": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + { + "relative": "examples/school-management/src/reconciled/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts", + "beforeSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "generatedSha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "sha256": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "generatedSha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "sha256": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts", + "beforeSha256": "fac23dbff189b41421432bb7efd6dcddcfe4fd96d6eaf004fda78e17567c62cd", + "generatedSha256": "d3325cc673acf6e25c847f57e5a6912a0135c1a8cf675c1d5cd3548d8d54c76b", + "sha256": "d3325cc673acf6e25c847f57e5a6912a0135c1a8cf675c1d5cd3548d8d54c76b" + }, + { + "relative": "examples/school-management/src/reconciled/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/school-management/src/reconciled/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/school-management/src/reconciled/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/school-management/src/reconciled/teaql-schemas.ts", + "beforeSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "generatedSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "sha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c" + }, + { + "relative": "examples/school-management/src/reconciled/runtime-module.ts", + "beforeSha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "generatedSha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "sha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61" + }, + { + "relative": "examples/school-management/src/reconciled/generated-bootstrap.ts", + "beforeSha256": "1513d365488b3f1016973c158034e450b06c6601dec5c109c4fa2bd369aef736", + "generatedSha256": "6a29d81e4bbc4c5fd76ed3fa5e87f79b9e4ace4fc02a0afa29cfefc12e32b323", + "sha256": "6a29d81e4bbc4c5fd76ed3fa5e87f79b9e4ace4fc02a0afa29cfefc12e32b323" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/Platform.ts", + "beforeSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "generatedSha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "sha256": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/SchoolType.ts", + "beforeSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "generatedSha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "sha256": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/School.ts", + "beforeSha256": "125e5812cf6a9b2ac14614ea98b6e0f514d09c15db605a55c347ff1ac35a8185", + "generatedSha256": "63cc850cdd588ff0b83185e608183381aca7ffc63d41bb6cf381a13eecb095f2", + "sha256": "63cc850cdd588ff0b83185e608183381aca7ffc63d41bb6cf381a13eecb095f2" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/Q.ts", + "beforeSha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "generatedSha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "sha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "d4aeb3fc4d61fcca6628617e61b11eedbe0df48920275a8ad50c7f97e401e890", + "generatedSha256": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22", + "sha256": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts", + "beforeSha256": "735cffc0e97d95bf2be8af3efebd815ed4beb9a7ea49b0762b7234ae9f67139f", + "generatedSha256": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77", + "sha256": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts", + "beforeSha256": "e949e3b0f03613224e8c756e1217672e9e1a972527797461539fb3e539b7b0c9", + "generatedSha256": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf", + "sha256": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "bc9aee5b8b9ee262d6aa52f243b06a8b6527493b9284e3a6a2ac3e6c86ec7c4d", + "generatedSha256": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244", + "sha256": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "1bace871f045b60e27f8cc184e491a8cbf44a9a90aa8f3af74ea4be53d5df2d6", + "generatedSha256": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b", + "sha256": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/E.ts", + "beforeSha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "generatedSha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "sha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated-search-models.ts", + "beforeSha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "generatedSha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "sha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/teaql-schemas.ts", + "beforeSha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "generatedSha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "sha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/runtime-module.ts", + "beforeSha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "generatedSha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "sha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts", + "beforeSha256": "01e5a1a0501f7cb756d74b2f4c13ab8654ab0b6623b0d276f6c120508af6b2d5", + "generatedSha256": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c", + "sha256": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts", + "beforeSha256": "be35c375bd7f267e8df179e6aade7d4c158bb86274b2c6823975e9bda4362a70", + "generatedSha256": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415", + "sha256": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts", + "beforeSha256": "ae5b3bbbe9ecaa46048eb3fb99cd767c347d312afcb604d4f5bc0cb921b4dfe2", + "generatedSha256": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e", + "sha256": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts", + "beforeSha256": "47e2a271fbd84be36affa0e7e5fe77d489f32735e69f137371ffcf0edeb3bcba", + "generatedSha256": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a", + "sha256": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts", + "beforeSha256": "11dd27a3b310cb88a495df5df3241bdc0d7e42834593b7a5b475d7d76755ee3c", + "generatedSha256": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c", + "sha256": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts", + "beforeSha256": "45543cf484bf7b57b542bedd42d7f6f1c2650678d80b11da2ddc63925e32e706", + "generatedSha256": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64", + "sha256": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/Q.ts", + "beforeSha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "generatedSha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "sha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts", + "beforeSha256": "3686c7f2c2d18bb7960b88c4f4a636c83d96ba97a6d31620cefee2f218722e3c", + "generatedSha256": "ef0a19b22463fa587329c6dbac02ab0a36c1c0a028df8a55ae18ba9f3b5682d3", + "sha256": "ef0a19b22463fa587329c6dbac02ab0a36c1c0a028df8a55ae18ba9f3b5682d3" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts", + "beforeSha256": "5e6c59ead789538fdd469a70255f09144dc12c93c9ad10017629f0b618ab7653", + "generatedSha256": "ff9abb76e676c2896aba610b7aec8d5aa59ee70bbfb4927a87f11e7de3ddf9b5", + "sha256": "ff9abb76e676c2896aba610b7aec8d5aa59ee70bbfb4927a87f11e7de3ddf9b5" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "896c43cb390a9b5d9ac76cde78dc296fa55a2b0e8e2aca344daa3ebb33fa5a63", + "generatedSha256": "d34f38b4b08026fd7037d7c6e4dd9aea3d2f9201fa5c775bc90ff849c765c17f", + "sha256": "d34f38b4b08026fd7037d7c6e4dd9aea3d2f9201fa5c775bc90ff849c765c17f" + }, + { + "relative": "examples/fix-e-alignment/generated/teaql-i18n.json", + "beforeSha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "generatedSha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "sha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/E.ts", + "beforeSha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "generatedSha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "sha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b" + }, + { + "relative": "examples/fix-e-alignment/generated/package.json", + "beforeSha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "generatedSha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "sha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9" + }, + { + "relative": "examples/fix-e-alignment/generated/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated-search-models.ts", + "beforeSha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "generatedSha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "sha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-node-sql.ts", + "beforeSha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "generatedSha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "sha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3" + }, + { + "relative": "examples/fix-e-alignment/generated/src/runtime-module.ts", + "beforeSha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "generatedSha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "sha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated-bootstrap.ts", + "beforeSha256": "f16c9576076922c99fab0b88ab36c7c21b1560dce451d99d44b281bbedc5c237", + "generatedSha256": "71cc3c025cf32f6e05626cb661a3fedaeccc7bf3be189a9e5c6d3facb5bc6056", + "sha256": "71cc3c025cf32f6e05626cb661a3fedaeccc7bf3be189a9e5c6d3facb5bc6056" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/Tenant.ts", + "beforeSha256": "18ecfca38a353d05fb3a28ca82d9a54e0b466d91c4c5225deafa95d9cdf11434", + "generatedSha256": "46774bc45834a3c033c1e7da26abec9af272a768f1831728313bef4f57f8fcfd", + "sha256": "46774bc45834a3c033c1e7da26abec9af272a768f1831728313bef4f57f8fcfd" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/PurchaseOrder.ts", + "beforeSha256": "ab23220c528f82e51a507ce17aea90e706234b638aa4b89eee326d15bb39d9e0", + "generatedSha256": "07159c49037a18eb9c8cedb1e0413dc6e2dc89e1ea27d08478e30d2cf29311b2", + "sha256": "07159c49037a18eb9c8cedb1e0413dc6e2dc89e1ea27d08478e30d2cf29311b2" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/OrderItem.ts", + "beforeSha256": "84408c401d116fb8edce9d0ef5bbbc2ed568c46ab0dc8ac517743e9fd80a8ae6", + "generatedSha256": "f2234d0ffe17b0f2bd9a481326125d77150921f0ac312fe893a991e0613d0405", + "sha256": "f2234d0ffe17b0f2bd9a481326125d77150921f0ac312fe893a991e0613d0405" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "generatedSha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "sha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "generatedSha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "sha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad" + }, + { + "relative": "examples/scalar-type-probe/generated/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/E.ts", + "beforeSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "generatedSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "sha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f" + }, + { + "relative": "examples/scalar-type-probe/generated/package.json", + "beforeSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/scalar-type-probe/generated/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/scalar-type-probe/generated/src/runtime-module.ts", + "beforeSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "generatedSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "sha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "sha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/models/TypePlatform.ts", + "beforeSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "generatedSha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "sha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "generatedSha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8", + "sha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/Q.ts", + "beforeSha256": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a", + "generatedSha256": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a", + "sha256": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts", + "beforeSha256": "b52beef112067fdec2f4ad0ea49d6edc12faf982bd9943b25424a5807ca0461c", + "generatedSha256": "bb321283f5211715fdda57fd9d002ffce07de09c7f62ad6acf82b44b5b245dac", + "sha256": "bb321283f5211715fdda57fd9d002ffce07de09c7f62ad6acf82b44b5b245dac" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts", + "beforeSha256": "f5ef064cc780f439173e1b78e643bbc53f92f07cfb63dca60374bbe220207f4e", + "generatedSha256": "eee68ef2f5729c4b7c6859b6025480cf109182ae0d87464996ab9189e966c3be", + "sha256": "eee68ef2f5729c4b7c6859b6025480cf109182ae0d87464996ab9189e966c3be" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts", + "beforeSha256": "1682ba1e66ed78eb7870c8b947f6f6cc61d91629fe0f0e360379763ba9afddd3", + "generatedSha256": "03e36b6c3605404ce8c8f45c5d17f15d8af296217d81b60202c65d65a1ad87c9", + "sha256": "03e36b6c3605404ce8c8f45c5d17f15d8af296217d81b60202c65d65a1ad87c9" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "42d0af0b3f801f8a9086cf9bf945e82ccbf99fd93377a6dfc23eba8b655ac8ee", + "generatedSha256": "1377852a538bae2b1be0c1332586c4af09b24d803e508f36c10c1b1026faa8b0", + "sha256": "1377852a538bae2b1be0c1332586c4af09b24d803e508f36c10c1b1026faa8b0" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts", + "beforeSha256": "4dbd632a3c0d1f1e0191af73633200c5ce2102531fc8c275b600ae628685275d", + "generatedSha256": "42ca7706d38898b971963d20e7d28c3f8a82a2c9bb56aab6892f55ddc27f8029", + "sha256": "42ca7706d38898b971963d20e7d28c3f8a82a2c9bb56aab6892f55ddc27f8029" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts", + "beforeSha256": "c7625ef9ebe20f8ee0a6f0dc1c7be4bfc42a6751ded68735be17478254bcaa62", + "generatedSha256": "f6a7b5ae18de560ae7f51fd66c09f86db7c5dcac0df8f611caee696ffccc9dac", + "sha256": "f6a7b5ae18de560ae7f51fd66c09f86db7c5dcac0df8f611caee696ffccc9dac" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts", + "beforeSha256": "02808647c11620de5098c6d6ec01e06b3738d0c0563c26c000fd6b191bdf64c6", + "generatedSha256": "73c34276b4d415f424f3222020eb5730e00aab9489ef8fc3e2108925a85d0c63", + "sha256": "73c34276b4d415f424f3222020eb5730e00aab9489ef8fc3e2108925a85d0c63" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/teaql-i18n.json", + "beforeSha256": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135", + "generatedSha256": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135", + "sha256": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/E.ts", + "beforeSha256": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae", + "generatedSha256": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae", + "sha256": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/package.json", + "beforeSha256": "81de7f3d7b09de596d3462ddbdd148e1a7b4b889680186efc52a3b5ae0918b11", + "generatedSha256": "e716061a9ba54b60ac22146437bad3b95835027dccc980014eb760dd7c7e0c1c", + "sha256": "81de7f3d7b09de596d3462ddbdd148e1a7b4b889680186efc52a3b5ae0918b11" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated-search-models.ts", + "beforeSha256": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5", + "generatedSha256": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5", + "sha256": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts", + "beforeSha256": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf", + "generatedSha256": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf", + "sha256": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/runtime-module.ts", + "beforeSha256": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c", + "generatedSha256": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c", + "sha256": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated-bootstrap.ts", + "beforeSha256": "5273e61aca2b4f61980d12b239850c2cbe53034ab4ff2728aec79331202e0218", + "generatedSha256": "6aca696efbe1a792d3a2034c2a91272b63bee6c2f8901845a49d6c0989964b96", + "sha256": "6aca696efbe1a792d3a2034c2a91272b63bee6c2f8901845a49d6c0989964b96" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts", + "beforeSha256": "e1b01e6a42c8fdadc1634f45e8f700eed0d3c3fa841fb22cb9b3c7cf22199a81", + "generatedSha256": "03474ffc86ad0ff40135007fca3cc5fce9aac98b6dcf3a4481e55903e82bb063", + "sha256": "03474ffc86ad0ff40135007fca3cc5fce9aac98b6dcf3a4481e55903e82bb063" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts", + "beforeSha256": "aafef115b28e5075aa280d9eacfd06feefff4ecf298f35a7c9057ae221738ede", + "generatedSha256": "f9559bc455bb18d82a4e7fb5d8063fc25a056861cf6c9eea30d0a0f0ee8885c9", + "sha256": "f9559bc455bb18d82a4e7fb5d8063fc25a056861cf6c9eea30d0a0f0ee8885c9" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts", + "beforeSha256": "dc8467ddfa4bd759d4a30cd49f8990a5bbcd67d6a36467c4e23623fa23c44a2d", + "generatedSha256": "09870c39c7120c5156035dfa2284221086a41e606ba8e575121da066615a8563", + "sha256": "09870c39c7120c5156035dfa2284221086a41e606ba8e575121da066615a8563" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts", + "beforeSha256": "47bd5e38d16373e70860e021383921ee4c6d22f9db2de7d46d07d3592b0a7363", + "generatedSha256": "327156068a71c8046a4a621493865b83dea9828a0ce13fbfa2cdded9d2bedebb", + "sha256": "327156068a71c8046a4a621493865b83dea9828a0ce13fbfa2cdded9d2bedebb" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts", + "beforeSha256": "cedd9d09a18ccdb8f68943729e300390da46c9790b9601506124cfd968b085ef", + "generatedSha256": "6b7938d74b6af15cb32c3c46f5bf6feef5f944dea564ac110665147b9f82a9e5", + "sha256": "6b7938d74b6af15cb32c3c46f5bf6feef5f944dea564ac110665147b9f82a9e5" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts", + "beforeSha256": "1a63ec46b4f02d04efeed5bbe3c7377293c6cea09d336556a84db2c6f67d3e2e", + "generatedSha256": "c950492a984cbe84d318d79dd2aac7786b4c470801ba1970b2ac5c11b1c77e4f", + "sha256": "c950492a984cbe84d318d79dd2aac7786b4c470801ba1970b2ac5c11b1c77e4f" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts", + "beforeSha256": "e02d8a9db91b94756869a067922f47b638f347c2051900f4f786762c1e3b1266", + "generatedSha256": "f283ee931c89cf98cd5fa4f13a3ec900e2bba5c25db1e613ae0acddda5ad0f3f", + "sha256": "f283ee931c89cf98cd5fa4f13a3ec900e2bba5c25db1e613ae0acddda5ad0f3f" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/Q.ts", + "beforeSha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "generatedSha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "sha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "d02f8397132992a40731bdeecb4d321bcd4807a48a940d211b7bea8ef38f9d08", + "generatedSha256": "c20d7cdee9394dba4103a64cd5d8b44a9f9714d8a752d561f6bea13bb39d53a3", + "sha256": "c20d7cdee9394dba4103a64cd5d8b44a9f9714d8a752d561f6bea13bb39d53a3" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts", + "beforeSha256": "501ed560c7fef2143b6df6dd80084824ae3bfa623c499cf624613465352e19ba", + "generatedSha256": "6cb4081eecc35f10aa66fa7d56ac66a406d438d60a96e6d84e5d38669faaa3c8", + "sha256": "6cb4081eecc35f10aa66fa7d56ac66a406d438d60a96e6d84e5d38669faaa3c8" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts", + "beforeSha256": "a66bb1ce89a44a1c91219f6f26c002f20d496a6ae58611bf596fd59eb2c46185", + "generatedSha256": "312c7a5b30f86e4d656daee7cf1075d6e6388f010b2f3d46c41fd73427f9003a", + "sha256": "312c7a5b30f86e4d656daee7cf1075d6e6388f010b2f3d46c41fd73427f9003a" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts", + "beforeSha256": "451abd611b6bec0ea8470a1d4337ad48e389892d9475e8f5efd6dcba9517de28", + "generatedSha256": "1484d5c9e07fe4cd46688e0fa40976091b335d2ecc736a1cd99d1e0457714b5f", + "sha256": "1484d5c9e07fe4cd46688e0fa40976091b335d2ecc736a1cd99d1e0457714b5f" + }, + { + "relative": "examples/task-board/ts-lib-core/teaql-i18n.json", + "beforeSha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "generatedSha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "sha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/E.ts", + "beforeSha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "generatedSha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "sha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7" + }, + { + "relative": "examples/task-board/ts-lib-core/package.json", + "beforeSha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "generatedSha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "sha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8" + }, + { + "relative": "examples/task-board/ts-lib-core/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated-search-models.ts", + "beforeSha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "generatedSha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "sha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-node-sql.ts", + "beforeSha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "generatedSha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "sha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8" + }, + { + "relative": "examples/task-board/ts-lib-core/src/runtime-module.ts", + "beforeSha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "generatedSha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "sha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated-bootstrap.ts", + "beforeSha256": "89796bbdfdcf09c31cffbd64c654853a163b66511776b996594fe5cbf7c5ab01", + "generatedSha256": "a0444cc739c1a3c8cd3bc89127c2db056ca2aedf3293990c2b7fe5bfdf44afc3", + "sha256": "a0444cc739c1a3c8cd3bc89127c2db056ca2aedf3293990c2b7fe5bfdf44afc3" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/Platform.ts", + "beforeSha256": "2e8dc7c1c3ca171b352b1ed7d318b8b2506f02645f167e30f569ce9be4011707", + "generatedSha256": "c455434e212c63a95e789131400ceba113800d6ab045778d96f142f54c014da2", + "sha256": "c455434e212c63a95e789131400ceba113800d6ab045778d96f142f54c014da2" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts", + "beforeSha256": "cf236b6d0b08056c578e9fa6681dc141ab7b155aacaa44e339c9974a504ad456", + "generatedSha256": "8610b1aa0156f0b1dba7f6ba691b2b490dbdb2f489fa17b9894cc994e20156a4", + "sha256": "8610b1aa0156f0b1dba7f6ba691b2b490dbdb2f489fa17b9894cc994e20156a4" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/Task.ts", + "beforeSha256": "a80de823264c6abda17d177b762462b3791f6d2d377adfdb9282a67b5239feaf", + "generatedSha256": "efea9096e07268c6b0eb5fa711c397fc40d104a5e67840c6e067d01c4e83b5a8", + "sha256": "efea9096e07268c6b0eb5fa711c397fc40d104a5e67840c6e067d01c4e83b5a8" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts", + "beforeSha256": "271b9d3a51cbf86cd2190b1f6798bca3414594c4d41b74719c7d3c50ff3873ef", + "generatedSha256": "2a100aea505f12a86fd7c87ee8ead1a3313d8d7515ab5e3b4388eb31c14dd03a", + "sha256": "2a100aea505f12a86fd7c87ee8ead1a3313d8d7515ab5e3b4388eb31c14dd03a" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "generatedSha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "sha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "generatedSha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "sha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/E.ts", + "beforeSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "generatedSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "sha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/package.json", + "beforeSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/runtime-module.ts", + "beforeSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "generatedSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "sha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "sha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/models/TypePlatform.ts", + "beforeSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "generatedSha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "sha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "generatedSha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8", + "sha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "generatedSha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "sha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "generatedSha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "sha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/E.ts", + "beforeSha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "generatedSha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "sha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/package.json", + "beforeSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/runtime-module.ts", + "beforeSha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "generatedSha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "sha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "sha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/models/TypePlatform.ts", + "beforeSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "generatedSha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "sha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "generatedSha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8", + "sha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "generatedSha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "sha256": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "generatedSha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "sha256": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/E.ts", + "beforeSha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "generatedSha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "sha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/package.json", + "beforeSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-ts.ts", + "beforeSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generatedSha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "sha256": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated-search-models.ts", + "beforeSha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "generatedSha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "sha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/runtime-module.ts", + "beforeSha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "generatedSha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "sha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "sha256": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/models/TypePlatform.ts", + "beforeSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "generatedSha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "sha256": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "generatedSha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8", + "sha256": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + } + ] +} diff --git a/source/teaql-ts/examples/natural-messages/AGENTS.md b/source/teaql-ts/examples/natural-messages/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..a8f6834783687e702f2d4060b6fc88f1371f5bac --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/AGENTS.md @@ -0,0 +1,19 @@ +# Natural Checker messages example + +Run `node scripts/verify-natural-messages.cjs --full --example --output +/new/evidence/path` from the runtime repository. The output path must not exist. + +The example consumes the complete immutable generated library and model under +`fixture/`. Do not read or edit generated library source for +API discovery. Use current model-aware Assist when application code needs an +operation not already demonstrated here. Its generated Runtime Module installs +presentation metadata and actual Checker rules. Do not replace them with manual +descriptors or hand-written bounds to make the example pass. + +Keep generated Q bounded and supply comment/purpose. Use generated audited Save +for every write. Never replace the scalar-length check with the mask's length or +dump the secret into diagnostics. The verifier runs twice against the same retained +SQLite database and JSON store, checks the unchanged-parent graph origin and a +single safe customer renderer invocation, and disposes only its owned source +copy, dependencies and outputs. Regenerate the fixture through +`TypescriptNaturalMessagesGenerationTest`; preserve its manifest and evaluation. diff --git a/source/teaql-ts/examples/natural-messages/README.md b/source/teaql-ts/examples/natural-messages/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1103bba48b17e39393b653d5de86c32e12e059b1 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/README.md @@ -0,0 +1,45 @@ +# Natural Checker messages from generated Q and E + +The backend returns `The name of the 2nd entry is required.` or +`请填写第2项明细的名称。`, while retaining `/entryList/1/name`. The frontend can +display the message directly and use the structured pointer independently. + +```bash +node scripts/verify-natural-messages.cjs --full --example --output /new/evidence/path +``` + +This source-only gate installs pinned dependencies offline in an owned temporary +copy, typechecks, runs native tests, builds production bundles, checks the message +module's browser bundle, and runs this example twice against the same SQLite +database and file-backed JSON store. +Only `better-sqlite3` and `esbuild` install scripts are enabled in the disposable +execution manifest. The candidate manifest and dependency versions do not change. +Build outputs and dependencies are removed after owned child processes exit; +compact logs, source hashes, response JSON and both data stores remain. +Source snapshots exclude only the rebuilt `dist/` tree. Missing actual source, +source symlinks and symlink ancestors still fail the gate; three focused tests +check that boundary before dependency installation. + +The complete unedited Catalog/Entry library in `fixture/` is produced by +`TypescriptNaturalMessagesGenerationTest`. The model supplies Chinese labels and +classifies `name` as sensitive. Its generated module installs immutable message +descriptors automatically; no presentation model is installed by the application +or retained on its Context. The actual generated Checker requires a name and +limits it to 100 Unicode scalar values. + +An unchanged parent and two edited children form the failing graph. The second +child fails required checks in English and Chinese, then exceeds the real length +bound with 101 private scalars. The message keeps that original count after +masking. A custom renderer is called once, and its safe text survives graph-path +relocation without restoring the private input. Every rejection precedes provider +work and committed mutation audits; the file store also remains byte-identical. +After restoring the first edit, audited Save updates only the corrected second +child. Generated Q reloads values and E verifies them. Both provider paths use +the same runtime privacy and rendering contracts. + +The complete repository example inventory and published-artifact acceptance +remain separate gates. +The runtime renderer is browser-safe and has no Node-only context-local dependency. + +Tracking: [teaql-ts #65](https://github.com/teaql/teaql-ts/issues/65), +[conformance #244](https://github.com/teaql/teaql-conformance/issues/244). diff --git a/source/teaql-ts/examples/natural-messages/fixture/evaluation.json b/source/teaql-ts/examples/natural-messages/fixture/evaluation.json new file mode 100644 index 0000000000000000000000000000000000000000..bb2307fa6bd39f3424ce3d4a6565d4833a4146a7 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/evaluation.json @@ -0,0 +1,108 @@ +{ + "solids" : [ { + "ruleId" : "KSML-UPLOAD-001", + "title" : "Model upload is non-empty", + "message" : "The upload contains 1 files.", + "path" : "model.zip", + "objectName" : null, + "fieldName" : null, + "xmlPath" : null, + "lineNumber" : null, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "model.zip" + }, { + "ruleId" : "KSML-UPLOAD-005", + "title" : "Valid entrypoint found", + "message" : "Resolved entrypoint: model.xml", + "path" : "model.xml", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "model.xml" + }, { + "ruleId" : "KSML-XML-002", + "title" : "XML is well-formed", + "message" : "The XML document model.xml was parsed successfully.", + "path" : "model.xml", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "model.xml" + }, { + "ruleId" : "KSML-ROOT-003", + "title" : "Standard root name", + "message" : "Root name 'natural-message-service' is well-formed.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "/root" + }, { + "ruleId" : "KSML-ROOT-008", + "title" : "Default JSON field naming", + "message" : "External JSON business fields use the default camelCase profile.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "/root" + }, { + "ruleId" : "KSML-REFERENCE-003", + "title" : "Reference target exists", + "message" : "Reference 'catalog' in 'entry' successfully resolves to target object 'catalog'.", + "path" : "/root/entry/catalog", + "objectName" : "entry", + "fieldName" : "catalog", + "xmlPath" : "model.xml", + "lineNumber" : 3, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "entry.catalog" + }, { + "ruleId" : "KSML-DOMAIN-ROOT-003", + "title" : "One domain root found", + "message" : "Exactly one domain root candidate 'catalog' was found.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "/root" + } ], + "warnings" : [ { + "ruleId" : "KSML-OBJECT-001", + "title" : "Missing object display metadata", + "message" : "Object 'catalog' is missing display metadata: _module, _module_key", + "path" : "/root/catalog", + "objectName" : "catalog", + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 2, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "catalog" + }, { + "ruleId" : "KSML-OBJECT-001", + "title" : "Missing object display metadata", + "message" : "Object 'entry' is missing display metadata: _module, _module_key", + "path" : "/root/entry", + "objectName" : "entry", + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 3, + "action" : "Check agents/ERROR-FIX.md", + "reportTarget" : "entry" + } ], + "suggestions" : [ ], + "errors" : [ ], + "privacyFindings" : [ ], + "privacyRegions" : [ ], + "errorSummaries" : [ ] +} diff --git a/source/teaql-ts/examples/natural-messages/fixture/generated-files.json b/source/teaql-ts/examples/natural-messages/fixture/generated-files.json new file mode 100644 index 0000000000000000000000000000000000000000..a110acedbae641bb1f3d937a56b38b3753ec7310 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/generated-files.json @@ -0,0 +1,19 @@ +{ + "package.json" : "586e300694b0099b058720ff213730601a9ec25ae6a52f4b15aea5c9fb675054", + "src/generated-bootstrap.ts" : "677a9cf250a379a43c2be66dec7c34ba16f7c40902ace18ac4848956244a25d2", + "src/generated-search-models.ts" : "cbef8c139ad276aa2582b260f9bdab1e890964527805493a3887f1bd207f1bc6", + "src/generated/E.ts" : "169d045fc67673c9bcab19851a962af445193be59d70fd5566a59977056c371a", + "src/generated/Q.ts" : "482e727f3b0cb5c10dce9924a3aff1d64b0b68d90f2f20374cc2b89018fa9f82", + "src/generated/models/Catalog.ts" : "f92aaedff2688e897239d149d6f2723792da22588a8737c38f597344de012aea", + "src/generated/models/Entry.ts" : "0857f86b45f16ba0222220fe12933fd4afa584d0ff826dd206dd6d0c0d8b35da", + "src/generated/requests/CatalogRequest.ts" : "accacd09d03c992cef2c7a93cf634387d93c37a58c021879fc52ccb0d59283ba", + "src/generated/requests/EntryRequest.ts" : "b3f3cd544d96ffbcbad6d7203ef3b4735adb60025cecfd2c7fd1f36f9a3cec48", + "src/runtime-module.ts" : "4e379d29cedf6485d3435fa6eb0ffd62d97e1478c5832ec6262d0258b69ef574", + "src/teaql-node-sql.ts" : "92133605afea747ce3abdc7b547949860f1761aa2866ca4de8ddada2ad964af3", + "src/teaql-node-sqlite.ts" : "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/teaql-ts.ts" : "1f0af27f2d14f6bab1963cae88e3776b2fde5e01aa22befd463a50d7a6fb4bab", + "teaql-i18n.json" : "3142adc809a66c3f45df816e926967273ba7fcf3470c00629fcd6fa8da693f06", + "teaql/checker-model.json" : "5ac0524fcb22c68970fc358b685d10081e47048af423951514e8d28ec2bd0bc6", + "teaql/model-provenance.json" : "f03bf5d79f88a745afce41a9c9dd865ba764b8a5525e884468941d835e987ff6", + "tsconfig.json" : "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" +} diff --git a/source/teaql-ts/examples/natural-messages/fixture/generation.json b/source/teaql-ts/examples/natural-messages/fixture/generation.json new file mode 100644 index 0000000000000000000000000000000000000000..dedf2dd11620aadb7e0abe2d1cb43d102c969925 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/generation.json @@ -0,0 +1,11 @@ +{ + "schema": "teaql.generated-natural-checker-fixture/v1", + "generatorCommit": "ff5d00f5", + "scope": "typescript-node-lib-core", + "test": "TypescriptNaturalMessagesGenerationTest", + "generationEvidence": "2026-11-12-natural-checker-typescript-generation-qualified", + "runtimeTarget": "0.5.0-dev.0", + "dependencyBinding": "repository-local source via the controlled Jest module mapper", + "sourceFixtureEdited": false, + "publicPublication": false +} diff --git a/source/teaql-ts/examples/natural-messages/fixture/model.xml b/source/teaql-ts/examples/natural-messages/fixture/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f6d3f3263088a706cb4ce52e336bb1d049dbad92 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/model.xml @@ -0,0 +1,5 @@ + + + + diff --git a/source/teaql-ts/examples/natural-messages/fixture/package.json b/source/teaql-ts/examples/natural-messages/fixture/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cfd6324efdabd9451aa7fd3fbb7c2cdae70d0510 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/package.json @@ -0,0 +1,18 @@ +{ + "name": "natural-message-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.5.0-dev.0", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated-bootstrap.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..63c96a67e0d10df872681959dd87ef07027dcef1 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Catalog } from './generated/models/Catalog'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.catalogs().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Catalog.teaqlBootstrapNew('1'); + domainRoot.updateName("Catalog"); + await domainRoot.auditAs('create generated Domain Root Catalog').save(context); + } + context.withActiveRoot({ entity: 'Catalog', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated-search-models.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd86dfdd46dac83e0f0bce14b1acee7677203ea2 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated-search-models.ts @@ -0,0 +1,45 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Catalog": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "entryList": "Entry", + }), + }), + "Entry": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "catalog": "integer" as const, + "name": "string" as const, + "born_at": "timestamp" as const, + "bornAt": "timestamp" as const, + "touched_at": "timestamp" as const, + "touchedAt": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "catalog": "catalog", + "name": "name", + "born_at": "bornAt", + "bornAt": "bornAt", + "touched_at": "touchedAt", + "touchedAt": "touchedAt", + "version": "version", + }), + relations: Object.freeze({ + "catalog": "Catalog", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/E.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a944412b8fa5e2aac349d1b6896cfd79ec9d454 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/E.ts @@ -0,0 +1,320 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { Catalog } from './models/Catalog'; +import { Entry } from './models/Entry'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class CatalogExpression { + constructor( + private readonly value: Catalog | null | undefined, + private readonly root = 'Catalog(null)', + private readonly path = ExpressionPath.root('E.catalog()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Catalog | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + entryList(): EntryListExpression { + const path = this.path.member('entry_list', 'entryList'); + if (this.notLoaded) { + return new EntryListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return EntryListExpression.missing(this.root, path); + if (!this.value.isLoaded('entryList')) { + return new EntryListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'entry_list')); + } + return new EntryListExpression( + this.value.entryList(), this.root, path, + ); + } +} + +export class EntryExpression { + constructor( + private readonly value: Entry | null | undefined, + private readonly root = 'Entry(null)', + private readonly path = ExpressionPath.root('E.entry()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Entry | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + bornAt(): ValueExpression { + const path = this.path.member('born_at', 'bornAt'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('bornAt')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'born_at'), + ); + } + return new ValueExpression(this.value.bornAt); + } + + touchedAt(): ValueExpression { + const path = this.path.member('touched_at', 'touchedAt'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('touchedAt')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'touched_at'), + ); + } + return new ValueExpression(this.value.touchedAt); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + catalogId(): ValueExpression { + const path = this.path.member('catalog', 'catalogId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('catalog')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'catalog'), + ); + } + const reference = this.value.catalog; + return new ValueExpression( + reference instanceof Catalog + ? reference.id : reference as string | number | undefined, + ); + } + + catalog(): CatalogExpression { + const path = this.path.member('catalog', 'catalog'); + if (this.notLoaded) { + return new CatalogExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CatalogExpression(undefined, this.root, path); + if (!this.value.isLoaded('catalog')) { + return new CatalogExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'catalog')); + } + const relation = this.value.catalog; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Catalog)) { + return new CatalogExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'catalog')); + } + const target = relation instanceof Catalog ? relation : undefined; + return new CatalogExpression(target, this.root, path); + } + +} + +export class CatalogListExpression { + constructor( + private readonly items: readonly Catalog[], + private readonly root = 'Catalog(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CatalogListExpression { + return new CatalogListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): CatalogExpression { + return this.item(0, true); + } + + get(index: number): CatalogExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): CatalogExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new CatalogExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new CatalogExpression(undefined, this.root, itemPath) + : new CatalogExpression(this.items[index], this.root, itemPath); + } +} + +export class EntryListExpression { + constructor( + private readonly items: readonly Entry[], + private readonly root = 'Entry(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): EntryListExpression { + return new EntryListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): EntryExpression { + return this.item(0, true); + } + + get(index: number): EntryExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): EntryExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new EntryExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new EntryExpression(undefined, this.root, itemPath) + : new EntryExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static catalog( + value: Catalog | null | undefined, + ): CatalogExpression { + return new CatalogExpression( + value, 'Catalog', ExpressionPath.root('E.catalog()', 'camelCase'), + ); + } + + static entry( + value: Entry | null | undefined, + ): EntryExpression { + return new EntryExpression( + value, 'Entry', ExpressionPath.root('E.entry()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/Q.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e5a7216c93e8384c6449f6ba5763d54f3e66df6 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { CatalogRequest } from './requests/CatalogRequest'; +import { EntryRequest } from './requests/EntryRequest'; + +export class Q { + static catalogs(): CatalogRequest { + return new CatalogRequest(false); + } + + static catalogsWithMinimalFields(): CatalogRequest { + return new CatalogRequest(true); + } + static entries(): EntryRequest { + return new EntryRequest(false); + } + + static entriesWithMinimalFields(): EntryRequest { + return new EntryRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Catalog.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Catalog.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb51496702102dab008b4622f666df9d2b3a37c0 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Catalog.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Entry } from './Entry'; + +export class Catalog { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Catalog", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Catalog.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_entryList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["entryList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).entryList)) { + const selected = (init as any).entryList; + (this as any)._entryList = new SmartList(selected.map( + (child: unknown) => child instanceof Entry + ? child + : Entry.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("entryList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Catalog", id: (this as any)._ledgerId }; } + /** @internal Restore known equal scalars after the prepared graph completes. */ + private teaqlRestoreFixedValues(values: Readonly>): void { + for (const field of [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]) { + if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical]; + } + } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._entryList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Catalog { + const entity = new Catalog(record as Partial); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + return this.teaqlJson(new Set()); + } + + private static teaqlJsonValue(value: any, active: Set): any { + if (value === null || value === undefined) return value; + if (typeof value.teaqlJson === "function") return value.teaqlJson(active); + if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active)); + if (typeof value.toJSON === "function") return value.toJSON(); + if (typeof value === "object") return Object.fromEntries(Object.entries(value).map( + ([key, item]) => [key, this.teaqlJsonValue(item, active)])); + return typeof value === "bigint" ? value.toString() : value; + } + + private teaqlJson(active: Set): Record { + if (active.has(this)) return { id: this.id, version: this.version }; + active.add(this); + try { + // Only enumerable business/query data participates; runtime state is private. + const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key)) + .map(([key, value]) => [key, Catalog.teaqlJsonValue(value, active)])); + const childrenEntryList = this.entryList(); + if (childrenEntryList.isLoaded || childrenEntryList.some(child => + (child as any)._root.hasPending((child as any).teaqlEntityKey()))) { + payload["entryList"] = Catalog.teaqlJsonValue(childrenEntryList, active); + } + return payload; + } finally { active.delete(this); } + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Catalog { + return new Catalog({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Catalog { + return new Catalog().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._entryList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._entryList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "entry_list": graph.sourceMembers((this as any)._entryList) + })); + for (const child of (this as any)._entryList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Catalog.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Catalog", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._entryList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Catalog", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Catalog", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Catalog", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + entryList(): SmartList { + return (this as any)._entryList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Entry.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Entry.ts new file mode 100644 index 0000000000000000000000000000000000000000..00603c22071ea4c88d984fb67c446b9b018d8d5a --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Entry.ts @@ -0,0 +1,345 @@ +import { CheckException, integer32Error, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Catalog } from './Catalog'; + +export class Entry { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Entry", + ["id", "catalog", "name", "born_at", "touched_at", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + catalog?: Catalog | string; + name?: string; + bornAt?: string; + touchedAt?: string; + version?: EntityVersion; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Entry.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).catalog && typeof (init as any).catalog === "object") { + this.catalog = (init as any).catalog instanceof Catalog + ? (init as any).catalog + : Catalog.fromRecord((init as any).catalog); + this.markLoaded("catalog"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Entry", id: (this as any)._ledgerId }; } + /** @internal Restore known equal scalars after the prepared graph completes. */ + private teaqlRestoreFixedValues(values: Readonly>): void { + for (const field of [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "version", canonical: "version" }]) { + if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical]; + } + } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Entry { + const entity = new Entry(record as Partial); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + return this.teaqlJson(new Set()); + } + + private static teaqlJsonValue(value: any, active: Set): any { + if (value === null || value === undefined) return value; + if (typeof value.teaqlJson === "function") return value.teaqlJson(active); + if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active)); + if (typeof value.toJSON === "function") return value.toJSON(); + if (typeof value === "object") return Object.fromEntries(Object.entries(value).map( + ([key, item]) => [key, this.teaqlJsonValue(item, active)])); + return typeof value === "bigint" ? value.toString() : value; + } + + private teaqlJson(active: Set): Record { + if (active.has(this)) return { id: this.id, version: this.version }; + active.add(this); + try { + // Only enumerable business/query data participates; runtime state is private. + const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key)) + .map(([key, value]) => [key, Entry.teaqlJsonValue(value, active)])); + return payload; + } finally { active.delete(this); } + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Entry { + return new Entry({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Entry { + return new Entry().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "catalog": "Catalog" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Entry.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "catalog", canonical: "catalog" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Entry", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "catalog", canonical: "catalog" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Entry", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Entry", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Entry", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "catalog": this.catalog, + "name": this.name, + "born_at": this.bornAt, + "touched_at": this.touchedAt, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateBornAt(value: string): this { + this.bornAt = value; + this.markLoaded("bornAt"); + (this as any)._root.set(this.teaqlEntityKey(), "born_at", value); + return this; + } + + updateTouchedAt(value: string): this { + this.touchedAt = value; + this.markLoaded("touchedAt"); + (this as any)._root.set(this.teaqlEntityKey(), "touched_at", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateCatalog(value: any): this { + this.catalog = value?.id ?? value; + this.markLoaded("catalog"); + (this as any)._root.set(this.teaqlEntityKey(), "catalog", this.catalog); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/CatalogRequest.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/CatalogRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..c978c8d22ed8105da2ae7353278f57b78d1f0667 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/CatalogRequest.ts @@ -0,0 +1,616 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Catalog } from '../models/Catalog'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class CatalogRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Catalog"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableCatalogRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableCatalogRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectEntryListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "entryList", request.toQuery(), "id", "catalog", true, + { kind: "relation-select", method: "selectEntryListWith", relation: "entryList" }); + return this; + } + + haveEntries(): this { + return this.withEntryListMatching({ + toQuery: () => new SelectQuery("Entry"), + }); + } + + haveNoEntries(): this { + return this.withoutEntryListMatching({ + toQuery: () => new SelectQuery("Entry"), + }); + } + + withEntryListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "catalog", + }, + }, + }); + return this; + } + + withoutEntryListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "catalog", + }, + }, + }); + return this; + } + + countEntries(): this { + return this.countEntriesAs("countEntries"); + } + + countEntriesAs(alias: string): this { + const query = new SelectQuery("Entry").filter({ version: { "$gte": 1 } }); + this.countEntriesWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countEntriesAs", relation: "entryList", alias }; + return this; + } + + countEntriesWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("entryList", alias, query, true, + { kind: "relation-count", method: "countEntriesWith", relation: "entryList", alias }); + return this; + } + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows"); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Catalog + ? row + : Catalog.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const aggregateOnly = pageQuery.aggregateItems.length > 0; + const data = new SmartList(aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Catalog + ? row + : Catalog.fromRecord(row as Record, new EntityRoot()))); + if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) { + throw new Error("Entity streams require entity rows; use a record or aggregation query"); + } + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Catalog + ? entity + : Catalog.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableCatalogRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Catalog { + this.ensureIntent(); + return new Catalog(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/EntryRequest.ts b/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/EntryRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e12ac38e60e3be490891cefe010d874367e38ed --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/EntryRequest.ts @@ -0,0 +1,778 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Entry } from '../models/Entry'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class EntryRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Entry"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableEntryRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableEntryRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "catalog", "name", "bornAt", "touchedAt", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectBornAt(): this { + this.query.select(["bornAt"]); + return this; + } + + selectTouchedAt(): this { + this.query.select(["touchedAt"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCatalogWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["catalog"]); + this.query.relationQuery( + "catalog", request.toQuery(), "catalog", "id", false, + { kind: "relation-select", method: "selectCatalogWith", relation: "catalog" }); + return this; + } + + withCatalogMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "catalog": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCatalogMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "catalog": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByCatalog(val: any): this { + this.filters.push({ "catalog": { "$eq": val } }); + return this; + } + + filterByCatalogIn(...vals: any[]): this { + this.filters.push({ "catalog": { "$in": vals } }); + return this; + } + + withCatalogIsKnown(): this { + this.filters.push({ "catalog": { "$isNull": false } }); + return this; + } + + withCatalogIsUnknown(): this { + this.filters.push({ "catalog": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withBornAtIs(val: any): this { + this.filters.push({ "bornAt": { "$eq": val } }); + return this; + } + + withBornAtIsNot(val: any): this { + this.filters.push({ "bornAt": { "$ne": val } }); + return this; + } + + withBornAtIn(...vals: any[]): this { + this.filters.push({ "bornAt": { "$in": vals } }); + return this; + } + + withBornAtNotIn(...vals: any[]): this { + this.filters.push({ "bornAt": { "$notIn": vals } }); + return this; + } + + withBornAtGreaterThan(val: any): this { + this.filters.push({ "bornAt": { "$gt": val } }); + return this; + } + + withBornAtGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "bornAt": { "$gte": val } }); + return this; + } + + withBornAtLessThan(val: any): this { + this.filters.push({ "bornAt": { "$lt": val } }); + return this; + } + + withBornAtLessThanOrEqualTo(val: any): this { + this.filters.push({ "bornAt": { "$lte": val } }); + return this; + } + + withBornAtBetween(lower: any, upper: any): this { + this.filters.push({ "bornAt": { "$between": [lower, upper] } }); + return this; + } + + withBornAtIsKnown(): this { + this.filters.push({ "bornAt": { "$isNull": false } }); + return this; + } + + withBornAtIsUnknown(): this { + this.filters.push({ "bornAt": { "$isNull": true } }); + return this; + } + + withTouchedAtIs(val: any): this { + this.filters.push({ "touchedAt": { "$eq": val } }); + return this; + } + + withTouchedAtIsNot(val: any): this { + this.filters.push({ "touchedAt": { "$ne": val } }); + return this; + } + + withTouchedAtIn(...vals: any[]): this { + this.filters.push({ "touchedAt": { "$in": vals } }); + return this; + } + + withTouchedAtNotIn(...vals: any[]): this { + this.filters.push({ "touchedAt": { "$notIn": vals } }); + return this; + } + + withTouchedAtGreaterThan(val: any): this { + this.filters.push({ "touchedAt": { "$gt": val } }); + return this; + } + + withTouchedAtGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "touchedAt": { "$gte": val } }); + return this; + } + + withTouchedAtLessThan(val: any): this { + this.filters.push({ "touchedAt": { "$lt": val } }); + return this; + } + + withTouchedAtLessThanOrEqualTo(val: any): this { + this.filters.push({ "touchedAt": { "$lte": val } }); + return this; + } + + withTouchedAtBetween(lower: any, upper: any): this { + this.filters.push({ "touchedAt": { "$between": [lower, upper] } }); + return this; + } + + withTouchedAtIsKnown(): this { + this.filters.push({ "touchedAt": { "$isNull": false } }); + return this; + } + + withTouchedAtIsUnknown(): this { + this.filters.push({ "touchedAt": { "$isNull": true } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByBornAtAscending(): this { + this.query.orderBy("bornAt", "asc"); + return this; + } + + orderByBornAtDescending(): this { + this.query.orderBy("bornAt", "desc"); + return this; + } + + orderByTouchedAtAscending(): this { + this.query.orderBy("touchedAt", "asc"); + return this; + } + + orderByTouchedAtDescending(): this { + this.query.orderBy("touchedAt", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByCatalog(): this { + this.query.groupBy("catalog"); + return this; + } + + groupByCatalogAs(retName: string): this { + this.query.groupBy("catalog"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByBornAt(): this { + this.query.groupBy("bornAt"); + return this; + } + + groupByBornAtAs(retName: string): this { + this.query.groupBy("bornAt"); // In TS we don't alias group by yet natively + return this; + } + groupByTouchedAt(): this { + this.query.groupBy("touchedAt"); + return this; + } + + groupByTouchedAtAs(retName: string): this { + this.query.groupBy("touchedAt"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCatalogAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "catalog", request, includeAllFacets, + { kind: "facet", method: "facetByCatalogAs", relation: "catalog", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows"); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Entry + ? row + : Entry.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const aggregateOnly = pageQuery.aggregateItems.length > 0; + const data = new SmartList(aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Entry + ? row + : Entry.fromRecord(row as Record, new EntityRoot()))); + if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) { + throw new Error("Entity streams require entity rows; use a record or aggregation query"); + } + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Entry + ? entity + : Entry.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableEntryRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Entry { + this.ensureIntent(); + return new Entry(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/runtime-module.ts b/source/teaql-ts/examples/natural-messages/fixture/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..e64e9adf5a88de1b94573cfe54d252a7906d90d1 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/runtime-module.ts @@ -0,0 +1,74 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ContextFix, ObjectLocation, RuntimeModule } from "teaql-ts"; +import { CheckerPresentationModel } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Catalog": Object.freeze({ + entityType: "Catalog", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "Entry": Object.freeze({ + entityType: "Entry", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "catalog": Object.freeze({ canonicalName: "catalog", wireName: "catalog", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "born_at": Object.freeze({ canonicalName: "born_at", wireName: "bornAt", aliases: Object.freeze([] as string[]) }), + "touched_at": Object.freeze({ canonicalName: "touched_at", wireName: "touchedAt", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Catalog": { + checkAndFix(context, mutation, results) { + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "Entry": { + checkAndFix(context, mutation, results) { + if (mutation.action === "Create") { + ContextFix.apply(context, mutation, "born_at", "now", []); + } + + if (mutation.action === "Create") { + ContextFix.apply(context, mutation, "touched_at", "now", []); + } + if (mutation.action === "Update") { + ContextFix.apply(context, mutation, "touched_at", "now", []); + } + + + if ((mutation.action === "Create" && mutation.payload["catalog"] === undefined) || mutation.payload["catalog"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("catalog") }); + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["born_at"] === undefined) || mutation.payload["born_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("born_at") }); + + if ((mutation.action === "Create" && mutation.payload["touched_at"] === undefined) || mutation.payload["touched_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("touched_at") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Catalog", id: "1", values: { "name": "Catalog" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }).withCheckerPresentation(CheckerPresentationModel.fromJson("{\"schema\":\"teaql.checker-model/v1\",\"revision\":\"sha256:6499e0ef58931c3d57f98303285ad7d8cc498b658a8be72890e0431a6e158a25\",\"entities\":{\"Catalog\":{\"labels\":{\"en\":\"catalog\",\"zh-CN\":\"目录\"},\"fields\":[{\"name\":\"entry_list\",\"targetType\":\"Entry\",\"labels\":{\"en\":\"entry\",\"zh-CN\":\"明细\"},\"aliases\":[\"EntryList\",\"entryList\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\",\"zh-CN\":\"名称\"},\"aliases\":[\"Name\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]},\"Entry\":{\"labels\":{\"en\":\"entry\",\"zh-CN\":\"明细\"},\"fields\":[{\"name\":\"born_at\",\"labels\":{\"en\":\"born at\"},\"aliases\":[\"BornAt\",\"bornAt\"]},{\"name\":\"catalog\",\"targetType\":\"Catalog\",\"labels\":{\"en\":\"catalog\",\"zh-CN\":\"目录\"},\"aliases\":[\"Catalog\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\",\"zh-CN\":\"名称\"},\"aliases\":[\"Name\"]},{\"name\":\"touched_at\",\"labels\":{\"en\":\"touched at\"},\"aliases\":[\"TouchedAt\",\"touchedAt\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]}}}")); \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sql.ts b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..355f6f47c67bb0fdf8b86b0deebf128e7c1b2aaa --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Catalog": { + table: "catalog_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"entryList": { targetEntity: "Entry", localKey: "id", foreignKey: "catalog", many: true }} +}, +"Entry": { + table: "entry_data", + auditMaskFields: ["name"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "catalog": { columnName: "catalog", modelName: "catalog", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "bornAt": { columnName: "born_at", modelName: "born_at", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false, createFunction: "now" }, "touchedAt": { columnName: "touched_at", modelName: "touched_at", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false, createFunction: "now", updateFunction: "now" }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"catalog": { targetEntity: "Catalog", localKey: "catalog", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/src/teaql-ts.ts b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6c41a5aee3514c4483c0351d25393303803df93 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/src/teaql-ts.ts @@ -0,0 +1,530 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, ContextFix, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, +} from "teaql-ts"; +import { CheckerPresentationModel } from "teaql-ts"; +import type { CheckerMessageConfiguration, CheckerValidationOrigin } from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private checkerPresentationModel = CheckerPresentationModel.empty; + private readonly checkerPrivacyPolicy = (entity: string | undefined, field: string): "masked" | "credential" | undefined => { + const schema = entity ? this.schemas[entity] : undefined; + if (!schema) return undefined; + const native = Object.keys(schema.columns).find(name => name === field + || schema.columns[name].modelName === field || schema.columns[name].columnName === field) ?? field; + const column = schema.columns[native]; + const modeled = column?.modelName ?? column?.columnName ?? native; + if (column?.logPolicy === "credential") return "credential"; + if (column?.logPolicy === "masked" || schema.auditMaskFields?.includes(modeled) + || schema.auditMaskFields?.includes(native)) return "masked"; + return undefined; + }; + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + const presentation = this.checkerPresentationModel.merge(module.checkerPresentationModel); + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + this.checkerPresentationModel = presentation; + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionReference(() => this.checkerPresentationModel); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + let checkerConfig: CheckerMessageConfiguration | undefined; + let checkerOrigin: CheckerValidationOrigin | undefined; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + checkerConfig = executionContext.captureCheckerMessages(this.checkerPresentationModel); + if (graph.preparedRootEntity) checkerOrigin = Object.freeze({model: checkerConfig.model, entity: graph.preparedRootEntity}); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + if (error instanceof CheckException && checkerOrigin && checkerConfig) { + error.refreshPresentation(executionContext.renderCheckerGraphResults(error.violations, checkerConfig, checkerOrigin)); + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + mutation = this.checkAndFixMutation(request); + const normalized = request.graphSession?.normalizePreparedMutation(mutation); + if (normalized?.restore) { + this.afterGraphCommit(normalized.restore); + this.afterGraphRollback(normalized.restore); + } + if (normalized?.empty) return mutation; + request.graphSession?.recordPreparedMutation(); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + ContextFix.run(this.userContext, mutation, schema, () => checker.checkAndFix(this.userContext, mutation, results)); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResultsFrom(declaringEntityType, results, { + defaultModel: this.checkerPresentationModel, privacyPolicy: this.checkerPrivacyPolicy, + checkedValues: [request.loadedValues(), request.mutation.payload ?? {}, mutation.payload ?? {}], + }); + if (results.length) throw new CheckException(results); + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) { + const undo = ContextFix.captureUndo(mutation, schema); + if (request.graphSession && undo) this.graphRollbackActions.push(undo); + for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + } + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/teaql-i18n.json b/source/teaql-ts/examples/natural-messages/fixture/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..43596b75cc9c1b17bd37c7567a38bbff96e82ec6 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/teaql-i18n.json @@ -0,0 +1,112 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "entity.catalog": "Catalog", + "property.entry.name": "Name", + "property.catalog.id": "Id", + "property.entry.touchedAt": "Touched At", + "property.entry.id": "Id", + "property.catalog.name": "Name", + "property.catalog.version": "Version", + "property.entry.version": "Version", + "entity.entry": "Entry", + "property.entry.bornAt": "Born At", + "property.entry.catalog": "Catalog" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + "entity.catalog": "目录", + "property.entry.name": "名称", + "property.catalog.name": "名称", + "entity.entry": "明细", + "property.entry.catalog": "目录" + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/teaql/checker-model.json b/source/teaql-ts/examples/natural-messages/fixture/teaql/checker-model.json new file mode 100644 index 0000000000000000000000000000000000000000..a7b2d0236967ecc9caf9f51c4f85637cca769176 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/teaql/checker-model.json @@ -0,0 +1 @@ +{"schema":"teaql.checker-model/v1","revision":"sha256:6499e0ef58931c3d57f98303285ad7d8cc498b658a8be72890e0431a6e158a25","entities":{"Catalog":{"labels":{"en":"catalog","zh-CN":"目录"},"fields":[{"name":"entry_list","targetType":"Entry","labels":{"en":"entry","zh-CN":"明细"},"aliases":["EntryList","entryList"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name","zh-CN":"名称"},"aliases":["Name"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]},"Entry":{"labels":{"en":"entry","zh-CN":"明细"},"fields":[{"name":"born_at","labels":{"en":"born at"},"aliases":["BornAt","bornAt"]},{"name":"catalog","targetType":"Catalog","labels":{"en":"catalog","zh-CN":"目录"},"aliases":["Catalog"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name","zh-CN":"名称"},"aliases":["Name"]},{"name":"touched_at","labels":{"en":"touched at"},"aliases":["TouchedAt","touchedAt"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]}}} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/teaql/model-provenance.json b/source/teaql-ts/examples/natural-messages/fixture/teaql/model-provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..969a4f39c5c7a50d9b4b33420478b8fd3179cea0 --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":"sha256:86937993c820d848cd5e8e24dcdf3c9152a47c5c518339c4ea6beb2bc22cb8a5","generatorVersion":"unknown"} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/fixture/tsconfig.json b/source/teaql-ts/examples/natural-messages/fixture/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/fixture/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/natural-messages/verify.test.ts b/source/teaql-ts/examples/natural-messages/verify.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5c677103eeaaa03882c1253dfea7c8e377431aa --- /dev/null +++ b/source/teaql-ts/examples/natural-messages/verify.test.ts @@ -0,0 +1,91 @@ +import fs from 'node:fs'; +import {CheckException, CheckerPresentationModel, UserContext, checkResultToWire, + standardCheckerMessageRenderer} from '../../src'; +import {Q} from 'natural-generated/generated/Q'; +import {E} from 'natural-generated/generated/E'; +import {SQLiteTeaQLClient} from 'natural-generated/teaql-node-sqlite'; +import {TeaQLClient as FileTeaQLClient} from 'natural-generated/teaql-ts'; +import {GENERATED_RUNTIME_MODULE} from 'natural-generated/runtime-module'; + +// 101 Unicode scalars, 102 UTF-16 units. Actual generated bound is 100 scalars. +const SECRET='密钥🔑'+'a'.repeat(98); + +test.each(['sqlite','file'] as const)('generated %s graph uses automatic metadata and protects relocated diagnostics',async provider=>{ + expect(require.resolve('teaql-ts')).toBe(process.env.TEAQL_EXPECTED_RUNTIME_ENTRY); + const sqlite=process.env.TEAQL_NATURAL_MESSAGES_DB,file=process.env.TEAQL_NATURAL_MESSAGES_FILE; + if(!sqlite||!file)throw new Error('Use scripts/verify-natural-messages.cjs --example'); + const context=new UserContext().installCheckerMessageWarning(()=>{}); + const client=provider==='sqlite'?new SQLiteTeaQLClient(sqlite).setDiagnosticSQLLogSink(undefined):new FileTeaQLClient(file); + client.setUserContext(context).install(GENERATED_RUNTIME_MODULE);context.insertResource('dataService',client); + // The generated module owns descriptors and the actual Checker. There is no + // manually installed presentation model, custom bounds rule or seed SQL. + expect(context.checkerPresentationModel).toBe(CheckerPresentationModel.empty); + expect(GENERATED_RUNTIME_MODULE.checkerPresentationModel).not.toBe(CheckerPresentationModel.empty); + const responses:unknown[]=[]; + async function rejected(work:()=>Promise,expected:string):Promise{ + let failure:unknown;try{await work();}catch(error){failure=error;} + expect(failure).toBeInstanceOf(CheckException); + const error=failure as CheckException,response={provider,violations:error.violations.map(result=>checkResultToWire(result))}; + const target=response.violations.find(result=>result.instancePath==='/entryList/1/name'); + expect(target).toBeDefined();expect(target!.entityType).toBe('Entry');expect(target!.message).toBe(expected); + expect(error.message).toContain(expected);expect(JSON.stringify(response)).not.toContain(SECRET); + expect(String(error)).not.toContain(SECRET);responses.push(response); + process.stdout.write('TS_NATURAL_RESPONSE='+JSON.stringify(response)+'\n'); + } + try{ + await context.ensureSchema();await context.ensureSchema(); + const make=(name:string)=>Q.entries().comment('Prepare an example child') + .purpose('Verify generated audited mutation and natural errors').newEntity(context).updateName(name).updateCatalog('1'); + let first=make('first'),second=make('second'); + await first.auditAs('Create the first valid child').save(context); + await second.auditAs('Create the second valid child').save(context); + const load=async(id:string)=>{ + const rows=await Q.entries().withIdIs(id).limit(1).comment('Reload complete child') + .purpose('Verify actual stored values through E').executeForList(context);expect(rows).toHaveLength(1);return rows[0]; + }; + first=await load(first.id!);second=await load(second.id!); + expect(E.entry(second).name().eval()).toBe('second');const secondId=second.id!,version=second.version; + const parents=await Q.catalogs().withIdIs('1').limit(1).comment('Load unchanged graph owner') + .purpose('Verify an indexed child failure without editing the parent').executeForList(context); + const parent=parents[0],parentVersion=parent.version;parent.entryList().push(first,second); + const execute=jest.spyOn(client,'executeMutation'); + const query=provider==='sqlite'?jest.spyOn((client as any).driver,'query'):undefined; + const transaction=provider==='sqlite'?jest.spyOn((client as any).driver,'transaction'):undefined; + const auditBefore=client.auditTrace.length,originalFile=provider==='file'?fs.readFileSync(file):undefined; + const reset=()=>{execute.mockClear();query?.mockClear();transaction?.mockClear();}; + const unchanged=()=>{ + expect(execute).not.toHaveBeenCalled();if(query)expect(query).not.toHaveBeenCalled();if(transaction)expect(transaction).not.toHaveBeenCalled(); + expect(client.auditTrace).toHaveLength(auditBefore);expect(parent.version).toBe(parentVersion); + if(originalFile)expect(fs.readFileSync(file)).toEqual(originalFile); + }; + // The unchanged parent is not a writable view; the first writable child is + // not the origin. The failure must still identify the second child. + first.updateName('changed'); + for(const [locale,expected] of [['en','The name of the 2nd entry is required.'],['zh-CN','请填写第2项明细的名称。']] as const){ + context.setLocaleCode(locale);second.updateName(null as unknown as string);reset(); + await rejected(()=>parent.auditAs('Reject the second null child before provider work').save(context),expected);unchanged(); + } + context.setLocaleCode('en');second.updateName(SECRET);reset(); + await rejected(()=>parent.auditAs('Reject a private scalar-length violation').save(context), + 'The name of the 2nd entry must not exceed 100 Unicode scalar values; its current length is 101.');unchanged(); + expect(second.name).toBe(SECRET);expect(second.version).toBe(version); + // Relocation reuses a safe literal from the customer renderer. It must not + // invoke customer code a second time after the original privacy scope ends. + let rendererCalls=0; + context.installCheckerMessageRenderer(request=>{ + rendererCalls++;expect(request.arguments.input).not.toBe(SECRET);expect(request.arguments.input_len).toBe('101'); + return {message:`Custom response ${SECRET}`,warnings:[]}; + });reset(); + await rejected(()=>parent.auditAs('Verify one customer rendering per error').save(context),'Custom response [REDACTED]'); + expect(rendererCalls).toBe(1);unchanged();context.installCheckerMessageRenderer(standardCheckerMessageRenderer); + first.updateName('first');second.updateName('renamed'); + await parent.auditAs('Persist only the corrected second child').save(context); + expect(client.auditTrace).toHaveLength(auditBefore+1);expect(parent.version).toBe(parentVersion); + const stored=await load(secondId);expect(E.entry(stored).name().eval()).toBe('renamed');expect(stored.version).toBe(Number(version)+1); + expect(context.checkerPresentationModel).toBe(CheckerPresentationModel.empty); + execute.mockRestore();query?.mockRestore();transaction?.mockRestore(); + process.stdout.write('TS_NATURAL_SQLITE_PASS='+JSON.stringify({passed:true,provider,child:secondId,first:first.id,version:stored.version, + responses:responses.length,providerCallsOnRejection:0,transactionCallsOnRejection:0,updatedAudits:1,rendererCalls, + automaticMetadata:true,unchangedParent:true,localSource:require.resolve('teaql-ts')})+'\n'); + }finally{if(client instanceof SQLiteTeaQLClient)await client.close();} +},30000); diff --git a/source/teaql-ts/examples/order-management/model.xml b/source/teaql-ts/examples/order-management/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f0b3e2d3a00242075a6f6820b4573c1a844f6bc5 --- /dev/null +++ b/source/teaql-ts/examples/order-management/model.xml @@ -0,0 +1,13 @@ + + + + + + <_value id="1001" name="Pending" code="PENDING" color="#F59E0B" display_order="1" commerce_platform="1"/> + <_value id="1002" name="Confirmed" code="CONFIRMED" color="#10B981" display_order="2" commerce_platform="1"/> + + + + + + diff --git a/source/teaql-ts/examples/order-management/package-lock.json b/source/teaql-ts/examples/order-management/package-lock.json index 83caacecf28a675e2d7f7581982aeb79d04c808a..2443df8c94ae1439725555f6c5ff72b4f959e166 100644 --- a/source/teaql-ts/examples/order-management/package-lock.json +++ b/source/teaql-ts/examples/order-management/package-lock.json @@ -8,11 +8,14 @@ "workspaces": [ "typescript-node-lib-core", "typescript-app-console" - ] + ], + "engines": { + "node": ">=22" + } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -36,7 +39,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -63,7 +66,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", @@ -242,126 +245,25 @@ "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", "license": "MIT" }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/better-sqlite3": { - "version": "11.10.0", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", - "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "node-addon-api": "^8.0.0" + }, + "engines": { + "node": ">=22" } }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "license": "MIT" }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, "node_modules/diff": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", @@ -371,132 +273,19 @@ "node": ">=0.3.1" } }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "license": "ISC" }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.94.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz", - "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==", + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, "engines": { - "node": ">=10" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" + "node": "^18 || ^20 || >= 21" } }, "node_modules/order-management-example": { @@ -507,195 +296,6 @@ "resolved": "typescript-node-lib-core", "link": true }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/ts-node": { "version": "10.9.2", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", @@ -739,18 +339,6 @@ } } }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -770,24 +358,12 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", "license": "MIT" }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", @@ -818,7 +394,7 @@ "name": "order-management-service-lib", "version": "1.0.0", "dependencies": { - "better-sqlite3": "^11.7.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../../.." }, "devDependencies": { @@ -826,6 +402,9 @@ "@types/node": "^22.0.0", "ts-node": "^10.9.2", "typescript": "^5.0.0" + }, + "engines": { + "node": ">=22" } }, "typescript-node-lib-core/node_modules/teaql-ts": { diff --git a/source/teaql-ts/examples/order-management/package.json b/source/teaql-ts/examples/order-management/package.json index 8de48ae3d4ea24e1621dd00759d769c4bdc631d3..da6129b15e1a8e6a155c21fca7a01bd64b704c7b 100644 --- a/source/teaql-ts/examples/order-management/package.json +++ b/source/teaql-ts/examples/order-management/package.json @@ -1,10 +1,14 @@ { "name": "teaql-order-management-example", "private": true, + "engines": { "node": ">=22" }, "workspaces": [ "typescript-node-lib-core", "typescript-app-console" ], + "overrides": { + "better-sqlite3": "^13.0.3" + }, "scripts": { "build": "npm run build --workspace order-management-example", "start": "npm start --workspace order-management-example" diff --git a/source/teaql-ts/examples/order-management/typescript-app-console/app.ts b/source/teaql-ts/examples/order-management/typescript-app-console/app.ts index 0cd3600cc75d9289f6fdae378dc9558014ebe917..fd867486063dfd543b66aed2c38c3660a4057408 100644 --- a/source/teaql-ts/examples/order-management/typescript-app-console/app.ts +++ b/source/teaql-ts/examples/order-management/typescript-app-console/app.ts @@ -1,11 +1,7 @@ import fs from "node:fs"; import path from "node:path"; import { Q } from "order-management-service-lib/src/generated/Q"; -import { CommercePlatform } from "order-management-service-lib/src/generated/models/CommercePlatform"; -import { Customer } from "order-management-service-lib/src/generated/models/Customer"; -import { CustomerOrder } from "order-management-service-lib/src/generated/models/CustomerOrder"; -import { OrderSearchPreset } from "order-management-service-lib/src/generated/models/OrderSearchPreset"; -import { UserContext } from "teaql-ts"; +import { UserContext, decimal } from "teaql-ts"; import { SQLiteTeaQLClient } from "order-management-service-lib/src/teaql-node-sqlite"; async function main(): Promise { @@ -30,7 +26,8 @@ async function main(): Promise { .executeForList(ctx); let platformId: string; if (platforms.data.length === 0) { - const platform = new CommercePlatform().updateName("Northwind Demo"); + const platform = (await Q.commercePlatforms().comment("Prepare the demo commerce platform") + .purpose("Reserve identity before initializing business data").newEntity(ctx)).updateName("Northwind Demo"); await platform.auditAs("Create quick-start commerce platform").save(ctx); platformId = platform.id!; } else platformId = String(platforms.data[0].id); @@ -41,15 +38,17 @@ async function main(): Promise { .purpose("Initialize the local order-management example") .executeForList(ctx); if (seeded.data.length === 0) { - const customer = new Customer() + const customer = (await Q.customers().comment("Prepare the demo customer") + .purpose("Reserve identity before initializing business data").newEntity(ctx)) .updateName("Acme Retail") .updateEmail("masked-in-quick-start") .updateCommercePlatform(platformId); await customer.auditAs("Create masked quick-start customer").save(ctx); - const order = new CustomerOrder() + const order = (await Q.customerOrders().comment("Prepare the deterministic demo order") + .purpose("Reserve identity before initializing business data").newEntity(ctx)) .updateOrderNumber("WEB-2026-001") .updateOrderDate("2026-08-12") - .updateTotalAmount(129.95) + .updateTotalAmount(decimal('129.95')) .updateStatusToPending() .updateCustomer(customer.id) .updateCommercePlatform(platformId); @@ -74,7 +73,8 @@ async function main(): Promise { .purpose("Persist the operator's reusable search") .executeForList(ctx); if (presets.data.length === 0) { - const preset = new OrderSearchPreset() + const preset = (await Q.orderSearchPresets().comment("Prepare a reusable demo search") + .purpose("Reserve identity before persisting a search preset").newEntity(ctx)) .updateName("Pending web orders") .updateFilterJson('{"order_number":"WEB-"}') .updateRequestId("quick-start-pending-orders") diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json b/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json index 3c3b6813698d0e4b6c7383b6b4567057dfa8d0f1..5fdaaf462fc2baf0f2385b381b0602accf0da109 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/package.json @@ -2,16 +2,21 @@ "name": "order-management-service-lib", "version": "1.0.0", "description": "Generated typescript library", + "engines": { + "node": ">=22" + }, "main": "src/generated/Q.ts", "scripts": { "build": "tsc --noEmit" }, "dependencies": { "teaql-ts": "file:../../..", - "better-sqlite3": "^11.7.0"}, + "better-sqlite3": "^13.0.3" + }, "devDependencies": { "typescript": "^5.0.0", "ts-node": "^10.9.2", "@types/node": "^22.0.0", - "@types/better-sqlite3": "^7.6.12"} + "@types/better-sqlite3": "^7.6.12" + } } diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-bootstrap.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..1690f1141033f5a6747f5545c3cca551b49f597d --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-bootstrap.ts @@ -0,0 +1,51 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { CommercePlatform } from './generated/models/CommercePlatform'; +import { OrderStatus } from './generated/models/OrderStatus'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.commercePlatforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = CommercePlatform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Northwind Demo"); + await domainRoot.auditAs('create generated Domain Root CommercePlatform').save(context); + } + context.withActiveRoot({ entity: 'CommercePlatform', id: domainRoot.id! }); + let constantOrderStatus1001 = (await Q.orderStatuses().withIdIs("1001").comment('what: locate generated constant OrderStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantOrderStatus1001) { + constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew(context, "1001"); + constantOrderStatus1001.updateName("Pending"); + constantOrderStatus1001.updateCode("PENDING"); + constantOrderStatus1001.updateColor("#F59E0B"); + constantOrderStatus1001.updateDisplayOrder(decimal("1")); + constantOrderStatus1001.updateCommercePlatform(domainRoot); + await constantOrderStatus1001.auditAs('create model constant OrderStatus(1001)').save(context); + } else { + let changed = false; + if (constantOrderStatus1001.name !== "Pending") { constantOrderStatus1001.updateName("Pending"); changed = true; } + if (constantOrderStatus1001.code !== "PENDING") { constantOrderStatus1001.updateCode("PENDING"); changed = true; } + if (constantOrderStatus1001.color !== "#F59E0B") { constantOrderStatus1001.updateColor("#F59E0B"); changed = true; } + if (constantOrderStatus1001.displayOrder !== decimal("1")) { constantOrderStatus1001.updateDisplayOrder(decimal("1")); changed = true; } + if (String((constantOrderStatus1001.commercePlatform as any)?.id ?? constantOrderStatus1001.commercePlatform) !== String(domainRoot.id)) { constantOrderStatus1001.updateCommercePlatform(domainRoot); changed = true; } + if (changed) await constantOrderStatus1001.auditAs('reconcile model constant OrderStatus(1001)').save(context); + } + let constantOrderStatus1002 = (await Q.orderStatuses().withIdIs("1002").comment('what: locate generated constant OrderStatus(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantOrderStatus1002) { + constantOrderStatus1002 = OrderStatus.teaqlBootstrapNew(context, "1002"); + constantOrderStatus1002.updateName("Confirmed"); + constantOrderStatus1002.updateCode("CONFIRMED"); + constantOrderStatus1002.updateColor("#10B981"); + constantOrderStatus1002.updateDisplayOrder(decimal("2")); + constantOrderStatus1002.updateCommercePlatform(domainRoot); + await constantOrderStatus1002.auditAs('create model constant OrderStatus(1002)').save(context); + } else { + let changed = false; + if (constantOrderStatus1002.name !== "Confirmed") { constantOrderStatus1002.updateName("Confirmed"); changed = true; } + if (constantOrderStatus1002.code !== "CONFIRMED") { constantOrderStatus1002.updateCode("CONFIRMED"); changed = true; } + if (constantOrderStatus1002.color !== "#10B981") { constantOrderStatus1002.updateColor("#10B981"); changed = true; } + if (constantOrderStatus1002.displayOrder !== decimal("2")) { constantOrderStatus1002.updateDisplayOrder(decimal("2")); changed = true; } + if (String((constantOrderStatus1002.commercePlatform as any)?.id ?? constantOrderStatus1002.commercePlatform) !== String(domainRoot.id)) { constantOrderStatus1002.updateCommercePlatform(domainRoot); changed = true; } + if (changed) await constantOrderStatus1002.auditAs('reconcile model constant OrderStatus(1002)').save(context); + } +} diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-search-models.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..000b1a7fb0522c774d38ee69f324a667927da9eb --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated-search-models.ts @@ -0,0 +1,252 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "CommercePlatform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "customerList": "Customer", + "orderStatusList": "OrderStatus", + "customerOrderList": "CustomerOrder", + "productList": "Product", + "orderLineList": "OrderLine", + "orderSearchPresetList": "OrderSearchPreset", + }), + }), + "Customer": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "email": "string" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "email": "email", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + "customerOrderList": "CustomerOrder", + }), + }), + "OrderStatus": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "code": "string" as const, + "color": "string" as const, + "display_order": "decimal" as const, + "displayOrder": "decimal" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "code": "code", + "color": "color", + "display_order": "displayOrder", + "displayOrder": "displayOrder", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "version": "version", + }), + relations: Object.freeze({ + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + "customerOrderList": "CustomerOrder", + }), + }), + "CustomerOrder": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "order_number": "string" as const, + "orderNumber": "string" as const, + "order_date": "date" as const, + "orderDate": "date" as const, + "total_amount": "decimal" as const, + "totalAmount": "decimal" as const, + "status": "integer" as const, + "customer": "integer" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "order_number": "orderNumber", + "orderNumber": "orderNumber", + "order_date": "orderDate", + "orderDate": "orderDate", + "total_amount": "totalAmount", + "totalAmount": "totalAmount", + "status": "status", + "customer": "customer", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "status": "OrderStatus", + "customer": "Customer", + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + "orderLineList": "OrderLine", + }), + }), + "Product": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "sku": "string" as const, + "image_url": "string" as const, + "imageUrl": "string" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "sku": "sku", + "image_url": "imageUrl", + "imageUrl": "imageUrl", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + "orderLineList": "OrderLine", + }), + }), + "OrderLine": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "customer_order": "integer" as const, + "customerOrder": "integer" as const, + "product": "integer" as const, + "product_name": "string" as const, + "productName": "string" as const, + "sku": "string" as const, + "quantity": "integer" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "customer_order": "customerOrder", + "customerOrder": "customerOrder", + "product": "product", + "product_name": "productName", + "productName": "productName", + "sku": "sku", + "quantity": "quantity", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "create_time": "createTime", + "createTime": "createTime", + "version": "version", + }), + relations: Object.freeze({ + "customer_order": "CustomerOrder", + "customerOrder": "CustomerOrder", + "product": "Product", + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + }), + }), + "OrderSearchPreset": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "filter_json": "string" as const, + "filterJson": "string" as const, + "request_id": "string" as const, + "requestId": "string" as const, + "owner_user_id": "string" as const, + "ownerUserId": "string" as const, + "commerce_platform": "integer" as const, + "commercePlatform": "integer" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "filter_json": "filterJson", + "filterJson": "filterJson", + "request_id": "requestId", + "requestId": "requestId", + "owner_user_id": "ownerUserId", + "ownerUserId": "ownerUserId", + "commerce_platform": "commercePlatform", + "commercePlatform": "commercePlatform", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "commerce_platform": "CommercePlatform", + "commercePlatform": "CommercePlatform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/E.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0e1442e27461a0c5b481aa5c367740bd873558f --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/E.ts @@ -0,0 +1,1545 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { CommercePlatform } from './models/CommercePlatform'; +import { Customer } from './models/Customer'; +import { OrderStatus } from './models/OrderStatus'; +import { CustomerOrder } from './models/CustomerOrder'; +import { Product } from './models/Product'; +import { OrderLine } from './models/OrderLine'; +import { OrderSearchPreset } from './models/OrderSearchPreset'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class CommercePlatformExpression { + constructor( + private readonly value: CommercePlatform | null | undefined, + private readonly root = 'CommercePlatform(null)', + private readonly path = ExpressionPath.root('E.commercePlatform()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): CommercePlatform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + customerList(): CustomerListExpression { + const path = this.path.member('customer_list', 'customerList'); + if (this.notLoaded) { + return new CustomerListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return CustomerListExpression.missing(this.root, path); + if (!this.value.isLoaded('customerList')) { + return new CustomerListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'customer_list')); + } + return new CustomerListExpression( + this.value.customerList(), this.root, path, + ); + } + + orderStatusList(): OrderStatusListExpression { + const path = this.path.member('order_status_list', 'orderStatusList'); + if (this.notLoaded) { + return new OrderStatusListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderStatusListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderStatusList')) { + return new OrderStatusListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_status_list')); + } + return new OrderStatusListExpression( + this.value.orderStatusList(), this.root, path, + ); + } + + customerOrderList(): CustomerOrderListExpression { + const path = this.path.member('customer_order_list', 'customerOrderList'); + if (this.notLoaded) { + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return CustomerOrderListExpression.missing(this.root, path); + if (!this.value.isLoaded('customerOrderList')) { + return new CustomerOrderListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); + } + return new CustomerOrderListExpression( + this.value.customerOrderList(), this.root, path, + ); + } + + productList(): ProductListExpression { + const path = this.path.member('product_list', 'productList'); + if (this.notLoaded) { + return new ProductListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return ProductListExpression.missing(this.root, path); + if (!this.value.isLoaded('productList')) { + return new ProductListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'product_list')); + } + return new ProductListExpression( + this.value.productList(), this.root, path, + ); + } + + orderLineList(): OrderLineListExpression { + const path = this.path.member('order_line_list', 'orderLineList'); + if (this.notLoaded) { + return new OrderLineListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderLineListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderLineList')) { + return new OrderLineListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_line_list')); + } + return new OrderLineListExpression( + this.value.orderLineList(), this.root, path, + ); + } + + orderSearchPresetList(): OrderSearchPresetListExpression { + const path = this.path.member('order_search_preset_list', 'orderSearchPresetList'); + if (this.notLoaded) { + return new OrderSearchPresetListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderSearchPresetListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderSearchPresetList')) { + return new OrderSearchPresetListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_search_preset_list')); + } + return new OrderSearchPresetListExpression( + this.value.orderSearchPresetList(), this.root, path, + ); + } +} + +export class CustomerExpression { + constructor( + private readonly value: Customer | null | undefined, + private readonly root = 'Customer(null)', + private readonly path = ExpressionPath.root('E.customer()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Customer | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + email(): ValueExpression { + const path = this.path.member('email', 'email'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('email')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'email'), + ); + } + return new ValueExpression(this.value.email); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + + customerOrderList(): CustomerOrderListExpression { + const path = this.path.member('customer_order_list', 'customerOrderList'); + if (this.notLoaded) { + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return CustomerOrderListExpression.missing(this.root, path); + if (!this.value.isLoaded('customerOrderList')) { + return new CustomerOrderListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); + } + return new CustomerOrderListExpression( + this.value.customerOrderList(), this.root, path, + ); + } +} + +export class OrderStatusExpression { + constructor( + private readonly value: OrderStatus | null | undefined, + private readonly root = 'OrderStatus(null)', + private readonly path = ExpressionPath.root('E.orderStatus()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): OrderStatus | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + code(): ValueExpression { + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('code')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'code'), + ); + } + return new ValueExpression(this.value.code); + } + + color(): ValueExpression { + const path = this.path.member('color', 'color'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('color')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'color'), + ); + } + return new ValueExpression(this.value.color); + } + + displayOrder(): ValueExpression { + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('displayOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), + ); + } + return new ValueExpression(this.value.displayOrder); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + + customerOrderList(): CustomerOrderListExpression { + const path = this.path.member('customer_order_list', 'customerOrderList'); + if (this.notLoaded) { + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return CustomerOrderListExpression.missing(this.root, path); + if (!this.value.isLoaded('customerOrderList')) { + return new CustomerOrderListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); + } + return new CustomerOrderListExpression( + this.value.customerOrderList(), this.root, path, + ); + } +} + +export class CustomerOrderExpression { + constructor( + private readonly value: CustomerOrder | null | undefined, + private readonly root = 'CustomerOrder(null)', + private readonly path = ExpressionPath.root('E.customerOrder()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): CustomerOrder | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + orderNumber(): ValueExpression { + const path = this.path.member('order_number', 'orderNumber'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('orderNumber')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'order_number'), + ); + } + return new ValueExpression(this.value.orderNumber); + } + + orderDate(): ValueExpression { + const path = this.path.member('order_date', 'orderDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('orderDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'order_date'), + ); + } + return new ValueExpression(this.value.orderDate); + } + + totalAmount(): ValueExpression { + const path = this.path.member('total_amount', 'totalAmount'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('totalAmount')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'total_amount'), + ); + } + return new ValueExpression(this.value.totalAmount); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + statusId(): ValueExpression { + const path = this.path.member('status', 'statusId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('status')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'status'), + ); + } + const reference = this.value.status; + return new ValueExpression( + reference instanceof OrderStatus + ? reference.id : reference as string | number | undefined, + ); + } + + customerId(): ValueExpression { + const path = this.path.member('customer', 'customerId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('customer')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'customer'), + ); + } + const reference = this.value.customer; + return new ValueExpression( + reference instanceof Customer + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + status(): OrderStatusExpression { + const path = this.path.member('status', 'status'); + if (this.notLoaded) { + return new OrderStatusExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new OrderStatusExpression(undefined, this.root, path); + if (!this.value.isLoaded('status')) { + return new OrderStatusExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'status')); + } + const relation = this.value.status; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof OrderStatus)) { + return new OrderStatusExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'status')); + } + const target = relation instanceof OrderStatus ? relation : undefined; + return new OrderStatusExpression(target, this.root, path); + } + + customer(): CustomerExpression { + const path = this.path.member('customer', 'customer'); + if (this.notLoaded) { + return new CustomerExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CustomerExpression(undefined, this.root, path); + if (!this.value.isLoaded('customer')) { + return new CustomerExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer')); + } + const relation = this.value.customer; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Customer)) { + return new CustomerExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer')); + } + const target = relation instanceof Customer ? relation : undefined; + return new CustomerExpression(target, this.root, path); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + + orderLineList(): OrderLineListExpression { + const path = this.path.member('order_line_list', 'orderLineList'); + if (this.notLoaded) { + return new OrderLineListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderLineListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderLineList')) { + return new OrderLineListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_line_list')); + } + return new OrderLineListExpression( + this.value.orderLineList(), this.root, path, + ); + } +} + +export class ProductExpression { + constructor( + private readonly value: Product | null | undefined, + private readonly root = 'Product(null)', + private readonly path = ExpressionPath.root('E.product()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Product | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + sku(): ValueExpression { + const path = this.path.member('sku', 'sku'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('sku')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'sku'), + ); + } + return new ValueExpression(this.value.sku); + } + + imageUrl(): ValueExpression { + const path = this.path.member('image_url', 'imageUrl'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('imageUrl')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'image_url'), + ); + } + return new ValueExpression(this.value.imageUrl); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + + orderLineList(): OrderLineListExpression { + const path = this.path.member('order_line_list', 'orderLineList'); + if (this.notLoaded) { + return new OrderLineListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderLineListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderLineList')) { + return new OrderLineListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_line_list')); + } + return new OrderLineListExpression( + this.value.orderLineList(), this.root, path, + ); + } +} + +export class OrderLineExpression { + constructor( + private readonly value: OrderLine | null | undefined, + private readonly root = 'OrderLine(null)', + private readonly path = ExpressionPath.root('E.orderLine()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): OrderLine | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + productName(): ValueExpression { + const path = this.path.member('product_name', 'productName'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('productName')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'product_name'), + ); + } + return new ValueExpression(this.value.productName); + } + + sku(): ValueExpression { + const path = this.path.member('sku', 'sku'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('sku')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'sku'), + ); + } + return new ValueExpression(this.value.sku); + } + + quantity(): ValueExpression { + const path = this.path.member('quantity', 'quantity'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('quantity')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'quantity'), + ); + } + const error = integer32Error(this.value.quantity, 'OrderLine', 'quantity'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.quantity); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + customerOrderId(): ValueExpression { + const path = this.path.member('customer_order', 'customerOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('customerOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'customer_order'), + ); + } + const reference = this.value.customerOrder; + return new ValueExpression( + reference instanceof CustomerOrder + ? reference.id : reference as string | number | undefined, + ); + } + + productId(): ValueExpression { + const path = this.path.member('product', 'productId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('product')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'product'), + ); + } + const reference = this.value.product; + return new ValueExpression( + reference instanceof Product + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + customerOrder(): CustomerOrderExpression { + const path = this.path.member('customer_order', 'customerOrder'); + if (this.notLoaded) { + return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CustomerOrderExpression(undefined, this.root, path); + if (!this.value.isLoaded('customerOrder')) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const relation = this.value.customerOrder; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CustomerOrder)) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const target = relation instanceof CustomerOrder ? relation : undefined; + return new CustomerOrderExpression(target, this.root, path); + } + + product(): ProductExpression { + const path = this.path.member('product', 'product'); + if (this.notLoaded) { + return new ProductExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new ProductExpression(undefined, this.root, path); + if (!this.value.isLoaded('product')) { + return new ProductExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'product')); + } + const relation = this.value.product; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Product)) { + return new ProductExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'product')); + } + const target = relation instanceof Product ? relation : undefined; + return new ProductExpression(target, this.root, path); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + +} + +export class OrderSearchPresetExpression { + constructor( + private readonly value: OrderSearchPreset | null | undefined, + private readonly root = 'OrderSearchPreset(null)', + private readonly path = ExpressionPath.root('E.orderSearchPreset()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): OrderSearchPreset | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + filterJson(): ValueExpression { + const path = this.path.member('filter_json', 'filterJson'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('filterJson')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'filter_json'), + ); + } + return new ValueExpression(this.value.filterJson); + } + + requestId(): ValueExpression { + const path = this.path.member('request_id', 'requestId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requestId')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'request_id'), + ); + } + return new ValueExpression(this.value.requestId); + } + + ownerUserId(): ValueExpression { + const path = this.path.member('owner_user_id', 'ownerUserId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('ownerUserId')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'owner_user_id'), + ); + } + return new ValueExpression(this.value.ownerUserId); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + commercePlatformId(): ValueExpression { + const path = this.path.member('commerce_platform', 'commercePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('commercePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform'), + ); + } + const reference = this.value.commercePlatform; + return new ValueExpression( + reference instanceof CommercePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + commercePlatform(): CommercePlatformExpression { + const path = this.path.member('commerce_platform', 'commercePlatform'); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CommercePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('commercePlatform')) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const relation = this.value.commercePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CommercePlatform)) { + return new CommercePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'commerce_platform')); + } + const target = relation instanceof CommercePlatform ? relation : undefined; + return new CommercePlatformExpression(target, this.root, path); + } + +} + +export class CommercePlatformListExpression { + constructor( + private readonly items: readonly CommercePlatform[], + private readonly root = 'CommercePlatform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CommercePlatformListExpression { + return new CommercePlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): CommercePlatformExpression { + return this.item(0, true); + } + + get(index: number): CommercePlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): CommercePlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new CommercePlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new CommercePlatformExpression(undefined, this.root, itemPath) + : new CommercePlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class CustomerListExpression { + constructor( + private readonly items: readonly Customer[], + private readonly root = 'Customer(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CustomerListExpression { + return new CustomerListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): CustomerExpression { + return this.item(0, true); + } + + get(index: number): CustomerExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): CustomerExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new CustomerExpression(undefined, this.root, itemPath) + : new CustomerExpression(this.items[index], this.root, itemPath); + } +} + +export class OrderStatusListExpression { + constructor( + private readonly items: readonly OrderStatus[], + private readonly root = 'OrderStatus(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderStatusListExpression { + return new OrderStatusListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): OrderStatusExpression { + return this.item(0, true); + } + + get(index: number): OrderStatusExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderStatusExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new OrderStatusExpression(undefined, this.root, itemPath) + : new OrderStatusExpression(this.items[index], this.root, itemPath); + } +} + +export class CustomerOrderListExpression { + constructor( + private readonly items: readonly CustomerOrder[], + private readonly root = 'CustomerOrder(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CustomerOrderListExpression { + return new CustomerOrderListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): CustomerOrderExpression { + return this.item(0, true); + } + + get(index: number): CustomerOrderExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): CustomerOrderExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new CustomerOrderExpression(undefined, this.root, itemPath) + : new CustomerOrderExpression(this.items[index], this.root, itemPath); + } +} + +export class ProductListExpression { + constructor( + private readonly items: readonly Product[], + private readonly root = 'Product(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): ProductListExpression { + return new ProductListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): ProductExpression { + return this.item(0, true); + } + + get(index: number): ProductExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): ProductExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new ProductExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new ProductExpression(undefined, this.root, itemPath) + : new ProductExpression(this.items[index], this.root, itemPath); + } +} + +export class OrderLineListExpression { + constructor( + private readonly items: readonly OrderLine[], + private readonly root = 'OrderLine(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderLineListExpression { + return new OrderLineListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): OrderLineExpression { + return this.item(0, true); + } + + get(index: number): OrderLineExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderLineExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new OrderLineExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new OrderLineExpression(undefined, this.root, itemPath) + : new OrderLineExpression(this.items[index], this.root, itemPath); + } +} + +export class OrderSearchPresetListExpression { + constructor( + private readonly items: readonly OrderSearchPreset[], + private readonly root = 'OrderSearchPreset(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderSearchPresetListExpression { + return new OrderSearchPresetListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): OrderSearchPresetExpression { + return this.item(0, true); + } + + get(index: number): OrderSearchPresetExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderSearchPresetExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new OrderSearchPresetExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new OrderSearchPresetExpression(undefined, this.root, itemPath) + : new OrderSearchPresetExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static commercePlatform( + value: CommercePlatform | null | undefined, + ): CommercePlatformExpression { + return new CommercePlatformExpression( + value, 'CommercePlatform', ExpressionPath.root('E.commercePlatform()', 'camelCase'), + ); + } + + static customer( + value: Customer | null | undefined, + ): CustomerExpression { + return new CustomerExpression( + value, 'Customer', ExpressionPath.root('E.customer()', 'camelCase'), + ); + } + + static orderStatus( + value: OrderStatus | null | undefined, + ): OrderStatusExpression { + return new OrderStatusExpression( + value, 'OrderStatus', ExpressionPath.root('E.orderStatus()', 'camelCase'), + ); + } + + static customerOrder( + value: CustomerOrder | null | undefined, + ): CustomerOrderExpression { + return new CustomerOrderExpression( + value, 'CustomerOrder', ExpressionPath.root('E.customerOrder()', 'camelCase'), + ); + } + + static product( + value: Product | null | undefined, + ): ProductExpression { + return new ProductExpression( + value, 'Product', ExpressionPath.root('E.product()', 'camelCase'), + ); + } + + static orderLine( + value: OrderLine | null | undefined, + ): OrderLineExpression { + return new OrderLineExpression( + value, 'OrderLine', ExpressionPath.root('E.orderLine()', 'camelCase'), + ); + } + + static orderSearchPreset( + value: OrderSearchPreset | null | undefined, + ): OrderSearchPresetExpression { + return new OrderSearchPresetExpression( + value, 'OrderSearchPreset', ExpressionPath.root('E.orderSearchPreset()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts index d6d13901bbbf784ca6a47eb2926f67cac9e7e3ac..adea79898633b3437adcd5d7269d9d67f1a21716 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/Q.ts @@ -9,24 +9,52 @@ import { OrderSearchPresetRequest } from './requests/OrderSearchPresetRequest'; export class Q { static commercePlatforms(): CommercePlatformRequest { - return new CommercePlatformRequest(); + return new CommercePlatformRequest(false); + } + + static commercePlatformsWithMinimalFields(): CommercePlatformRequest { + return new CommercePlatformRequest(true); } static customers(): CustomerRequest { - return new CustomerRequest(); + return new CustomerRequest(false); + } + + static customersWithMinimalFields(): CustomerRequest { + return new CustomerRequest(true); } static orderStatuses(): OrderStatusRequest { - return new OrderStatusRequest(); + return new OrderStatusRequest(false); + } + + static orderStatusesWithMinimalFields(): OrderStatusRequest { + return new OrderStatusRequest(true); } static customerOrders(): CustomerOrderRequest { - return new CustomerOrderRequest(); + return new CustomerOrderRequest(false); + } + + static customerOrdersWithMinimalFields(): CustomerOrderRequest { + return new CustomerOrderRequest(true); } static products(): ProductRequest { - return new ProductRequest(); + return new ProductRequest(false); + } + + static productsWithMinimalFields(): ProductRequest { + return new ProductRequest(true); } static orderLines(): OrderLineRequest { - return new OrderLineRequest(); + return new OrderLineRequest(false); + } + + static orderLinesWithMinimalFields(): OrderLineRequest { + return new OrderLineRequest(true); } static orderSearchPresets(): OrderSearchPresetRequest { - return new OrderSearchPresetRequest(); + return new OrderSearchPresetRequest(false); + } + + static orderSearchPresetsWithMinimalFields(): OrderSearchPresetRequest { + return new OrderSearchPresetRequest(true); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts index a68d8cc2ca9842f459f99553d125f457e4caa3c3..f3cb604412c9bc995251208cf3a2771801cb8fe0 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts @@ -1,137 +1,876 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Customer } from './Customer'; +import { OrderStatus } from './OrderStatus'; +import { CustomerOrder } from './CustomerOrder'; +import { Product } from './Product'; +import { OrderLine } from './OrderLine'; +import { OrderSearchPreset } from './OrderSearchPreset'; + +const teaqlConstruction = Symbol("managed entity construction"); export class CommercePlatform { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("CommercePlatform", + ["id", "name", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerList", { value: [], writable: true, enumerable: false }); - Object.defineProperty(this, "_orderStatusList", { value: [], writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); - Object.defineProperty(this, "_productList", { value: [], writable: true, enumerable: false }); - Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); - Object.defineProperty(this, "_orderSearchPresetList", { value: [], writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CommercePlatform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderStatusList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_productList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderSearchPresetList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["customerList"]; + delete fields["orderStatusList"]; + delete fields["customerOrderList"]; + delete fields["productList"]; + delete fields["orderLineList"]; + delete fields["orderSearchPresetList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).customerList)) { + const selected = (init as any).customerList; + (this as any)._customerList = new SmartList(selected.map( + (child: unknown) => child instanceof Customer + ? child + : Customer.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("customerList"); + } + if (Array.isArray((init as any).orderStatusList)) { + const selected = (init as any).orderStatusList; + (this as any)._orderStatusList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderStatus + ? child + : OrderStatus.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderStatusList"); + } + if (Array.isArray((init as any).customerOrderList)) { + const selected = (init as any).customerOrderList; + (this as any)._customerOrderList = new SmartList(selected.map( + (child: unknown) => child instanceof CustomerOrder + ? child + : CustomerOrder.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("customerOrderList"); + } + if (Array.isArray((init as any).productList)) { + const selected = (init as any).productList; + (this as any)._productList = new SmartList(selected.map( + (child: unknown) => child instanceof Product + ? child + : Product.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("productList"); + } + if (Array.isArray((init as any).orderLineList)) { + const selected = (init as any).orderLineList; + (this as any)._orderLineList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderLine + ? child + : OrderLine.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderLineList"); + } + if (Array.isArray((init as any).orderSearchPresetList)) { + const selected = (init as any).orderSearchPresetList; + (this as any)._orderSearchPresetList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderSearchPreset + ? child + : OrderSearchPreset.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderSearchPresetList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "CommercePlatform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._customerList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._productList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._orderLineList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._orderSearchPresetList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): CommercePlatform { + const entity = EntityCreation.hydrated(new CommercePlatform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerList")) result["customerList"] = (this as any)._customerList; + if (this.isLoaded("orderStatusList")) result["orderStatusList"] = (this as any)._orderStatusList; + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + if (this.isLoaded("productList")) result["productList"] = (this as any)._productList; + if (this.isLoaded("orderLineList")) result["orderLineList"] = (this as any)._orderLineList; + if (this.isLoaded("orderSearchPresetList")) result["orderSearchPresetList"] = (this as any)._orderSearchPresetList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): CommercePlatform { - return new CommercePlatform({ id: String(id) } as Partial); + return CommercePlatform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): CommercePlatform { + return EntityCreation.bootstrap(context, "CommercePlatform", id, + reserved => new CommercePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "CommercePlatform", + reserved => new CommercePlatform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._orderStatusList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._productList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._orderLineList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._orderSearchPresetList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderStatusList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } } + for (const [index, child] of (this as any)._productList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("product_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderSearchPresetList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_search_preset_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CommercePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._orderStatusList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._productList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._orderLineList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._orderSearchPresetList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CommercePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_list": graph.sourceMembers((this as any)._customerList), + "order_status_list": graph.sourceMembers((this as any)._orderStatusList), + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList), + "product_list": graph.sourceMembers((this as any)._productList), + "order_line_list": graph.sourceMembers((this as any)._orderLineList), + "order_search_preset_list": graph.sourceMembers((this as any)._orderSearchPresetList) + })); + for (const child of (this as any)._customerList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._orderStatusList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._productList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._orderLineList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._orderSearchPresetList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + CommercePlatform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "CommercePlatform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderStatusList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._productList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("product_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderSearchPresetList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_search_preset_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(CommercePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "CommercePlatform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "CommercePlatform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._productList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("product_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderSearchPresetList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_search_preset_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "CommercePlatform", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; - } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { - for (const child of (this as any)._customerList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); - } - for (const child of (this as any)._orderStatusList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); - } - for (const child of (this as any)._customerOrderList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); - } - for (const child of (this as any)._productList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); - } - for (const child of (this as any)._orderLineList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); - } - for (const child of (this as any)._orderSearchPresetList) { - child.updateCommercePlatform(this); - child.auditAs((this as any)._comment); - await child.save(ctx); + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._productList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("product_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } } + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderSearchPresetList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_search_preset_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; } - return result; + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._customerList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._productList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("product_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderSearchPresetList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.commercePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("commercePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCommercePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_search_preset_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateName(value: string): this { this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } updateUpdateTime(value: string): this { this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } - customerList(): any[] { + customerList(): SmartList { return (this as any)._customerList; } - orderStatusList(): any[] { + orderStatusList(): SmartList { return (this as any)._orderStatusList; } - customerOrderList(): any[] { + customerOrderList(): SmartList { return (this as any)._customerOrderList; } - productList(): any[] { + productList(): SmartList { return (this as any)._productList; } - orderLineList(): any[] { + orderLineList(): SmartList { return (this as any)._orderLineList; } - orderSearchPresetList(): any[] { + orderSearchPresetList(): SmartList { return (this as any)._orderSearchPresetList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts index 57f36a2ba9bb65a6edb5c6c8f2c3a4bfbe1a4c77..ff06d75e388df7911696b00b3163d29111bc1316 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts @@ -1,99 +1,447 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CommercePlatform } from './CommercePlatform'; +import { CustomerOrder } from './CustomerOrder'; + +const teaqlConstruction = Symbol("managed entity construction"); export class Customer { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Customer", + ["id", "name", "email", "commerce_platform", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; email?: string; - commercePlatform?: any; + commercePlatform?: CommercePlatform | string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Customer.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["customerOrderList"]; + Object.assign(this, fields); + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + if (Array.isArray((init as any).customerOrderList)) { + const selected = (init as any).customerOrderList; + (this as any)._customerOrderList = new SmartList(selected.map( + (child: unknown) => child instanceof CustomerOrder + ? child + : CustomerOrder.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("customerOrderList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Customer", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Customer { + const entity = EntityCreation.hydrated(new Customer(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): Customer { - return new Customer({ id: String(id) } as Partial); + return Customer.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): Customer { + return EntityCreation.bootstrap(context, "Customer", id, + reserved => new Customer({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Customer", + reserved => new Customer({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList) + })); + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customer; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Customer.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "email", canonical: "email" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Customer", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "email", canonical: "email" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Customer", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } } + const request = graph.request({ + entity: "Customer", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customer; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "Customer", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customer; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { - for (const child of (this as any)._customerOrderList) { - child.updateCustomer(this); - child.auditAs((this as any)._comment); - await child.save(ctx); + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customer; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); } } - return result; + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "email": this.email, + "commerce_platform": this.commercePlatform, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateName(value: string): this { this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); return this; } updateEmail(value: string): this { this.email = value; + this.markLoaded("email"); + (this as any)._root.set(this.teaqlEntityKey(), "email", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } updateUpdateTime(value: string): this { this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } - customerOrderList(): any[] { + customerOrderList(): SmartList { return (this as any)._customerOrderList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts index f0d2a004146a7a705da8f4001950487302c359fa..6c5db6a484e7921bcf51853cf626489c5c324583 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts @@ -1,135 +1,505 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { OrderStatus } from './OrderStatus'; +import { Customer } from './Customer'; +import { CommercePlatform } from './CommercePlatform'; +import { OrderLine } from './OrderLine'; + +const teaqlConstruction = Symbol("managed entity construction"); export class CustomerOrder { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("CustomerOrder", + ["id", "order_number", "order_date", "total_amount", "status", "customer", "commerce_platform", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; orderNumber?: string; orderDate?: string; - totalAmount?: number; - status?: any; - customer?: any; - commercePlatform?: any; + totalAmount?: Decimal; + status?: OrderStatus | string; + customer?: Customer | string; + commercePlatform?: CommercePlatform | string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["orderLineList"]; + Object.assign(this, fields); + if ((init as any).status && typeof (init as any).status === "object") { + this.status = (init as any).status instanceof OrderStatus + ? (init as any).status + : OrderStatus.fromRecord((init as any).status); + this.markLoaded("status"); + } + if ((init as any).customer && typeof (init as any).customer === "object") { + this.customer = (init as any).customer instanceof Customer + ? (init as any).customer + : Customer.fromRecord((init as any).customer); + this.markLoaded("customer"); + } + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + if (Array.isArray((init as any).orderLineList)) { + const selected = (init as any).orderLineList; + (this as any)._orderLineList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderLine + ? child + : OrderLine.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderLineList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._orderLineList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): CustomerOrder { + const entity = EntityCreation.hydrated(new CustomerOrder(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderLineList")) result["orderLineList"] = (this as any)._orderLineList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): CustomerOrder { - return new CustomerOrder({ id: String(id) } as Partial); + return CustomerOrder.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): CustomerOrder { + return EntityCreation.bootstrap(context, "CustomerOrder", id, + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "CustomerOrder", + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderLineList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderLineList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "status": "OrderStatus", + "customer": "Customer", + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_line_list": graph.sourceMembers((this as any)._orderLineList) + })); + for (const child of (this as any)._orderLineList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + CustomerOrder.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "orderNumber", canonical: "order_number" }, { member: "orderDate", canonical: "order_date" }, { member: "totalAmount", canonical: "total_amount" }, { member: "status", canonical: "status" }, { member: "customer", canonical: "customer" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "orderNumber", canonical: "order_number" }, { member: "orderDate", canonical: "order_date" }, { member: "totalAmount", canonical: "total_amount" }, { member: "status", canonical: "status" }, { member: "customer", canonical: "customer" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "CustomerOrder", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "CustomerOrder", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "CustomerOrder", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { - for (const child of (this as any)._orderLineList) { - child.updateCustomerOrder(this); - child.auditAs((this as any)._comment); - await child.save(ctx); + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); } } - return result; + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "order_number": this.orderNumber, + "order_date": this.orderDate, + "total_amount": this.totalAmount, + "status": this.status, + "customer": this.customer, + "commerce_platform": this.commercePlatform, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateOrderNumber(value: string): this { this.orderNumber = value; + this.markLoaded("orderNumber"); + (this as any)._root.set(this.teaqlEntityKey(), "order_number", value); return this; } updateOrderDate(value: string): this { this.orderDate = value; + this.markLoaded("orderDate"); + (this as any)._root.set(this.teaqlEntityKey(), "order_date", value); return this; } - updateTotalAmount(value: number): this { + updateTotalAmount(value: Decimal): this { + if (value != null) value = decimal(value); this.totalAmount = value; + this.markLoaded("totalAmount"); + (this as any)._root.set(this.teaqlEntityKey(), "total_amount", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } updateUpdateTime(value: string): this { this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateStatus(value: any): this { this.status = value?.id ?? value; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); return this; } public updateStatusToPending(): CustomerOrder { this.status = "1001"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); return this; } - public updateStatusToProcessing(): CustomerOrder { + public updateStatusToConfirmed(): CustomerOrder { this.status = "1002"; - return this; - } - public updateStatusToShipped(): CustomerOrder { - this.status = "1003"; - return this; - } - public updateStatusToCompleted(): CustomerOrder { - this.status = "1004"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); return this; } updateCustomer(value: any): this { this.customer = value?.id ?? value; + this.markLoaded("customer"); + (this as any)._root.set(this.teaqlEntityKey(), "customer", this.customer); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } - orderLineList(): any[] { + orderLineList(): SmartList { return (this as any)._orderLineList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts index ff730f3ae9e838dd11df076199bb68b602161a95..4cd4637478dea2f1a430dedf7f3c68b8fd234c75 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts @@ -1,103 +1,400 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CustomerOrder } from './CustomerOrder'; +import { Product } from './Product'; +import { CommercePlatform } from './CommercePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); export class OrderLine { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderLine", + ["id", "customer_order", "product", "product_name", "sku", "quantity", "commerce_platform", "create_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; - customerOrder?: any; - product?: any; + customerOrder?: CustomerOrder | string; + product?: Product | string; productName?: string; sku?: string; - quantity?: any; - commercePlatform?: any; + quantity?: number; + commercePlatform?: CommercePlatform | string; createTime?: string; - version?: number; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.quantity, "OrderLine", "quantity"); if (error) throw error; } + + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderLine.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") { + this.customerOrder = (init as any).customerOrder instanceof CustomerOrder + ? (init as any).customerOrder + : CustomerOrder.fromRecord((init as any).customerOrder); + this.markLoaded("customerOrder"); + } + if ((init as any).product && typeof (init as any).product === "object") { + this.product = (init as any).product instanceof Product + ? (init as any).product + : Product.fromRecord((init as any).product); + this.markLoaded("product"); + } + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "OrderLine", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): OrderLine { + const entity = EntityCreation.hydrated(new OrderLine(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.quantity, "OrderLine", "quantity"); if (error) throw error; } + + + + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): OrderLine { - return new OrderLine({ id: String(id) } as Partial); + return OrderLine.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderLine { + return EntityCreation.bootstrap(context, "OrderLine", id, + reserved => new OrderLine({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderLine", + reserved => new OrderLine({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderLine.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderLine.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer_order": "CustomerOrder", + "product": "Product", + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderLine.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "product", canonical: "product" }, { member: "productName", canonical: "product_name" }, { member: "sku", canonical: "sku" }, { member: "quantity", canonical: "quantity" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderLine", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(OrderLine.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "product", canonical: "product" }, { member: "productName", canonical: "product_name" }, { member: "sku", canonical: "sku" }, { member: "quantity", canonical: "quantity" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "OrderLine", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "OrderLine", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "OrderLine", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); } - return result; + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "customer_order": this.customerOrder, + "product": this.product, + "product_name": this.productName, + "sku": this.sku, + "quantity": this.quantity, + "commerce_platform": this.commercePlatform, + "create_time": this.createTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateProductName(value: string): this { this.productName = value; + this.markLoaded("productName"); + (this as any)._root.set(this.teaqlEntityKey(), "product_name", value); return this; } updateSku(value: string): this { this.sku = value; + this.markLoaded("sku"); + (this as any)._root.set(this.teaqlEntityKey(), "sku", value); return this; } - updateQuantity(value: any): this { + updateQuantity(value: number): this { this.quantity = value; + this.markLoaded("quantity"); + (this as any)._root.set(this.teaqlEntityKey(), "quantity", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateCustomerOrder(value: any): this { this.customerOrder = value?.id ?? value; + this.markLoaded("customerOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "customer_order", this.customerOrder); return this; } updateProduct(value: any): this { this.product = value?.id ?? value; + this.markLoaded("product"); + (this as any)._root.set(this.teaqlEntityKey(), "product", this.product); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts index 165a6a8ee67e02500f6ef5ce0ce309da2cde16ae..01adf208c2002ecb8105fb7ab052f679bacab754 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts @@ -1,101 +1,374 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CommercePlatform } from './CommercePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); export class OrderSearchPreset { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderSearchPreset", + ["id", "name", "filter_json", "request_id", "owner_user_id", "commerce_platform", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; filterJson?: string; requestId?: string; ownerUserId?: string; - commercePlatform?: any; + commercePlatform?: CommercePlatform | string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderSearchPreset.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "OrderSearchPreset", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): OrderSearchPreset { + const entity = EntityCreation.hydrated(new OrderSearchPreset(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): OrderSearchPreset { - return new OrderSearchPreset({ id: String(id) } as Partial); + return OrderSearchPreset.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderSearchPreset { + return EntityCreation.bootstrap(context, "OrderSearchPreset", id, + reserved => new OrderSearchPreset({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderSearchPreset", + reserved => new OrderSearchPreset({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderSearchPreset.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderSearchPreset.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderSearchPreset.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "filterJson", canonical: "filter_json" }, { member: "requestId", canonical: "request_id" }, { member: "ownerUserId", canonical: "owner_user_id" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderSearchPreset", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(OrderSearchPreset.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "filterJson", canonical: "filter_json" }, { member: "requestId", canonical: "request_id" }, { member: "ownerUserId", canonical: "owner_user_id" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "OrderSearchPreset", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } } + const request = graph.request({ + entity: "OrderSearchPreset", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "OrderSearchPreset", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); } - return result; + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "filter_json": this.filterJson, + "request_id": this.requestId, + "owner_user_id": this.ownerUserId, + "commerce_platform": this.commercePlatform, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateName(value: string): this { this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); return this; } updateFilterJson(value: string): this { this.filterJson = value; + this.markLoaded("filterJson"); + (this as any)._root.set(this.teaqlEntityKey(), "filter_json", value); return this; } updateRequestId(value: string): this { this.requestId = value; + this.markLoaded("requestId"); + (this as any)._root.set(this.teaqlEntityKey(), "request_id", value); return this; } updateOwnerUserId(value: string): this { this.ownerUserId = value; + this.markLoaded("ownerUserId"); + (this as any)._root.set(this.teaqlEntityKey(), "owner_user_id", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } updateUpdateTime(value: string): this { this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts index aecd15c248718ece781534e0151c79c867dc2236..f81e3d2193b2325e6c08b1ef291ba2e749f6067f 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts @@ -1,99 +1,448 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CommercePlatform } from './CommercePlatform'; +import { CustomerOrder } from './CustomerOrder'; + +const teaqlConstruction = Symbol("managed entity construction"); export class OrderStatus { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderStatus", + ["id", "name", "code", "color", "display_order", "commerce_platform", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; code?: string; - color?: string; - displayOrder?: number; - commercePlatform?: any; - version?: number; + color?: string | null; + displayOrder?: Decimal | null; + commercePlatform?: CommercePlatform | string; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: [], writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderStatus.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["customerOrderList"]; + Object.assign(this, fields); + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + if (Array.isArray((init as any).customerOrderList)) { + const selected = (init as any).customerOrderList; + (this as any)._customerOrderList = new SmartList(selected.map( + (child: unknown) => child instanceof CustomerOrder + ? child + : CustomerOrder.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("customerOrderList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "OrderStatus", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): OrderStatus { + const entity = EntityCreation.hydrated(new OrderStatus(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): OrderStatus { - return new OrderStatus({ id: String(id) } as Partial); + return OrderStatus.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderStatus { + return EntityCreation.bootstrap(context, "OrderStatus", id, + reserved => new OrderStatus({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderStatus", + reserved => new OrderStatus({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList) + })); + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderStatus.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderStatus", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "OrderStatus", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } } + const request = graph.request({ + entity: "OrderStatus", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "OrderStatus", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { - for (const child of (this as any)._customerOrderList) { - child.updateStatus(this); - child.auditAs((this as any)._comment); - await child.save(ctx); + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); } } - return result; + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "code": this.code, + "color": this.color, + "display_order": this.displayOrder, + "commerce_platform": this.commercePlatform, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateName(value: string): this { this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); return this; } updateCode(value: string): this { this.code = value; + this.markLoaded("code"); + (this as any)._root.set(this.teaqlEntityKey(), "code", value); return this; } - updateColor(value: string): this { + updateColor(value: string | null): this { this.color = value; + this.markLoaded("color"); + (this as any)._root.set(this.teaqlEntityKey(), "color", value); return this; } - updateDisplayOrder(value: number): this { + updateDisplayOrder(value: Decimal | null): this { + if (value != null) value = decimal(value); this.displayOrder = value; + this.markLoaded("displayOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } - customerOrderList(): any[] { + customerOrderList(): SmartList { return (this as any)._customerOrderList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts index a0de4a9368ab291181025081eccb4ac70eba2661..17f17191794e0dc2f79fe3f91c28296d9f143b4a 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts @@ -1,105 +1,456 @@ -import { TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CommercePlatform } from './CommercePlatform'; +import { OrderLine } from './OrderLine'; + +const teaqlConstruction = Symbol("managed entity construction"); export class Product { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Product", + ["id", "name", "sku", "image_url", "commerce_platform", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; sku?: string; - imageUrl?: string; - commercePlatform?: any; + imageUrl?: string | null; + commercePlatform?: CommercePlatform | string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_orderLineList", { value: [], writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Product.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_orderLineList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["orderLineList"]; + Object.assign(this, fields); + if ((init as any).commercePlatform && typeof (init as any).commercePlatform === "object") { + this.commercePlatform = (init as any).commercePlatform instanceof CommercePlatform + ? (init as any).commercePlatform + : CommercePlatform.fromRecord((init as any).commercePlatform); + this.markLoaded("commercePlatform"); + } + if (Array.isArray((init as any).orderLineList)) { + const selected = (init as any).orderLineList; + (this as any)._orderLineList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderLine + ? child + : OrderLine.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderLineList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Product", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._orderLineList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Product { + const entity = EntityCreation.hydrated(new Product(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderLineList")) result["orderLineList"] = (this as any)._orderLineList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; } static refer(id: string | number): Product { - return new Product({ id: String(id) } as Partial); + return Product.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): Product { + return EntityCreation.bootstrap(context, "Product", id, + reserved => new Product({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Product", + reserved => new Product({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: UserContext): Promise { - if (!(this as any)._comment) { - throw new Error("Security audit failure: auditAs() must be called before save()"); + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderLineList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Product.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderLineList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Product.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "commerce_platform": "CommercePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_line_list": graph.sourceMembers((this as any)._orderLineList) + })); + for (const child of (this as any)._orderLineList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.product; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("product") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateProduct(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Product.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "sku", canonical: "sku" }, { member: "imageUrl", canonical: "image_url" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Product", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderLineList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(Product.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "sku", canonical: "sku" }, { member: "imageUrl", canonical: "image_url" }, { member: "commercePlatform", canonical: "commerce_platform" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Product", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } } + const request = graph.request({ + entity: "Product", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.product; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("product") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateProduct(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "Product", action: (this as any)._action, - payload: this, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - const service = ctx.requireResource("dataService"); - const result = await service.executeMutation(mutation); - if ((this as any)._action === "Create") { - (this as any).id = result.id; - (this as any)._action = "Update"; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.product; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("product") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateProduct(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; } - if (result.version !== undefined) (this as any).version = result.version; - if (mutation.action !== "Delete") { - for (const child of (this as any)._orderLineList) { - child.updateProduct(this); - child.auditAs((this as any)._comment); - await child.save(ctx); + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._orderLineList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.product; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("product") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateProduct(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_line_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); } } - return result; + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "sku": this.sku, + "image_url": this.imageUrl, + "commerce_platform": this.commercePlatform, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } updateId(value: string): this { this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); return this; } updateName(value: string): this { this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); return this; } updateSku(value: string): this { this.sku = value; + this.markLoaded("sku"); + (this as any)._root.set(this.teaqlEntityKey(), "sku", value); return this; } - updateImageUrl(value: string): this { + updateImageUrl(value: string | null): this { this.imageUrl = value; + this.markLoaded("imageUrl"); + (this as any)._root.set(this.teaqlEntityKey(), "image_url", value); return this; } updateCreateTime(value: string): this { this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); return this; } updateUpdateTime(value: string): this { this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); return this; } updateCommercePlatform(value: any): this { this.commercePlatform = value?.id ?? value; + this.markLoaded("commercePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "commerce_platform", this.commercePlatform); return this; } - orderLineList(): any[] { + orderLineList(): SmartList { return (this as any)._orderLineList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts index de644cc8972ac0b53a28339cb45db629cce1758a..46fd0f362c6199eaa4b8e3315243ff919050eba0 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { CommercePlatform } from '../models/CommercePlatform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class CommercePlatformRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("CommercePlatform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "CommercePlatform" { + return "CommercePlatform"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class CommercePlatformRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableCommercePlatformRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableCommercePlatformRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,54 +97,827 @@ export class CommercePlatformRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } - selectCustomerListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("customerList", request.toQuery()); + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectCustomerListWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "customerList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectCustomerListWith", relation: "customerList" }); + return this; + } + selectOrderStatusListWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderStatusList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectOrderStatusListWith", relation: "orderStatusList" }); + return this; + } + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "customerOrderList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); + return this; + } + selectProductListWith(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "productList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectProductListWith", relation: "productList" }); + return this; + } + selectOrderLineListWith(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderLineList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectOrderLineListWith", relation: "orderLineList" }); + return this; + } + selectOrderSearchPresetListWith(request: { readonly entityName: "OrderSearchPreset"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderSearchPresetList", request.toQuery(), "id", "commercePlatform", true, + { kind: "relation-select", method: "selectOrderSearchPresetListWith", relation: "orderSearchPresetList" }); + return this; + } + + haveCustomers(): this { + return this.withCustomerListMatching({ + entityName: "Customer", + toQuery: () => new SelectQuery("Customer"), + }); + } + + haveNoCustomers(): this { + return this.withoutCustomerListMatching({ + entityName: "Customer", + toQuery: () => new SelectQuery("Customer"), + }); + } + + withCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + haveOrderStatuses(): this { + return this.withOrderStatusListMatching({ + entityName: "OrderStatus", + toQuery: () => new SelectQuery("OrderStatus"), + }); + } + + haveNoOrderStatuses(): this { + return this.withoutOrderStatusListMatching({ + entityName: "OrderStatus", + toQuery: () => new SelectQuery("OrderStatus"), + }); + } + + withOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + haveCustomerOrders(): this { + return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + haveNoCustomerOrders(): this { + return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + haveProducts(): this { + return this.withProductListMatching({ + entityName: "Product", + toQuery: () => new SelectQuery("Product"), + }); + } + + haveNoProducts(): this { + return this.withoutProductListMatching({ + entityName: "Product", + toQuery: () => new SelectQuery("Product"), + }); + } + + withProductListMatching(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutProductListMatching(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + haveOrderLines(): this { + return this.withOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + haveNoOrderLines(): this { + return this.withoutOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + withOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + haveOrderSearchPresets(): this { + return this.withOrderSearchPresetListMatching({ + entityName: "OrderSearchPreset", + toQuery: () => new SelectQuery("OrderSearchPreset"), + }); + } + + haveNoOrderSearchPresets(): this { + return this.withoutOrderSearchPresetListMatching({ + entityName: "OrderSearchPreset", + toQuery: () => new SelectQuery("OrderSearchPreset"), + }); + } + + withOrderSearchPresetListMatching(request: { readonly entityName: "OrderSearchPreset"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + withoutOrderSearchPresetListMatching(request: { readonly entityName: "OrderSearchPreset"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "commercePlatform", + }, + }, + }); + return this; + } + + countCustomers(): this { + return this.countCustomersAs("countCustomers"); + } + + countCustomersAs(alias: string): this { + const query = new SelectQuery("Customer").filter({ version: { "$gte": 1 } }); + this.countCustomersWith(alias, { entityName: "Customer", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countCustomersAs", relation: "customerList", alias }; + return this; + } + + countCustomersWith(alias: string, child: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("customerList", alias, query, true, + { kind: "relation-count", method: "countCustomersWith", relation: "customerList", alias }); + return this; + } + + + countOrderStatuses(): this { + return this.countOrderStatusesAs("countOrderStatuses"); + } + + countOrderStatusesAs(alias: string): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + this.countOrderStatusesWith(alias, { entityName: "OrderStatus", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderStatusesAs", relation: "orderStatusList", alias }; + return this; + } + + countOrderStatusesWith(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "relation-count", method: "countOrderStatusesWith", relation: "orderStatusList", alias }); + return this; + } + + minDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.minDisplayOrderOfOrderStatusesAs( + "minOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + minDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "minDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + maxDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.maxDisplayOrderOfOrderStatusesAs( + "maxOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + maxDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "maxDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + sumDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.sumDisplayOrderOfOrderStatusesAs( + "sumOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + sumDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "sumDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + avgDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.avgDisplayOrderOfOrderStatusesAs( + "avgOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + avgDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "avgDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + standardDeviationDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.standardDeviationDisplayOrderOfOrderStatusesAs( + "standardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "standardDeviationDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs( + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + sampleVarianceDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceDisplayOrderOfOrderStatusesAs( + "sampleVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + samplePopulationVarianceDisplayOrderOfOrderStatuses(): this { + const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs( + "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); + } + + samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "displayOrder", alias); + this.query.relationAggregate("orderStatusList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfOrderStatusesAs", relation: "orderStatusList", alias }); + return this; + } + countCustomerOrders(): this { + return this.countCustomerOrdersAs("countCustomerOrders"); + } + + countCustomerOrdersAs(alias: string): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; + return this; + } + + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "relation-count", method: "countCustomerOrdersWith", relation: "customerOrderList", alias }); + return this; + } + + minTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.minTotalAmountOfCustomerOrdersAs( + "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "minTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + maxTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.maxTotalAmountOfCustomerOrdersAs( + "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "maxTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sumTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sumTotalAmountOfCustomerOrdersAs( + "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sumTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + avgTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.avgTotalAmountOfCustomerOrdersAs( + "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "avgTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + standardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.standardDeviationTotalAmountOfCustomerOrdersAs( + "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "standardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs( + "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sampleVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceTotalAmountOfCustomerOrdersAs( + "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + samplePopulationVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs( + "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + countProducts(): this { + return this.countProductsAs("countProducts"); + } + + countProductsAs(alias: string): this { + const query = new SelectQuery("Product").filter({ version: { "$gte": 1 } }); + this.countProductsWith(alias, { entityName: "Product", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countProductsAs", relation: "productList", alias }; + return this; + } + + countProductsWith(alias: string, child: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("productList", alias, query, true, + { kind: "relation-count", method: "countProductsWith", relation: "productList", alias }); + return this; + } + + + countOrderLines(): this { + return this.countOrderLinesAs("countOrderLines"); + } + + countOrderLinesAs(alias: string): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + this.countOrderLinesWith(alias, { entityName: "OrderLine", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderLinesAs", relation: "orderLineList", alias }; return this; } - selectOrderStatusListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("orderStatusList", request.toQuery()); + + countOrderLinesWith(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "relation-count", method: "countOrderLinesWith", relation: "orderLineList", alias }); return this; } - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("customerOrderList", request.toQuery()); + + minQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.minQuantityOfOrderLinesAs( + "minOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + minQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "minQuantityOfOrderLinesAs", relation: "orderLineList", alias }); return this; } - selectProductListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("productList", request.toQuery()); + maxQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.maxQuantityOfOrderLinesAs( + "maxOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + maxQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "maxQuantityOfOrderLinesAs", relation: "orderLineList", alias }); return this; } - selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("orderLineList", request.toQuery()); + sumQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sumQuantityOfOrderLinesAs( + "sumOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sumQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sumQuantityOfOrderLinesAs", relation: "orderLineList", alias }); return this; } - selectOrderSearchPresetListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("orderSearchPresetList", request.toQuery()); + avgQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.avgQuantityOfOrderLinesAs( + "avgOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + avgQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "avgQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + standardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.standardDeviationQuantityOfOrderLinesAs( + "standardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + standardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "standardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs( + "squareRootOfPopulationStandardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + sampleVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceQuantityOfOrderLinesAs( + "sampleVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sampleVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + samplePopulationVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceQuantityOfOrderLinesAs( + "samplePopulationVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + samplePopulationVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + countOrderSearchPresets(): this { + return this.countOrderSearchPresetsAs("countOrderSearchPresets"); + } + + countOrderSearchPresetsAs(alias: string): this { + const query = new SelectQuery("OrderSearchPreset").filter({ version: { "$gte": 1 } }); + this.countOrderSearchPresetsWith(alias, { entityName: "OrderSearchPreset", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderSearchPresetsAs", relation: "orderSearchPresetList", alias }; + return this; + } + + countOrderSearchPresetsWith(alias: string, child: { readonly entityName: "OrderSearchPreset"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderSearchPresetList", alias, query, true, + { kind: "relation-count", method: "countOrderSearchPresetsWith", relation: "orderSearchPresetList", alias }); return this; } - withIdIs(val: any): this { + + + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withNameContaining(val: string): this { this.filters.push({ "name": { "$contains": val } }); return this; @@ -99,71 +928,250 @@ export class CommercePlatformRequest { return this; } + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withCreateTimeIs(val: any): this { + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withUpdateTimeIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -218,11 +1226,15 @@ export class CommercePlatformRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -234,7 +1246,7 @@ export class CommercePlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -243,7 +1255,7 @@ export class CommercePlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCreateTime(): this { @@ -252,7 +1264,7 @@ export class CommercePlatformRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -261,7 +1273,7 @@ export class CommercePlatformRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -270,59 +1282,142 @@ export class CommercePlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof CommercePlatform + ? row + : CommercePlatform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); - } - result.facets[f.facetName] = await service.executeQuery(f.query); - } + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); } return result; } + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof CommercePlatform + ? row + : CommercePlatform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof CommercePlatform + ? entity + : CommercePlatform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + } export class ExecutableCommercePlatformRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): CommercePlatform { - return new CommercePlatform(); + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return CommercePlatform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); } - async executeForOne(ctx: UserContext): Promise { + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts index 4becbf9a5a1b916d30735cabedd5af0a4d6c7a8c..000f7c6401689ec8eda770743bc3f624c63f064b 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { CustomerOrder } from '../models/CustomerOrder'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class CustomerOrderRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("CustomerOrder"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "CustomerOrder" { + return "CustomerOrder"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class CustomerOrderRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableCustomerOrderRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableCustomerOrderRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,34 +97,375 @@ export class CustomerOrderRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } - selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("orderLineList", request.toQuery()); + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "orderNumber", "orderDate", "totalAmount", "status", "customer", "commercePlatform", "createTime", "updateTime", "version"]); return this; } - withIdIs(val: any): this { + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectOrderNumber(): this { + this.query.select(["orderNumber"]); + return this; + } + + selectOrderDate(): this { + this.query.select(["orderDate"]); + return this; + } + + selectTotalAmount(): this { + this.query.select(["totalAmount"]); + return this; + } + + + + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectStatusWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.query.select(["status"]); + this.query.relationQuery( + "status", request.toQuery(), "status", "id", false, + { kind: "relation-select", method: "selectStatusWith", relation: "status" }); + return this; + } + selectCustomerWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.query.select(["customer"]); + this.query.relationQuery( + "customer", request.toQuery(), "customer", "id", false, + { kind: "relation-select", method: "selectCustomerWith", relation: "customer" }); + return this; + } + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "status": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "status": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.filters.push({ + "customer": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { + this.filters.push({ + "customer": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectOrderLineListWith(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderLineList", request.toQuery(), "id", "customerOrder", true, + { kind: "relation-select", method: "selectOrderLineListWith", relation: "orderLineList" }); + return this; + } + + haveOrderLines(): this { + return this.withOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + haveNoOrderLines(): this { + return this.withoutOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + withOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "customerOrder", + }, + }, + }); + return this; + } + + withoutOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "customerOrder", + }, + }, + }); + return this; + } + + countOrderLines(): this { + return this.countOrderLinesAs("countOrderLines"); + } + + countOrderLinesAs(alias: string): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + this.countOrderLinesWith(alias, { entityName: "OrderLine", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderLinesAs", relation: "orderLineList", alias }; + return this; + } + + countOrderLinesWith(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "relation-count", method: "countOrderLinesWith", relation: "orderLineList", alias }); + return this; + } + + minQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.minQuantityOfOrderLinesAs( + "minOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + minQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "minQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + maxQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.maxQuantityOfOrderLinesAs( + "maxOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + maxQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "maxQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + sumQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sumQuantityOfOrderLinesAs( + "sumOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sumQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sumQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + avgQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.avgQuantityOfOrderLinesAs( + "avgOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + avgQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "avgQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + standardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.standardDeviationQuantityOfOrderLinesAs( + "standardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + standardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "standardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs( + "squareRootOfPopulationStandardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + sampleVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceQuantityOfOrderLinesAs( + "sampleVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sampleVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + samplePopulationVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceQuantityOfOrderLinesAs( + "samplePopulationVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + samplePopulationVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withOrderNumberContaining(val: string): this { this.filters.push({ "orderNumber": { "$contains": val } }); return this; @@ -79,51 +476,195 @@ export class CustomerOrderRequest { return this; } + withOrderNumberIsNot(val: string): this { + this.filters.push({ "orderNumber": { "$ne": val } }); + return this; + } + withOrderNumberIn(...vals: string[]): this { this.filters.push({ "orderNumber": { "$in": vals } }); return this; } - withOrderDateIs(val: any): this { + withOrderNumberNotIn(...vals: string[]): this { + this.filters.push({ "orderNumber": { "$notIn": vals } }); + return this; + } + + withOrderNumberGreaterThan(val: string): this { + this.filters.push({ "orderNumber": { "$gt": val } }); + return this; + } + + withOrderNumberGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "orderNumber": { "$gte": val } }); + return this; + } + + withOrderNumberLessThan(val: string): this { + this.filters.push({ "orderNumber": { "$lt": val } }); + return this; + } + + withOrderNumberLessThanOrEqualTo(val: string): this { + this.filters.push({ "orderNumber": { "$lte": val } }); + return this; + } + + withOrderNumberBetween(lower: string, upper: string): this { + this.filters.push({ "orderNumber": { "$between": [lower, upper] } }); + return this; + } + + withOrderNumberIsKnown(): this { + this.filters.push({ "orderNumber": { "$isNull": false } }); + return this; + } + + withOrderNumberIsUnknown(): this { + this.filters.push({ "orderNumber": { "$isNull": true } }); + return this; + } + withOrderNumberNotContaining(val: string): this { + this.filters.push({ "orderNumber": { "$notContains": val } }); + return this; + } + + withOrderNumberStartingWith(val: string): this { + this.filters.push({ "orderNumber": { "$startsWith": val } }); + return this; + } + + withOrderNumberNotStartingWith(val: string): this { + this.filters.push({ "orderNumber": { "$notStartsWith": val } }); + return this; + } + + withOrderNumberEndingWith(val: string): this { + this.filters.push({ "orderNumber": { "$endsWith": val } }); + return this; + } + + withOrderNumberNotEndingWith(val: string): this { + this.filters.push({ "orderNumber": { "$notEndsWith": val } }); + return this; + } + + withOrderNumberSoundingLike(val: string): this { + this.filters.push({ "orderNumber": { "$soundLike": val } }); + return this; + } + + withOrderDateIs(val: string): this { this.filters.push({ "orderDate": { "$eq": val } }); return this; } - withOrderDateIn(...vals: any[]): this { + withOrderDateIsNot(val: string): this { + this.filters.push({ "orderDate": { "$ne": val } }); + return this; + } + + withOrderDateIn(...vals: string[]): this { this.filters.push({ "orderDate": { "$in": vals } }); return this; } - withOrderDateGreaterThanOrEqualTo(val: any): this { + withOrderDateNotIn(...vals: string[]): this { + this.filters.push({ "orderDate": { "$notIn": vals } }); + return this; + } + + withOrderDateGreaterThan(val: string): this { + this.filters.push({ "orderDate": { "$gt": val } }); + return this; + } + + withOrderDateGreaterThanOrEqualTo(val: string): this { this.filters.push({ "orderDate": { "$gte": val } }); return this; } - withOrderDateLessThanOrEqualTo(val: any): this { + withOrderDateLessThan(val: string): this { + this.filters.push({ "orderDate": { "$lt": val } }); + return this; + } + + withOrderDateLessThanOrEqualTo(val: string): this { this.filters.push({ "orderDate": { "$lte": val } }); return this; } - withTotalAmountIs(val: any): this { + withOrderDateBetween(lower: string, upper: string): this { + this.filters.push({ "orderDate": { "$between": [lower, upper] } }); + return this; + } + + withOrderDateIsKnown(): this { + this.filters.push({ "orderDate": { "$isNull": false } }); + return this; + } + + withOrderDateIsUnknown(): this { + this.filters.push({ "orderDate": { "$isNull": true } }); + return this; + } + + withTotalAmountIs(val: Decimal): this { this.filters.push({ "totalAmount": { "$eq": val } }); return this; } - withTotalAmountIn(...vals: any[]): this { + withTotalAmountIsNot(val: Decimal): this { + this.filters.push({ "totalAmount": { "$ne": val } }); + return this; + } + + withTotalAmountIn(...vals: Decimal[]): this { this.filters.push({ "totalAmount": { "$in": vals } }); return this; } - withTotalAmountGreaterThanOrEqualTo(val: any): this { + withTotalAmountNotIn(...vals: Decimal[]): this { + this.filters.push({ "totalAmount": { "$notIn": vals } }); + return this; + } + + withTotalAmountGreaterThan(val: Decimal): this { + this.filters.push({ "totalAmount": { "$gt": val } }); + return this; + } + + withTotalAmountGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "totalAmount": { "$gte": val } }); return this; } - withTotalAmountLessThanOrEqualTo(val: any): this { + withTotalAmountLessThan(val: Decimal): this { + this.filters.push({ "totalAmount": { "$lt": val } }); + return this; + } + + withTotalAmountLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "totalAmount": { "$lte": val } }); return this; } + withTotalAmountBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "totalAmount": { "$between": [lower, upper] } }); + return this; + } + + withTotalAmountIsKnown(): this { + this.filters.push({ "totalAmount": { "$isNull": false } }); + return this; + } + + withTotalAmountIsUnknown(): this { + this.filters.push({ "totalAmount": { "$isNull": true } }); + return this; + } + filterByStatus(val: any): this { this.filters.push({ "status": { "$eq": val } }); return this; @@ -134,6 +675,24 @@ export class CustomerOrderRequest { return this; } + withStatusIsKnown(): this { + this.filters.push({ "status": { "$isNull": false } }); + return this; + } + + withStatusIsUnknown(): this { + this.filters.push({ "status": { "$isNull": true } }); + return this; + } + withStatusIsPending(): this { + this.filters.push({ "status": { "$eq": "1001" } }); + return this; + } + withStatusIsConfirmed(): this { + this.filters.push({ "status": { "$eq": "1002" } }); + return this; + } + filterByCustomer(val: any): this { this.filters.push({ "customer": { "$eq": val } }); return this; @@ -144,6 +703,16 @@ export class CustomerOrderRequest { return this; } + withCustomerIsKnown(): this { + this.filters.push({ "customer": { "$isNull": false } }); + return this; + } + + withCustomerIsUnknown(): this { + this.filters.push({ "customer": { "$isNull": true } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -154,66 +723,181 @@ export class CustomerOrderRequest { return this; } - withCreateTimeIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withUpdateTimeIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -291,11 +975,15 @@ export class CustomerOrderRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -371,7 +1059,7 @@ export class CustomerOrderRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByOrderNumber(): this { @@ -380,7 +1068,7 @@ export class CustomerOrderRequest { } groupByOrderNumberAs(retName: string): this { - this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively + this.query.groupBy("orderNumber", retName); return this; } groupByOrderDate(): this { @@ -389,7 +1077,7 @@ export class CustomerOrderRequest { } groupByOrderDateAs(retName: string): this { - this.query.groupBy("orderDate"); // In TS we don't alias group by yet natively + this.query.groupBy("orderDate", retName); return this; } groupByTotalAmount(): this { @@ -398,7 +1086,7 @@ export class CustomerOrderRequest { } groupByTotalAmountAs(retName: string): this { - this.query.groupBy("totalAmount"); // In TS we don't alias group by yet natively + this.query.groupBy("totalAmount", retName); return this; } groupByStatus(): this { @@ -407,7 +1095,7 @@ export class CustomerOrderRequest { } groupByStatusAs(retName: string): this { - this.query.groupBy("status"); // In TS we don't alias group by yet natively + this.query.groupBy("status", retName); return this; } groupByCustomer(): this { @@ -416,7 +1104,7 @@ export class CustomerOrderRequest { } groupByCustomerAs(retName: string): this { - this.query.groupBy("customer"); // In TS we don't alias group by yet natively + this.query.groupBy("customer", retName); return this; } groupByCommercePlatform(): this { @@ -425,7 +1113,7 @@ export class CustomerOrderRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByCreateTime(): this { @@ -434,7 +1122,7 @@ export class CustomerOrderRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -443,7 +1131,7 @@ export class CustomerOrderRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -452,74 +1140,172 @@ export class CustomerOrderRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByStatusAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "STATUS_PROPERTY", request); + facetByStatusAs( + facetName: string, + request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "status", request, includeAllFacets, + { kind: "facet", method: "facetByStatusAs", relation: "status", alias: facetName }); return this; } - facetByCustomerAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "CUSTOMER_PROPERTY", request); + facetByCustomerAs( + facetName: string, + request: { readonly entityName: "Customer"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "customer", request, includeAllFacets, + { kind: "facet", method: "facetByCustomerAs", relation: "customer", alias: facetName }); return this; } - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof CustomerOrder + ? row + : CustomerOrder.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof CustomerOrder + ? row + : CustomerOrder.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof CustomerOrder + ? entity + : CustomerOrder.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableCustomerOrderRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): CustomerOrder { - return new CustomerOrder(); + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return CustomerOrder.teaqlCreate(context); } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); } - async executeForOne(ctx: UserContext): Promise { + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts index fe04568bf9119f460f93b6da39420aee5ba3c3e1..b5e094a857af4a84a874fbdfe7cd7724f5817dea 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Customer } from '../models/Customer'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class CustomerRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("Customer"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "Customer" { + return "Customer"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class CustomerRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableCustomerRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableCustomerRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,34 +97,320 @@ export class CustomerRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("customerOrderList", request.toQuery()); + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "email", "commercePlatform", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectEmail(): this { + this.query.select(["email"]); + return this; + } + + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "customerOrderList", request.toQuery(), "id", "customer", true, + { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); + return this; + } + + haveCustomerOrders(): this { + return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + haveNoCustomerOrders(): this { + return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "customer", + }, + }, + }); + return this; + } + + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "customer", + }, + }, + }); + return this; + } + + countCustomerOrders(): this { + return this.countCustomerOrdersAs("countCustomerOrders"); + } + + countCustomerOrdersAs(alias: string): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; + return this; + } + + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "relation-count", method: "countCustomerOrdersWith", relation: "customerOrderList", alias }); + return this; + } + + minTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.minTotalAmountOfCustomerOrdersAs( + "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "minTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + maxTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.maxTotalAmountOfCustomerOrdersAs( + "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "maxTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sumTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sumTotalAmountOfCustomerOrdersAs( + "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sumTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + avgTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.avgTotalAmountOfCustomerOrdersAs( + "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "avgTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + standardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.standardDeviationTotalAmountOfCustomerOrdersAs( + "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "standardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs( + "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sampleVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceTotalAmountOfCustomerOrdersAs( + "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + samplePopulationVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs( + "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withNameContaining(val: string): this { this.filters.push({ "name": { "$contains": val } }); return this; @@ -79,11 +421,85 @@ export class CustomerRequest { return this; } + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + withEmailContaining(val: string): this { this.filters.push({ "email": { "$contains": val } }); return this; @@ -94,11 +510,85 @@ export class CustomerRequest { return this; } + withEmailIsNot(val: string): this { + this.filters.push({ "email": { "$ne": val } }); + return this; + } + withEmailIn(...vals: string[]): this { this.filters.push({ "email": { "$in": vals } }); return this; } + withEmailNotIn(...vals: string[]): this { + this.filters.push({ "email": { "$notIn": vals } }); + return this; + } + + withEmailGreaterThan(val: string): this { + this.filters.push({ "email": { "$gt": val } }); + return this; + } + + withEmailGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "email": { "$gte": val } }); + return this; + } + + withEmailLessThan(val: string): this { + this.filters.push({ "email": { "$lt": val } }); + return this; + } + + withEmailLessThanOrEqualTo(val: string): this { + this.filters.push({ "email": { "$lte": val } }); + return this; + } + + withEmailBetween(lower: string, upper: string): this { + this.filters.push({ "email": { "$between": [lower, upper] } }); + return this; + } + + withEmailIsKnown(): this { + this.filters.push({ "email": { "$isNull": false } }); + return this; + } + + withEmailIsUnknown(): this { + this.filters.push({ "email": { "$isNull": true } }); + return this; + } + withEmailNotContaining(val: string): this { + this.filters.push({ "email": { "$notContains": val } }); + return this; + } + + withEmailStartingWith(val: string): this { + this.filters.push({ "email": { "$startsWith": val } }); + return this; + } + + withEmailNotStartingWith(val: string): this { + this.filters.push({ "email": { "$notStartsWith": val } }); + return this; + } + + withEmailEndingWith(val: string): this { + this.filters.push({ "email": { "$endsWith": val } }); + return this; + } + + withEmailNotEndingWith(val: string): this { + this.filters.push({ "email": { "$notEndsWith": val } }); + return this; + } + + withEmailSoundingLike(val: string): this { + this.filters.push({ "email": { "$soundLike": val } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -109,66 +599,181 @@ export class CustomerRequest { return this; } - withCreateTimeIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withUpdateTimeIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -234,11 +839,15 @@ export class CustomerRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -250,7 +859,7 @@ export class CustomerRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -259,7 +868,7 @@ export class CustomerRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByEmail(): this { @@ -268,7 +877,7 @@ export class CustomerRequest { } groupByEmailAs(retName: string): this { - this.query.groupBy("email"); // In TS we don't alias group by yet natively + this.query.groupBy("email", retName); return this; } groupByCommercePlatform(): this { @@ -277,7 +886,7 @@ export class CustomerRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByCreateTime(): this { @@ -286,7 +895,7 @@ export class CustomerRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -295,7 +904,7 @@ export class CustomerRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -304,64 +913,152 @@ export class CustomerRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Customer + ? row + : Customer.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Customer + ? row + : Customer.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Customer + ? entity + : Customer.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableCustomerRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): Customer { - return new Customer(); + comment(c: string): this { + this.addComment(c); + return this; } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Customer.teaqlCreate(context); } - async executeForOne(ctx: UserContext): Promise { + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts index 724e9b3fbc95d1484de9bd66ed17c84b96632c19..28ceca6cdee95dd47cc4dbc38fb10b25a7f000c4 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderLine } from '../models/OrderLine'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class OrderLineRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("OrderLine"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "OrderLine" { + return "OrderLine"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class OrderLineRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableOrderLineRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableOrderLineRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,30 +97,196 @@ export class OrderLineRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "customerOrder", "product", "productName", "sku", "quantity", "commercePlatform", "createTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + + selectProductName(): this { + this.query.select(["productName"]); + return this; + } + + selectSku(): this { + this.query.select(["sku"]); + return this; + } + + selectQuantity(): this { + this.query.select(["quantity"]); + return this; + } + + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.query.select(["customerOrder"]); + this.query.relationQuery( + "customerOrder", request.toQuery(), "customerOrder", "id", false, + { kind: "relation-select", method: "selectCustomerOrderWith", relation: "customerOrder" }); + return this; + } + selectProductWith(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.query.select(["product"]); + this.query.relationQuery( + "product", request.toQuery(), "product", "id", false, + { kind: "relation-select", method: "selectProductWith", relation: "product" }); + return this; + } + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "customerOrder": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "customerOrder": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withProductMatching(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.filters.push({ + "product": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutProductMatching(request: { readonly entityName: "Product"; toQuery(): SelectQuery }): this { + this.filters.push({ + "product": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + - withIdIs(val: any): this { + + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + filterByCustomerOrder(val: any): this { this.filters.push({ "customerOrder": { "$eq": val } }); return this; @@ -75,6 +297,16 @@ export class OrderLineRequest { return this; } + withCustomerOrderIsKnown(): this { + this.filters.push({ "customerOrder": { "$isNull": false } }); + return this; + } + + withCustomerOrderIsUnknown(): this { + this.filters.push({ "customerOrder": { "$isNull": true } }); + return this; + } + filterByProduct(val: any): this { this.filters.push({ "product": { "$eq": val } }); return this; @@ -85,6 +317,16 @@ export class OrderLineRequest { return this; } + withProductIsKnown(): this { + this.filters.push({ "product": { "$isNull": false } }); + return this; + } + + withProductIsUnknown(): this { + this.filters.push({ "product": { "$isNull": true } }); + return this; + } + withProductNameContaining(val: string): this { this.filters.push({ "productName": { "$contains": val } }); return this; @@ -95,11 +337,85 @@ export class OrderLineRequest { return this; } + withProductNameIsNot(val: string): this { + this.filters.push({ "productName": { "$ne": val } }); + return this; + } + withProductNameIn(...vals: string[]): this { this.filters.push({ "productName": { "$in": vals } }); return this; } + withProductNameNotIn(...vals: string[]): this { + this.filters.push({ "productName": { "$notIn": vals } }); + return this; + } + + withProductNameGreaterThan(val: string): this { + this.filters.push({ "productName": { "$gt": val } }); + return this; + } + + withProductNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "productName": { "$gte": val } }); + return this; + } + + withProductNameLessThan(val: string): this { + this.filters.push({ "productName": { "$lt": val } }); + return this; + } + + withProductNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "productName": { "$lte": val } }); + return this; + } + + withProductNameBetween(lower: string, upper: string): this { + this.filters.push({ "productName": { "$between": [lower, upper] } }); + return this; + } + + withProductNameIsKnown(): this { + this.filters.push({ "productName": { "$isNull": false } }); + return this; + } + + withProductNameIsUnknown(): this { + this.filters.push({ "productName": { "$isNull": true } }); + return this; + } + withProductNameNotContaining(val: string): this { + this.filters.push({ "productName": { "$notContains": val } }); + return this; + } + + withProductNameStartingWith(val: string): this { + this.filters.push({ "productName": { "$startsWith": val } }); + return this; + } + + withProductNameNotStartingWith(val: string): this { + this.filters.push({ "productName": { "$notStartsWith": val } }); + return this; + } + + withProductNameEndingWith(val: string): this { + this.filters.push({ "productName": { "$endsWith": val } }); + return this; + } + + withProductNameNotEndingWith(val: string): this { + this.filters.push({ "productName": { "$notEndsWith": val } }); + return this; + } + + withProductNameSoundingLike(val: string): this { + this.filters.push({ "productName": { "$soundLike": val } }); + return this; + } + withSkuContaining(val: string): this { this.filters.push({ "sku": { "$contains": val } }); return this; @@ -110,31 +426,140 @@ export class OrderLineRequest { return this; } + withSkuIsNot(val: string): this { + this.filters.push({ "sku": { "$ne": val } }); + return this; + } + withSkuIn(...vals: string[]): this { this.filters.push({ "sku": { "$in": vals } }); return this; } - withQuantityIs(val: any): this { + withSkuNotIn(...vals: string[]): this { + this.filters.push({ "sku": { "$notIn": vals } }); + return this; + } + + withSkuGreaterThan(val: string): this { + this.filters.push({ "sku": { "$gt": val } }); + return this; + } + + withSkuGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "sku": { "$gte": val } }); + return this; + } + + withSkuLessThan(val: string): this { + this.filters.push({ "sku": { "$lt": val } }); + return this; + } + + withSkuLessThanOrEqualTo(val: string): this { + this.filters.push({ "sku": { "$lte": val } }); + return this; + } + + withSkuBetween(lower: string, upper: string): this { + this.filters.push({ "sku": { "$between": [lower, upper] } }); + return this; + } + + withSkuIsKnown(): this { + this.filters.push({ "sku": { "$isNull": false } }); + return this; + } + + withSkuIsUnknown(): this { + this.filters.push({ "sku": { "$isNull": true } }); + return this; + } + withSkuNotContaining(val: string): this { + this.filters.push({ "sku": { "$notContains": val } }); + return this; + } + + withSkuStartingWith(val: string): this { + this.filters.push({ "sku": { "$startsWith": val } }); + return this; + } + + withSkuNotStartingWith(val: string): this { + this.filters.push({ "sku": { "$notStartsWith": val } }); + return this; + } + + withSkuEndingWith(val: string): this { + this.filters.push({ "sku": { "$endsWith": val } }); + return this; + } + + withSkuNotEndingWith(val: string): this { + this.filters.push({ "sku": { "$notEndsWith": val } }); + return this; + } + + withSkuSoundingLike(val: string): this { + this.filters.push({ "sku": { "$soundLike": val } }); + return this; + } + + withQuantityIs(val: number): this { this.filters.push({ "quantity": { "$eq": val } }); return this; } - withQuantityIn(...vals: any[]): this { + withQuantityIsNot(val: number): this { + this.filters.push({ "quantity": { "$ne": val } }); + return this; + } + + withQuantityIn(...vals: number[]): this { this.filters.push({ "quantity": { "$in": vals } }); return this; } - withQuantityGreaterThanOrEqualTo(val: any): this { + withQuantityNotIn(...vals: number[]): this { + this.filters.push({ "quantity": { "$notIn": vals } }); + return this; + } + + withQuantityGreaterThan(val: number): this { + this.filters.push({ "quantity": { "$gt": val } }); + return this; + } + + withQuantityGreaterThanOrEqualTo(val: number): this { this.filters.push({ "quantity": { "$gte": val } }); return this; } - withQuantityLessThanOrEqualTo(val: any): this { + withQuantityLessThan(val: number): this { + this.filters.push({ "quantity": { "$lt": val } }); + return this; + } + + withQuantityLessThanOrEqualTo(val: number): this { this.filters.push({ "quantity": { "$lte": val } }); return this; } + withQuantityBetween(lower: number, upper: number): this { + this.filters.push({ "quantity": { "$between": [lower, upper] } }); + return this; + } + + withQuantityIsKnown(): this { + this.filters.push({ "quantity": { "$isNull": false } }); + return this; + } + + withQuantityIsUnknown(): this { + this.filters.push({ "quantity": { "$isNull": true } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -145,46 +570,126 @@ export class OrderLineRequest { return this; } - withCreateTimeIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -252,11 +757,15 @@ export class OrderLineRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -332,7 +841,7 @@ export class OrderLineRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomerOrder(): this { @@ -341,7 +850,7 @@ export class OrderLineRequest { } groupByCustomerOrderAs(retName: string): this { - this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("customerOrder", retName); return this; } groupByProduct(): this { @@ -350,7 +859,7 @@ export class OrderLineRequest { } groupByProductAs(retName: string): this { - this.query.groupBy("product"); // In TS we don't alias group by yet natively + this.query.groupBy("product", retName); return this; } groupByProductName(): this { @@ -359,7 +868,7 @@ export class OrderLineRequest { } groupByProductNameAs(retName: string): this { - this.query.groupBy("productName"); // In TS we don't alias group by yet natively + this.query.groupBy("productName", retName); return this; } groupBySku(): this { @@ -368,7 +877,7 @@ export class OrderLineRequest { } groupBySkuAs(retName: string): this { - this.query.groupBy("sku"); // In TS we don't alias group by yet natively + this.query.groupBy("sku", retName); return this; } groupByQuantity(): this { @@ -377,7 +886,7 @@ export class OrderLineRequest { } groupByQuantityAs(retName: string): this { - this.query.groupBy("quantity"); // In TS we don't alias group by yet natively + this.query.groupBy("quantity", retName); return this; } groupByCommercePlatform(): this { @@ -386,7 +895,7 @@ export class OrderLineRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByCreateTime(): this { @@ -395,7 +904,7 @@ export class OrderLineRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByVersion(): this { @@ -404,74 +913,172 @@ export class OrderLineRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByCustomerOrderAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "CUSTOMER_ORDER_PROPERTY", request); + facetByCustomerOrderAs( + facetName: string, + request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "customerOrder", request, includeAllFacets, + { kind: "facet", method: "facetByCustomerOrderAs", relation: "customerOrder", alias: facetName }); return this; } - facetByProductAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "PRODUCT_PROPERTY", request); + facetByProductAs( + facetName: string, + request: { readonly entityName: "Product"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "product", request, includeAllFacets, + { kind: "facet", method: "facetByProductAs", relation: "product", alias: facetName }); return this; } - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof OrderLine + ? row + : OrderLine.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof OrderLine + ? row + : OrderLine.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof OrderLine + ? entity + : OrderLine.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableOrderLineRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): OrderLine { - return new OrderLine(); + comment(c: string): this { + this.addComment(c); + return this; } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderLine.teaqlCreate(context); } - async executeForOne(ctx: UserContext): Promise { + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts index fa8f517296ca28d183b6c047ed4067438fe3aaf4..e8d210f1bc962a50049b1d519296e455af1d7e82 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderSearchPreset } from '../models/OrderSearchPreset'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class OrderSearchPresetRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("OrderSearchPreset"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "OrderSearchPreset" { + return "OrderSearchPreset"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class OrderSearchPresetRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableOrderSearchPresetRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableOrderSearchPresetRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,30 +97,156 @@ export class OrderSearchPresetRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "filterJson", "requestId", "ownerUserId", "commercePlatform", "createTime", "updateTime", "version"]); + return this; + } - withIdIs(val: any): this { + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectFilterJson(): this { + this.query.select(["filterJson"]); + return this; + } + + selectRequestId(): this { + this.query.select(["requestId"]); + return this; + } + + selectOwnerUserId(): this { + this.query.select(["ownerUserId"]); + return this; + } + + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withNameContaining(val: string): this { this.filters.push({ "name": { "$contains": val } }); return this; @@ -75,11 +257,85 @@ export class OrderSearchPresetRequest { return this; } + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + withFilterJsonContaining(val: string): this { this.filters.push({ "filterJson": { "$contains": val } }); return this; @@ -90,11 +346,85 @@ export class OrderSearchPresetRequest { return this; } + withFilterJsonIsNot(val: string): this { + this.filters.push({ "filterJson": { "$ne": val } }); + return this; + } + withFilterJsonIn(...vals: string[]): this { this.filters.push({ "filterJson": { "$in": vals } }); return this; } + withFilterJsonNotIn(...vals: string[]): this { + this.filters.push({ "filterJson": { "$notIn": vals } }); + return this; + } + + withFilterJsonGreaterThan(val: string): this { + this.filters.push({ "filterJson": { "$gt": val } }); + return this; + } + + withFilterJsonGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "filterJson": { "$gte": val } }); + return this; + } + + withFilterJsonLessThan(val: string): this { + this.filters.push({ "filterJson": { "$lt": val } }); + return this; + } + + withFilterJsonLessThanOrEqualTo(val: string): this { + this.filters.push({ "filterJson": { "$lte": val } }); + return this; + } + + withFilterJsonBetween(lower: string, upper: string): this { + this.filters.push({ "filterJson": { "$between": [lower, upper] } }); + return this; + } + + withFilterJsonIsKnown(): this { + this.filters.push({ "filterJson": { "$isNull": false } }); + return this; + } + + withFilterJsonIsUnknown(): this { + this.filters.push({ "filterJson": { "$isNull": true } }); + return this; + } + withFilterJsonNotContaining(val: string): this { + this.filters.push({ "filterJson": { "$notContains": val } }); + return this; + } + + withFilterJsonStartingWith(val: string): this { + this.filters.push({ "filterJson": { "$startsWith": val } }); + return this; + } + + withFilterJsonNotStartingWith(val: string): this { + this.filters.push({ "filterJson": { "$notStartsWith": val } }); + return this; + } + + withFilterJsonEndingWith(val: string): this { + this.filters.push({ "filterJson": { "$endsWith": val } }); + return this; + } + + withFilterJsonNotEndingWith(val: string): this { + this.filters.push({ "filterJson": { "$notEndsWith": val } }); + return this; + } + + withFilterJsonSoundingLike(val: string): this { + this.filters.push({ "filterJson": { "$soundLike": val } }); + return this; + } + withRequestIdContaining(val: string): this { this.filters.push({ "requestId": { "$contains": val } }); return this; @@ -105,11 +435,85 @@ export class OrderSearchPresetRequest { return this; } + withRequestIdIsNot(val: string): this { + this.filters.push({ "requestId": { "$ne": val } }); + return this; + } + withRequestIdIn(...vals: string[]): this { this.filters.push({ "requestId": { "$in": vals } }); return this; } + withRequestIdNotIn(...vals: string[]): this { + this.filters.push({ "requestId": { "$notIn": vals } }); + return this; + } + + withRequestIdGreaterThan(val: string): this { + this.filters.push({ "requestId": { "$gt": val } }); + return this; + } + + withRequestIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requestId": { "$gte": val } }); + return this; + } + + withRequestIdLessThan(val: string): this { + this.filters.push({ "requestId": { "$lt": val } }); + return this; + } + + withRequestIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "requestId": { "$lte": val } }); + return this; + } + + withRequestIdBetween(lower: string, upper: string): this { + this.filters.push({ "requestId": { "$between": [lower, upper] } }); + return this; + } + + withRequestIdIsKnown(): this { + this.filters.push({ "requestId": { "$isNull": false } }); + return this; + } + + withRequestIdIsUnknown(): this { + this.filters.push({ "requestId": { "$isNull": true } }); + return this; + } + withRequestIdNotContaining(val: string): this { + this.filters.push({ "requestId": { "$notContains": val } }); + return this; + } + + withRequestIdStartingWith(val: string): this { + this.filters.push({ "requestId": { "$startsWith": val } }); + return this; + } + + withRequestIdNotStartingWith(val: string): this { + this.filters.push({ "requestId": { "$notStartsWith": val } }); + return this; + } + + withRequestIdEndingWith(val: string): this { + this.filters.push({ "requestId": { "$endsWith": val } }); + return this; + } + + withRequestIdNotEndingWith(val: string): this { + this.filters.push({ "requestId": { "$notEndsWith": val } }); + return this; + } + + withRequestIdSoundingLike(val: string): this { + this.filters.push({ "requestId": { "$soundLike": val } }); + return this; + } + withOwnerUserIdContaining(val: string): this { this.filters.push({ "ownerUserId": { "$contains": val } }); return this; @@ -120,11 +524,85 @@ export class OrderSearchPresetRequest { return this; } + withOwnerUserIdIsNot(val: string): this { + this.filters.push({ "ownerUserId": { "$ne": val } }); + return this; + } + withOwnerUserIdIn(...vals: string[]): this { this.filters.push({ "ownerUserId": { "$in": vals } }); return this; } + withOwnerUserIdNotIn(...vals: string[]): this { + this.filters.push({ "ownerUserId": { "$notIn": vals } }); + return this; + } + + withOwnerUserIdGreaterThan(val: string): this { + this.filters.push({ "ownerUserId": { "$gt": val } }); + return this; + } + + withOwnerUserIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "ownerUserId": { "$gte": val } }); + return this; + } + + withOwnerUserIdLessThan(val: string): this { + this.filters.push({ "ownerUserId": { "$lt": val } }); + return this; + } + + withOwnerUserIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "ownerUserId": { "$lte": val } }); + return this; + } + + withOwnerUserIdBetween(lower: string, upper: string): this { + this.filters.push({ "ownerUserId": { "$between": [lower, upper] } }); + return this; + } + + withOwnerUserIdIsKnown(): this { + this.filters.push({ "ownerUserId": { "$isNull": false } }); + return this; + } + + withOwnerUserIdIsUnknown(): this { + this.filters.push({ "ownerUserId": { "$isNull": true } }); + return this; + } + withOwnerUserIdNotContaining(val: string): this { + this.filters.push({ "ownerUserId": { "$notContains": val } }); + return this; + } + + withOwnerUserIdStartingWith(val: string): this { + this.filters.push({ "ownerUserId": { "$startsWith": val } }); + return this; + } + + withOwnerUserIdNotStartingWith(val: string): this { + this.filters.push({ "ownerUserId": { "$notStartsWith": val } }); + return this; + } + + withOwnerUserIdEndingWith(val: string): this { + this.filters.push({ "ownerUserId": { "$endsWith": val } }); + return this; + } + + withOwnerUserIdNotEndingWith(val: string): this { + this.filters.push({ "ownerUserId": { "$notEndsWith": val } }); + return this; + } + + withOwnerUserIdSoundingLike(val: string): this { + this.filters.push({ "ownerUserId": { "$soundLike": val } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -135,66 +613,181 @@ export class OrderSearchPresetRequest { return this; } - withCreateTimeIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withUpdateTimeIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -280,11 +873,15 @@ export class OrderSearchPresetRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -296,7 +893,7 @@ export class OrderSearchPresetRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -305,7 +902,7 @@ export class OrderSearchPresetRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByFilterJson(): this { @@ -314,7 +911,7 @@ export class OrderSearchPresetRequest { } groupByFilterJsonAs(retName: string): this { - this.query.groupBy("filterJson"); // In TS we don't alias group by yet natively + this.query.groupBy("filterJson", retName); return this; } groupByRequestId(): this { @@ -323,7 +920,7 @@ export class OrderSearchPresetRequest { } groupByRequestIdAs(retName: string): this { - this.query.groupBy("requestId"); // In TS we don't alias group by yet natively + this.query.groupBy("requestId", retName); return this; } groupByOwnerUserId(): this { @@ -332,7 +929,7 @@ export class OrderSearchPresetRequest { } groupByOwnerUserIdAs(retName: string): this { - this.query.groupBy("ownerUserId"); // In TS we don't alias group by yet natively + this.query.groupBy("ownerUserId", retName); return this; } groupByCommercePlatform(): this { @@ -341,7 +938,7 @@ export class OrderSearchPresetRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByCreateTime(): this { @@ -350,7 +947,7 @@ export class OrderSearchPresetRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -359,7 +956,7 @@ export class OrderSearchPresetRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -368,64 +965,152 @@ export class OrderSearchPresetRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof OrderSearchPreset + ? row + : OrderSearchPreset.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof OrderSearchPreset + ? row + : OrderSearchPreset.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof OrderSearchPreset + ? entity + : OrderSearchPreset.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableOrderSearchPresetRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): OrderSearchPreset { - return new OrderSearchPreset(); + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderSearchPreset.teaqlCreate(context); } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); } - async executeForOne(ctx: UserContext): Promise { + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts index 7061432bf69595836f3390c3172fc968e775ae1a..5c5b2dd7de47189e7c3c9484ce7976beb127a9f2 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderStatus } from '../models/OrderStatus'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class OrderStatusRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("OrderStatus"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "OrderStatus" { + return "OrderStatus"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class OrderStatusRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableOrderStatusRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableOrderStatusRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,34 +97,320 @@ export class OrderStatusRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("customerOrderList", request.toQuery()); + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "code", "color", "displayOrder", "commercePlatform", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCode(): this { + this.query.select(["code"]); + return this; + } + + selectColor(): this { + this.query.select(["color"]); + return this; + } + + selectDisplayOrder(): this { + this.query.select(["displayOrder"]); + return this; + } + + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "customerOrderList", request.toQuery(), "id", "status", true, + { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); + return this; + } + + haveCustomerOrders(): this { + return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + haveNoCustomerOrders(): this { + return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", + toQuery: () => new SelectQuery("CustomerOrder"), + }); + } + + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "status", + }, + }, + }); + return this; + } + + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "status", + }, + }, + }); + return this; + } + + countCustomerOrders(): this { + return this.countCustomerOrdersAs("countCustomerOrders"); + } + + countCustomerOrdersAs(alias: string): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; + return this; + } + + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "relation-count", method: "countCustomerOrdersWith", relation: "customerOrderList", alias }); + return this; + } + + minTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.minTotalAmountOfCustomerOrdersAs( + "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "minTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + maxTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.maxTotalAmountOfCustomerOrdersAs( + "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "maxTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sumTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sumTotalAmountOfCustomerOrdersAs( + "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sumTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); return this; } + avgTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.avgTotalAmountOfCustomerOrdersAs( + "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "avgTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + standardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.standardDeviationTotalAmountOfCustomerOrdersAs( + "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } - withIdIs(val: any): this { + standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "standardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs( + "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + sampleVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceTotalAmountOfCustomerOrdersAs( + "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + samplePopulationVarianceTotalAmountOfCustomerOrders(): this { + const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs( + "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); + } + + samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "totalAmount", alias); + this.query.relationAggregate("customerOrderList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceTotalAmountOfCustomerOrdersAs", relation: "customerOrderList", alias }); + return this; + } + + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withNameContaining(val: string): this { this.filters.push({ "name": { "$contains": val } }); return this; @@ -79,11 +421,85 @@ export class OrderStatusRequest { return this; } + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + withCodeContaining(val: string): this { this.filters.push({ "code": { "$contains": val } }); return this; @@ -94,11 +510,85 @@ export class OrderStatusRequest { return this; } + withCodeIsNot(val: string): this { + this.filters.push({ "code": { "$ne": val } }); + return this; + } + withCodeIn(...vals: string[]): this { this.filters.push({ "code": { "$in": vals } }); return this; } + withCodeNotIn(...vals: string[]): this { + this.filters.push({ "code": { "$notIn": vals } }); + return this; + } + + withCodeGreaterThan(val: string): this { + this.filters.push({ "code": { "$gt": val } }); + return this; + } + + withCodeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "code": { "$gte": val } }); + return this; + } + + withCodeLessThan(val: string): this { + this.filters.push({ "code": { "$lt": val } }); + return this; + } + + withCodeLessThanOrEqualTo(val: string): this { + this.filters.push({ "code": { "$lte": val } }); + return this; + } + + withCodeBetween(lower: string, upper: string): this { + this.filters.push({ "code": { "$between": [lower, upper] } }); + return this; + } + + withCodeIsKnown(): this { + this.filters.push({ "code": { "$isNull": false } }); + return this; + } + + withCodeIsUnknown(): this { + this.filters.push({ "code": { "$isNull": true } }); + return this; + } + withCodeNotContaining(val: string): this { + this.filters.push({ "code": { "$notContains": val } }); + return this; + } + + withCodeStartingWith(val: string): this { + this.filters.push({ "code": { "$startsWith": val } }); + return this; + } + + withCodeNotStartingWith(val: string): this { + this.filters.push({ "code": { "$notStartsWith": val } }); + return this; + } + + withCodeEndingWith(val: string): this { + this.filters.push({ "code": { "$endsWith": val } }); + return this; + } + + withCodeNotEndingWith(val: string): this { + this.filters.push({ "code": { "$notEndsWith": val } }); + return this; + } + + withCodeSoundingLike(val: string): this { + this.filters.push({ "code": { "$soundLike": val } }); + return this; + } + withColorContaining(val: string): this { this.filters.push({ "color": { "$contains": val } }); return this; @@ -109,31 +599,140 @@ export class OrderStatusRequest { return this; } + withColorIsNot(val: string): this { + this.filters.push({ "color": { "$ne": val } }); + return this; + } + withColorIn(...vals: string[]): this { this.filters.push({ "color": { "$in": vals } }); return this; } - withDisplayOrderIs(val: any): this { + withColorNotIn(...vals: string[]): this { + this.filters.push({ "color": { "$notIn": vals } }); + return this; + } + + withColorGreaterThan(val: string): this { + this.filters.push({ "color": { "$gt": val } }); + return this; + } + + withColorGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "color": { "$gte": val } }); + return this; + } + + withColorLessThan(val: string): this { + this.filters.push({ "color": { "$lt": val } }); + return this; + } + + withColorLessThanOrEqualTo(val: string): this { + this.filters.push({ "color": { "$lte": val } }); + return this; + } + + withColorBetween(lower: string, upper: string): this { + this.filters.push({ "color": { "$between": [lower, upper] } }); + return this; + } + + withColorIsKnown(): this { + this.filters.push({ "color": { "$isNull": false } }); + return this; + } + + withColorIsUnknown(): this { + this.filters.push({ "color": { "$isNull": true } }); + return this; + } + withColorNotContaining(val: string): this { + this.filters.push({ "color": { "$notContains": val } }); + return this; + } + + withColorStartingWith(val: string): this { + this.filters.push({ "color": { "$startsWith": val } }); + return this; + } + + withColorNotStartingWith(val: string): this { + this.filters.push({ "color": { "$notStartsWith": val } }); + return this; + } + + withColorEndingWith(val: string): this { + this.filters.push({ "color": { "$endsWith": val } }); + return this; + } + + withColorNotEndingWith(val: string): this { + this.filters.push({ "color": { "$notEndsWith": val } }); + return this; + } + + withColorSoundingLike(val: string): this { + this.filters.push({ "color": { "$soundLike": val } }); + return this; + } + + withDisplayOrderIs(val: Decimal): this { this.filters.push({ "displayOrder": { "$eq": val } }); return this; } - withDisplayOrderIn(...vals: any[]): this { + withDisplayOrderIsNot(val: Decimal): this { + this.filters.push({ "displayOrder": { "$ne": val } }); + return this; + } + + withDisplayOrderIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$in": vals } }); return this; } - withDisplayOrderGreaterThanOrEqualTo(val: any): this { + withDisplayOrderNotIn(...vals: Decimal[]): this { + this.filters.push({ "displayOrder": { "$notIn": vals } }); + return this; + } + + withDisplayOrderGreaterThan(val: Decimal): this { + this.filters.push({ "displayOrder": { "$gt": val } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$gte": val } }); return this; } - withDisplayOrderLessThanOrEqualTo(val: any): this { + withDisplayOrderLessThan(val: Decimal): this { + this.filters.push({ "displayOrder": { "$lt": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$lte": val } }); return this; } + withDisplayOrderBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); + return this; + } + + withDisplayOrderIsKnown(): this { + this.filters.push({ "displayOrder": { "$isNull": false } }); + return this; + } + + withDisplayOrderIsUnknown(): this { + this.filters.push({ "displayOrder": { "$isNull": true } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -144,26 +743,71 @@ export class OrderStatusRequest { return this; } - withVersionIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -229,11 +873,15 @@ export class OrderStatusRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -309,7 +957,7 @@ export class OrderStatusRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -318,7 +966,7 @@ export class OrderStatusRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCode(): this { @@ -327,7 +975,7 @@ export class OrderStatusRequest { } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } groupByColor(): this { @@ -336,7 +984,7 @@ export class OrderStatusRequest { } groupByColorAs(retName: string): this { - this.query.groupBy("color"); // In TS we don't alias group by yet natively + this.query.groupBy("color", retName); return this; } groupByDisplayOrder(): this { @@ -345,7 +993,7 @@ export class OrderStatusRequest { } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } groupByCommercePlatform(): this { @@ -354,7 +1002,7 @@ export class OrderStatusRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByVersion(): this { @@ -363,64 +1011,152 @@ export class OrderStatusRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof OrderStatus + ? row + : OrderStatus.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof OrderStatus + ? row + : OrderStatus.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof OrderStatus + ? entity + : OrderStatus.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableOrderStatusRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): OrderStatus { - return new OrderStatus(); + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderStatus.teaqlCreate(context); } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); } - async executeForOne(ctx: UserContext): Promise { + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts index 326c9fa4f9b7d8e26e5162fde4582d670ccabd1d..39dbab4aab7c5f41f784de01f1bc43af2f1b7ed9 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts @@ -1,5 +1,8 @@ -import { SelectQuery, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Product } from '../models/Product'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -8,9 +11,22 @@ export class ProductRequest { private filters: any[] = []; private _purpose: string | undefined; private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("Product"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "Product" { + return "Product"; } comment(c: string): this { @@ -19,15 +35,55 @@ export class ProductRequest { return this; } + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + purpose(p: string): ExecutableProductRequest { - if (!this._comment || !this._comment.trim()) { - throw new Error("purpose() requires a non-empty comment() set earlier on the request"); - } this.query.purpose(p); this._purpose = p; return new ExecutableProductRequest( - (ctx) => this.executeForListInternal(ctx), - () => this.limit(1)); + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; } limit(n: number): this { @@ -41,34 +97,325 @@ export class ProductRequest { } toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } return this.query; } - selectOrderLineListWith(request: { toQuery(): SelectQuery }): this { - this.query.relationQuery("orderLineList", request.toQuery()); + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "sku", "imageUrl", "commercePlatform", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectSku(): this { + this.query.select(["sku"]); + return this; + } + + selectImageUrl(): this { + this.query.select(["imageUrl"]); + return this; + } + + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCommercePlatformWith(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["commercePlatform"]); + this.query.relationQuery( + "commercePlatform", request.toQuery(), "commercePlatform", "id", false, + { kind: "relation-select", method: "selectCommercePlatformWith", relation: "commercePlatform" }); + return this; + } + + withCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCommercePlatformMatching(request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "commercePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectOrderLineListWith(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "orderLineList", request.toQuery(), "id", "product", true, + { kind: "relation-select", method: "selectOrderLineListWith", relation: "orderLineList" }); + return this; + } + + haveOrderLines(): this { + return this.withOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + haveNoOrderLines(): this { + return this.withoutOrderLineListMatching({ + entityName: "OrderLine", + toQuery: () => new SelectQuery("OrderLine"), + }); + } + + withOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "product", + }, + }, + }); + return this; + } + + withoutOrderLineListMatching(request: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "product", + }, + }, + }); + return this; + } + + countOrderLines(): this { + return this.countOrderLinesAs("countOrderLines"); + } + + countOrderLinesAs(alias: string): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + this.countOrderLinesWith(alias, { entityName: "OrderLine", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countOrderLinesAs", relation: "orderLineList", alias }; + return this; + } + + countOrderLinesWith(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "relation-count", method: "countOrderLinesWith", relation: "orderLineList", alias }); + return this; + } + + minQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.minQuantityOfOrderLinesAs( + "minOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + minQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "minQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + maxQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.maxQuantityOfOrderLinesAs( + "maxOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + maxQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "maxQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + sumQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sumQuantityOfOrderLinesAs( + "sumOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sumQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sumQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + avgQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.avgQuantityOfOrderLinesAs( + "avgOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + avgQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "avgQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + standardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.standardDeviationQuantityOfOrderLinesAs( + "standardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + standardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "standardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs( + "squareRootOfPopulationStandardDeviationOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + sampleVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceQuantityOfOrderLinesAs( + "sampleVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + sampleVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); + return this; + } + samplePopulationVarianceQuantityOfOrderLines(): this { + const query = new SelectQuery("OrderLine").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceQuantityOfOrderLinesAs( + "samplePopulationVarianceOfQuantityOfOrderLines", { entityName: "OrderLine", toQuery: () => query }); + } + + samplePopulationVarianceQuantityOfOrderLinesAs(alias: string, child: { readonly entityName: "OrderLine"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "quantity", alias); + this.query.relationAggregate("orderLineList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceQuantityOfOrderLinesAs", relation: "orderLineList", alias }); return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + withNameContaining(val: string): this { this.filters.push({ "name": { "$contains": val } }); return this; @@ -79,11 +426,85 @@ export class ProductRequest { return this; } + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + withSkuContaining(val: string): this { this.filters.push({ "sku": { "$contains": val } }); return this; @@ -94,11 +515,85 @@ export class ProductRequest { return this; } + withSkuIsNot(val: string): this { + this.filters.push({ "sku": { "$ne": val } }); + return this; + } + withSkuIn(...vals: string[]): this { this.filters.push({ "sku": { "$in": vals } }); return this; } + withSkuNotIn(...vals: string[]): this { + this.filters.push({ "sku": { "$notIn": vals } }); + return this; + } + + withSkuGreaterThan(val: string): this { + this.filters.push({ "sku": { "$gt": val } }); + return this; + } + + withSkuGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "sku": { "$gte": val } }); + return this; + } + + withSkuLessThan(val: string): this { + this.filters.push({ "sku": { "$lt": val } }); + return this; + } + + withSkuLessThanOrEqualTo(val: string): this { + this.filters.push({ "sku": { "$lte": val } }); + return this; + } + + withSkuBetween(lower: string, upper: string): this { + this.filters.push({ "sku": { "$between": [lower, upper] } }); + return this; + } + + withSkuIsKnown(): this { + this.filters.push({ "sku": { "$isNull": false } }); + return this; + } + + withSkuIsUnknown(): this { + this.filters.push({ "sku": { "$isNull": true } }); + return this; + } + withSkuNotContaining(val: string): this { + this.filters.push({ "sku": { "$notContains": val } }); + return this; + } + + withSkuStartingWith(val: string): this { + this.filters.push({ "sku": { "$startsWith": val } }); + return this; + } + + withSkuNotStartingWith(val: string): this { + this.filters.push({ "sku": { "$notStartsWith": val } }); + return this; + } + + withSkuEndingWith(val: string): this { + this.filters.push({ "sku": { "$endsWith": val } }); + return this; + } + + withSkuNotEndingWith(val: string): this { + this.filters.push({ "sku": { "$notEndsWith": val } }); + return this; + } + + withSkuSoundingLike(val: string): this { + this.filters.push({ "sku": { "$soundLike": val } }); + return this; + } + withImageUrlContaining(val: string): this { this.filters.push({ "imageUrl": { "$contains": val } }); return this; @@ -109,11 +604,85 @@ export class ProductRequest { return this; } + withImageUrlIsNot(val: string): this { + this.filters.push({ "imageUrl": { "$ne": val } }); + return this; + } + withImageUrlIn(...vals: string[]): this { this.filters.push({ "imageUrl": { "$in": vals } }); return this; } + withImageUrlNotIn(...vals: string[]): this { + this.filters.push({ "imageUrl": { "$notIn": vals } }); + return this; + } + + withImageUrlGreaterThan(val: string): this { + this.filters.push({ "imageUrl": { "$gt": val } }); + return this; + } + + withImageUrlGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "imageUrl": { "$gte": val } }); + return this; + } + + withImageUrlLessThan(val: string): this { + this.filters.push({ "imageUrl": { "$lt": val } }); + return this; + } + + withImageUrlLessThanOrEqualTo(val: string): this { + this.filters.push({ "imageUrl": { "$lte": val } }); + return this; + } + + withImageUrlBetween(lower: string, upper: string): this { + this.filters.push({ "imageUrl": { "$between": [lower, upper] } }); + return this; + } + + withImageUrlIsKnown(): this { + this.filters.push({ "imageUrl": { "$isNull": false } }); + return this; + } + + withImageUrlIsUnknown(): this { + this.filters.push({ "imageUrl": { "$isNull": true } }); + return this; + } + withImageUrlNotContaining(val: string): this { + this.filters.push({ "imageUrl": { "$notContains": val } }); + return this; + } + + withImageUrlStartingWith(val: string): this { + this.filters.push({ "imageUrl": { "$startsWith": val } }); + return this; + } + + withImageUrlNotStartingWith(val: string): this { + this.filters.push({ "imageUrl": { "$notStartsWith": val } }); + return this; + } + + withImageUrlEndingWith(val: string): this { + this.filters.push({ "imageUrl": { "$endsWith": val } }); + return this; + } + + withImageUrlNotEndingWith(val: string): this { + this.filters.push({ "imageUrl": { "$notEndsWith": val } }); + return this; + } + + withImageUrlSoundingLike(val: string): this { + this.filters.push({ "imageUrl": { "$soundLike": val } }); + return this; + } + filterByCommercePlatform(val: any): this { this.filters.push({ "commercePlatform": { "$eq": val } }); return this; @@ -124,66 +693,181 @@ export class ProductRequest { return this; } - withCreateTimeIs(val: any): this { + withCommercePlatformIsKnown(): this { + this.filters.push({ "commercePlatform": { "$isNull": false } }); + return this; + } + + withCommercePlatformIsUnknown(): this { + this.filters.push({ "commercePlatform": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withUpdateTimeIs(val: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withVersionIs(val: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + orderByIdAscending(): this { this.query.orderBy("id", "asc"); return this; @@ -259,11 +943,15 @@ export class ProductRequest { // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -275,7 +963,7 @@ export class ProductRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -284,7 +972,7 @@ export class ProductRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupBySku(): this { @@ -293,7 +981,7 @@ export class ProductRequest { } groupBySkuAs(retName: string): this { - this.query.groupBy("sku"); // In TS we don't alias group by yet natively + this.query.groupBy("sku", retName); return this; } groupByImageUrl(): this { @@ -302,7 +990,7 @@ export class ProductRequest { } groupByImageUrlAs(retName: string): this { - this.query.groupBy("imageUrl"); // In TS we don't alias group by yet natively + this.query.groupBy("imageUrl", retName); return this; } groupByCommercePlatform(): this { @@ -311,7 +999,7 @@ export class ProductRequest { } groupByCommercePlatformAs(retName: string): this { - this.query.groupBy("commercePlatform"); // In TS we don't alias group by yet natively + this.query.groupBy("commercePlatform", retName); return this; } groupByCreateTime(): this { @@ -320,7 +1008,7 @@ export class ProductRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -329,7 +1017,7 @@ export class ProductRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -338,64 +1026,152 @@ export class ProductRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- - facetByCommercePlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "COMMERCE_PLATFORM_PROPERTY", request); + facetByCommercePlatformAs( + facetName: string, + request: { readonly entityName: "CommercePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "commercePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByCommercePlatformAs", relation: "commercePlatform", alias: facetName }); return this; } - private async executeForListInternal(ctx: UserContext): Promise { - if (!this._purpose || !this._comment) { - throw new Error("Security audit failure: comment() and purpose() must be called before executeForList()"); - } + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); if (this.filters.length > 0) { this.query.filter({ "$and": this.filters }); } - const service = ctx.requireResource("dataService"); - const data = await service.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Product + ? row + : Product.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (this.filters.length > 0) { - f.query.filter({ "$and": this.filters }); + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Product + ? row + : Product.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Product + ? entity + : Product.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await service.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); } } export class ExecutableProductRequest { constructor( - private readonly execute: (ctx: UserContext) => Promise, + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, ) {} - newEntity(ctx: UserContext): Product { - return new Product(); + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Product.teaqlCreate(context); } - executeForList(ctx: UserContext): Promise { - return this.execute(ctx); + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); } - async executeForOne(ctx: UserContext): Promise { + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { this.limitOne(); - const res = await this.executeForList(ctx); - if (res.data && res.data.length > 0) { - return res.data[0]; - } - return null; + return (await this.executeForList(context))[0]; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/runtime-module.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d0537ed0a07fdcdacf978a14141e382b6cfaadb --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/runtime-module.ts @@ -0,0 +1,336 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "CommercePlatform": Object.freeze({ + entityType: "CommercePlatform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "Customer": Object.freeze({ + entityType: "Customer", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "email": Object.freeze({ canonicalName: "email", wireName: "email", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "OrderStatus": Object.freeze({ + entityType: "OrderStatus", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }), + "color": Object.freeze({ canonicalName: "color", wireName: "color", aliases: Object.freeze([] as string[]) }), + "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "CustomerOrder": Object.freeze({ + entityType: "CustomerOrder", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "order_number": Object.freeze({ canonicalName: "order_number", wireName: "orderNumber", aliases: Object.freeze([] as string[]) }), + "order_date": Object.freeze({ canonicalName: "order_date", wireName: "orderDate", aliases: Object.freeze([] as string[]) }), + "total_amount": Object.freeze({ canonicalName: "total_amount", wireName: "totalAmount", aliases: Object.freeze([] as string[]) }), + "status": Object.freeze({ canonicalName: "status", wireName: "status", aliases: Object.freeze([] as string[]) }), + "customer": Object.freeze({ canonicalName: "customer", wireName: "customer", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "Product": Object.freeze({ + entityType: "Product", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "sku": Object.freeze({ canonicalName: "sku", wireName: "sku", aliases: Object.freeze([] as string[]) }), + "image_url": Object.freeze({ canonicalName: "image_url", wireName: "imageUrl", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "OrderLine": Object.freeze({ + entityType: "OrderLine", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "customer_order": Object.freeze({ canonicalName: "customer_order", wireName: "customerOrder", aliases: Object.freeze([] as string[]) }), + "product": Object.freeze({ canonicalName: "product", wireName: "product", aliases: Object.freeze([] as string[]) }), + "product_name": Object.freeze({ canonicalName: "product_name", wireName: "productName", aliases: Object.freeze([] as string[]) }), + "sku": Object.freeze({ canonicalName: "sku", wireName: "sku", aliases: Object.freeze([] as string[]) }), + "quantity": Object.freeze({ canonicalName: "quantity", wireName: "quantity", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "OrderSearchPreset": Object.freeze({ + entityType: "OrderSearchPreset", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "filter_json": Object.freeze({ canonicalName: "filter_json", wireName: "filterJson", aliases: Object.freeze([] as string[]) }), + "request_id": Object.freeze({ canonicalName: "request_id", wireName: "requestId", aliases: Object.freeze([] as string[]) }), + "owner_user_id": Object.freeze({ canonicalName: "owner_user_id", wireName: "ownerUserId", aliases: Object.freeze([] as string[]) }), + "commerce_platform": Object.freeze({ canonicalName: "commerce_platform", wireName: "commercePlatform", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "CommercePlatform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "CommercePlatform", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "CommercePlatform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "CommercePlatform", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "Customer": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "Customer", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Customer", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Customer", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["email"] === undefined) || mutation.payload["email"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("email") }); + if (mutation.payload["email"] != null && [...String(mutation.payload["email"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("email"), inputValue: mutation.payload["email"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "OrderStatus": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") }); + if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 }); + + if (mutation.payload["color"] != null && [...String(mutation.payload["color"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("color"), inputValue: mutation.payload["color"], systemValue: 100 }); + + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + + }, + }, + "CustomerOrder": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "CustomerOrder", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "CustomerOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "CustomerOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["order_number"] === undefined) || mutation.payload["order_number"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("order_number") }); + if (mutation.payload["order_number"] != null && [...String(mutation.payload["order_number"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("order_number"), inputValue: mutation.payload["order_number"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["order_date"] === undefined) || mutation.payload["order_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("order_date") }); + + if ((mutation.action === "Create" && mutation.payload["total_amount"] === undefined) || mutation.payload["total_amount"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("total_amount") }); + + if ((mutation.action === "Create" && mutation.payload["status"] === undefined) || mutation.payload["status"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("status") }); + + if ((mutation.action === "Create" && mutation.payload["customer"] === undefined) || mutation.payload["customer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("customer") }); + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "Product": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "Product", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Product", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "Product", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["sku"] === undefined) || mutation.payload["sku"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("sku") }); + if (mutation.payload["sku"] != null && [...String(mutation.payload["sku"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("sku"), inputValue: mutation.payload["sku"], systemValue: 100 }); + + if (mutation.payload["image_url"] != null && [...String(mutation.payload["image_url"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("image_url"), inputValue: mutation.payload["image_url"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + }, + "OrderLine": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "OrderLine", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["customer_order"] === undefined) || mutation.payload["customer_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("customer_order") }); + + if ((mutation.action === "Create" && mutation.payload["product"] === undefined) || mutation.payload["product"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("product") }); + + if ((mutation.action === "Create" && mutation.payload["product_name"] === undefined) || mutation.payload["product_name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("product_name") }); + if (mutation.payload["product_name"] != null && [...String(mutation.payload["product_name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("product_name"), inputValue: mutation.payload["product_name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["sku"] === undefined) || mutation.payload["sku"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("sku") }); + if (mutation.payload["sku"] != null && [...String(mutation.payload["sku"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("sku"), inputValue: mutation.payload["sku"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["quantity"] === undefined) || mutation.payload["quantity"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("quantity") }); + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + + }, + }, + "OrderSearchPreset": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "OrderSearchPreset", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "OrderSearchPreset", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "OrderSearchPreset", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["filter_json"] === undefined) || mutation.payload["filter_json"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("filter_json") }); + if (mutation.payload["filter_json"] != null && [...String(mutation.payload["filter_json"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("filter_json"), inputValue: mutation.payload["filter_json"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["request_id"] === undefined) || mutation.payload["request_id"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("request_id") }); + if (mutation.payload["request_id"] != null && [...String(mutation.payload["request_id"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("request_id"), inputValue: mutation.payload["request_id"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["owner_user_id"] === undefined) || mutation.payload["owner_user_id"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("owner_user_id") }); + if (mutation.payload["owner_user_id"] != null && [...String(mutation.payload["owner_user_id"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("owner_user_id"), inputValue: mutation.payload["owner_user_id"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["commerce_platform"] === undefined) || mutation.payload["commerce_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("commerce_platform") }); + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "CommercePlatform", id: "1", values: { "name": "Northwind Demo", "createTime": "createTime()", "updateTime": "updateTime()" } }, + constants: [ + { entity: "OrderStatus", id: "1001", values: { "name": "Pending", "code": "PENDING", "color": "#F59E0B", "displayOrder": decimal("1"), "commercePlatform": "1" } }, + { entity: "OrderStatus", id: "1002", values: { "name": "Confirmed", "code": "CONFIRMED", "color": "#10B981", "displayOrder": decimal("2"), "commercePlatform": "1" } } + ] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts index 93bac3e368900391fcd74f5db5e08d82a99fbb46..fb1ec66c52e4cec076e96bbb89dd2106cfd3581e 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts @@ -3,28 +3,44 @@ import { EntitySchema } from "teaql-ts/sql/core"; export const ENTITY_SCHEMAS: Record = { "CommercePlatform": { table: "commerce_platform_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, - relations: {"customerList": { targetEntity: "Customer", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderStatusList": { targetEntity: "OrderStatus", localKey: "id", foreignKey: "commercePlatform", many: true }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "commercePlatform", many: true }, "productList": { targetEntity: "Product", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderSearchPresetList": { targetEntity: "OrderSearchPreset", localKey: "id", foreignKey: "commercePlatform", many: true }}}, + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"customerList": { targetEntity: "Customer", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderStatusList": { targetEntity: "OrderStatus", localKey: "id", foreignKey: "commercePlatform", many: true }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "commercePlatform", many: true }, "productList": { targetEntity: "Product", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "commercePlatform", many: true }, "orderSearchPresetList": { targetEntity: "OrderSearchPreset", localKey: "id", foreignKey: "commercePlatform", many: true }} +}, "Customer": { table: "customer_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "email": { columnName: "email", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, - relations: {"customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "customer", many: true }}}, + auditMaskFields: ["email"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "email": { columnName: "email", modelName: "email", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "customer", many: true }} +}, "OrderStatus": { table: "order_status_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "code": { columnName: "code", logicalType: "text", decode: "native" }, "color": { columnName: "color", logicalType: "text", decode: "native" }, "displayOrder": { columnName: "display_order", logicalType: "decimal", decode: "number" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, - relations: {"customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }}}, + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: true }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }} +}, "CustomerOrder": { table: "customer_order_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "orderNumber": { columnName: "order_number", logicalType: "text", decode: "native" }, "orderDate": { columnName: "order_date", logicalType: "date", decode: "date" }, "totalAmount": { columnName: "total_amount", logicalType: "decimal", decode: "number" }, "status": { columnName: "status", logicalType: "integer", decode: "string" }, "customer": { columnName: "customer", logicalType: "integer", decode: "string" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, - relations: {"orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "customerOrder", many: true }}}, + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"status": { targetEntity: "OrderStatus", localKey: "status", foreignKey: "id", many: false }, "customer": { targetEntity: "Customer", localKey: "customer", foreignKey: "id", many: false }, "commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }, "orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "customerOrder", many: true }} +}, "Product": { table: "product_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "sku": { columnName: "sku", logicalType: "text", decode: "native" }, "imageUrl": { columnName: "image_url", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}, - relations: {"orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "product", many: true }}}, + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "sku": { columnName: "sku", modelName: "sku", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "imageUrl": { columnName: "image_url", modelName: "image_url", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }, "orderLineList": { targetEntity: "OrderLine", localKey: "id", foreignKey: "product", many: true }} +}, "OrderLine": { table: "order_line_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "customerOrder": { columnName: "customer_order", logicalType: "integer", decode: "string" }, "product": { columnName: "product", logicalType: "integer", decode: "string" }, "productName": { columnName: "product_name", logicalType: "text", decode: "native" }, "sku": { columnName: "sku", logicalType: "text", decode: "native" }, "quantity": { columnName: "quantity", logicalType: "integer", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}}, + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "product": { columnName: "product", modelName: "product", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "sku": { columnName: "sku", modelName: "sku", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"customerOrder": { targetEntity: "CustomerOrder", localKey: "customerOrder", foreignKey: "id", many: false }, "product": { targetEntity: "Product", localKey: "product", foreignKey: "id", many: false }, "commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }} +}, "OrderSearchPreset": { table: "order_search_preset_data", - columns: {"id": { columnName: "id", logicalType: "integer", decode: "string" }, "name": { columnName: "name", logicalType: "text", decode: "native" }, "filterJson": { columnName: "filter_json", logicalType: "text", decode: "native" }, "requestId": { columnName: "request_id", logicalType: "text", decode: "native" }, "ownerUserId": { columnName: "owner_user_id", logicalType: "text", decode: "native" }, "commercePlatform": { columnName: "commerce_platform", logicalType: "integer", decode: "string" }, "createTime": { columnName: "create_time", logicalType: "date", decode: "date" }, "updateTime": { columnName: "update_time", logicalType: "date", decode: "date" }, "version": { columnName: "version", logicalType: "integer", decode: "number" }}} + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "filterJson": { columnName: "filter_json", modelName: "filter_json", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "requestId": { columnName: "request_id", modelName: "request_id", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "ownerUserId": { columnName: "owner_user_id", modelName: "owner_user_id", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "commercePlatform": { columnName: "commerce_platform", modelName: "commerce_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"commercePlatform": { targetEntity: "CommercePlatform", localKey: "commercePlatform", foreignKey: "id", many: false }} +} }; \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts index 77936819272592b22e27ec8c3051b032f182004e..bc3ded598b7e15ab43f23ad385e5ced318843a32 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts @@ -2,30 +2,13 @@ import { SQLiteDriver, SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient } from "teaql-ts/sql/sqlite"; -import { OrderBy, SelectQuery as RuntimeSelectQuery } from "teaql-ts"; -import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; export { SQLiteDriver } from "teaql-ts/sql/sqlite"; export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { constructor(filename: string) { - super(filename, ENTITY_SCHEMAS); + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); } - - async executeQuery(query: any): Promise { - if (typeof query?.prepareForList === "function") { - return super.executeQuery(query); - } - const adapted = new RuntimeSelectQuery(query.entity); - adapted.comment(query._comment ?? "legacy generated order example"); - adapted.purpose(query._purpose ?? "verify local runtime compatibility"); - adapted.filterCondition = query._filters?.length ? { $and: query._filters } : null; - adapted.limitValue = query._limit ?? 0; - adapted.offsetValue = query._offset ?? 0; - adapted.orderItems = (query._orderBy ?? []).map((item: any) => - item.d === "desc" ? OrderBy.desc(item.f) : OrderBy.asc(item.f)); - adapted.groupByItems = query._groupBy ?? []; - adapted.aggregateItems = query._aggregates ?? []; - return super.executeQuery(adapted); - } -} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts index f4c22fb6df95a7276e4b258506a80e711da6c210..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/src/teaql-ts.ts @@ -1,46 +1,88 @@ -export class SelectQuery { - entity: string; - _comment?: string; - _purpose?: string; - _limit?: number; - _offset?: number; - _orderBy: any[] = []; - _groupBy: string[] = []; - _aggregates: any[] = []; - _filters: any[] = []; - facets: any[] = []; - relations: Array<{ name: string; query?: SelectQuery }> = []; - - constructor(entity: string) { - this.entity = entity; - } - comment(c: string) { this._comment = c; } - purpose(p: string) { this._purpose = p; } - limit(n: number) { this._limit = n; } - offset(n: number) { this._offset = n; } - orderBy(f: string, d: string) { this._orderBy.push({f, d}); } - groupBy(f: string) { this._groupBy.push(f); } - countField(f: string, n: string) { this._aggregates.push({func: "count", field: f, retName: n}); } - aggregate(func: string, field: string, retName: string) { this._aggregates.push({func, field, retName}); } - andFilter(expr: any) { this._filters.push(expr); } - filter(expr: any) { this._filters.push(expr); } - relationQuery(name: string, query: SelectQuery) { this.relations.push({ name, query }); } - facetBy(facetName: string, field: string, req: any) { - this.facets.push({ facetName, query: req.query }); +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); } } export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; executeMutation(mutation: any): Promise; executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -51,6 +93,112 @@ export class TeaQLClient implements TeaQLDataService { } } + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -61,57 +209,310 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; - this.persist(); - return { success: true, id: String(id), version: record.version }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Update") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - this.persist(); - return { success: true, id, version: table[id].version }; - } - if (mutation.action === "Delete") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - delete table[id]; - this.persist(); - return { success: true, id, deleted: true }; + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } - async query(ctx: any, req: any): Promise { + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; - for (const expression of query._filters || []) rows = rows.filter(row => matches(row, expression)); - for (const order of [...(query._orderBy || [])].reverse()) { - rows.sort((a, b) => (a[order.f] === b[order.f] ? 0 : a[order.f] > b[order.f] ? 1 : -1) * (order.d === "desc" ? -1 : 1)); + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); } - const start = query._offset || 0; - return rows.slice(start, query._limit === undefined ? undefined : start + query._limit); } } declare const require: any; -export { UserContext } from "teaql-ts"; -import { UserContext } from "teaql-ts"; export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } -export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/order-management/typescript-node-lib-core/teaql-i18n.json b/source/teaql-ts/examples/order-management/typescript-node-lib-core/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..f8c1a3b256bb87bf917e82da02d0e24274567ba4 --- /dev/null +++ b/source/teaql-ts/examples/order-management/typescript-node-lib-core/teaql-i18n.json @@ -0,0 +1,158 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.orderLine.quantity": "Quantity", + "property.customerOrder.createTime": "Create Time", + "property.customerOrder.updateTime": "Update Time", + "property.product.id": "Id", + "property.orderLine.createTime": "Create Time", + "entity.commercePlatform": "Commerce Platform", + "property.orderSearchPreset.requestId": "Request Id", + "property.product.version": "Version", + "property.product.createTime": "Create Time", + "property.orderSearchPreset.ownerUserId": "Owner User Id", + "entity.customerOrder": "Customer Order", + "entity.orderLine": "Order Line", + "property.product.name": "Name", + "property.orderLine.commercePlatform": "Commerce Platform", + "property.product.updateTime": "Update Time", + "property.customerOrder.totalAmount": "Total Amount", + "property.customerOrder.version": "Version", + "property.orderLine.productName": "Product Name", + "property.customer.version": "Version", + "property.orderSearchPreset.filterJson": "Filter Json", + "property.customer.id": "Id", + "property.orderLine.id": "Id", + "property.orderSearchPreset.name": "Name", + "property.customerOrder.customer": "Customer", + "property.orderLine.product": "Product", + "property.orderStatus.name": "Name", + "property.orderLine.sku": "Sku", + "property.customer.createTime": "Create Time", + "property.customerOrder.orderNumber": "Order Number", + "property.commercePlatform.name": "Name", + "property.orderStatus.commercePlatform": "Commerce Platform", + "property.product.commercePlatform": "Commerce Platform", + "property.commercePlatform.id": "Id", + "property.orderStatus.version": "Version", + "property.customer.updateTime": "Update Time", + "property.customer.commercePlatform": "Commerce Platform", + "property.orderStatus.code": "Code", + "property.orderSearchPreset.id": "Id", + "property.customerOrder.orderDate": "Order Date", + "property.commercePlatform.updateTime": "Update Time", + "property.customer.email": "Email", + "property.orderSearchPreset.createTime": "Create Time", + "property.orderStatus.displayOrder": "Display Order", + "property.orderSearchPreset.version": "Version", + "entity.customer": "Customer", + "property.customerOrder.id": "Id", + "entity.product": "Product", + "property.orderLine.customerOrder": "Customer Order", + "property.orderStatus.color": "Color", + "property.commercePlatform.createTime": "Create Time", + "property.customerOrder.commercePlatform": "Commerce Platform", + "property.orderSearchPreset.updateTime": "Update Time", + "property.product.sku": "Sku", + "property.orderSearchPreset.commercePlatform": "Commerce Platform", + "property.orderStatus.id": "Id", + "property.product.imageUrl": "Image Url", + "property.orderLine.version": "Version", + "entity.orderStatus": "Order Status", + "entity.orderSearchPreset": "Order Search Preset", + "property.customer.name": "Name", + "property.customerOrder.status": "Status", + "property.commercePlatform.version": "Version" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/assist/create/scalar_type_probe.md b/source/teaql-ts/examples/scalar-type-probe/assist/create/scalar_type_probe.md new file mode 100644 index 0000000000000000000000000000000000000000..1d7b26beb526fdb1dbcbcee6e4e13178217a9037 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/assist/create/scalar_type_probe.md @@ -0,0 +1,125 @@ + + +# TypeScript Assist — Create `Scalar Type Probe` + +Use the exact generated `Q.scalarTypeProbes()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { Decimal, UserContext, decimal } from '../teaql-ts'; +import { Q } from './Q'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; + +export interface CreateScalarTypeProbeInput { + typePlatform: string | number; + requiredString: string; + optionalString: string; + largeText: string; + requiredBoolean: boolean; + optionalBoolean: boolean; + requiredInteger: number; + optionalInteger: number; + requiredLong: number; + optionalLong: number; + requiredDecimal: Decimal; + optionalDecimal: Decimal; + requiredFloat: number; + optionalFloat: number; + requiredDouble: number; + optionalDouble: number; + requiredDate: string; + optionalDate: string; + requiredTime: unknown; + optionalTime: unknown; + requiredDatetime: string; + optionalDatetime: string; + +} + +export async function createScalarTypeProbe( + input: CreateScalarTypeProbeInput, + context: UserContext, +): Promise { + const entity = await Q.scalarTypeProbes() + .comment('what: initialize Scalar Type Probe') + .purpose('why: create Scalar Type Probe') + .newEntity(context); + + entity.updateTypePlatform(input.typePlatform); + entity.updateRequiredString(input.requiredString); + entity.updateOptionalString(input.optionalString); + entity.updateLargeText(input.largeText); + entity.updateRequiredBoolean(input.requiredBoolean); + entity.updateOptionalBoolean(input.optionalBoolean); + entity.updateRequiredInteger(input.requiredInteger); + entity.updateOptionalInteger(input.optionalInteger); + entity.updateRequiredLong(input.requiredLong); + entity.updateOptionalLong(input.optionalLong); + entity.updateRequiredDecimal(input.requiredDecimal); + entity.updateOptionalDecimal(input.optionalDecimal); + entity.updateRequiredFloat(input.requiredFloat); + entity.updateOptionalFloat(input.optionalFloat); + entity.updateRequiredDouble(input.requiredDouble); + entity.updateOptionalDouble(input.optionalDouble); + entity.updateRequiredDate(input.requiredDate); + entity.updateOptionalDate(input.optionalDate); + entity.updateRequiredTime(input.requiredTime); + entity.updateOptionalTime(input.optionalTime); + entity.updateRequiredDatetime(input.requiredDatetime); + entity.updateOptionalDatetime(input.optionalDatetime); + + await entity + .auditAs('Create Scalar Type Probe for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +For Decimal fields, construct exact values with `decimal('3.50')`. Do not pass a +JavaScript `number`, which can lose digits before the runtime sees it. + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/scalar-type-probe/assist/expression/scalar_type_probe.md b/source/teaql-ts/examples/scalar-type-probe/assist/expression/scalar_type_probe.md new file mode 100644 index 0000000000000000000000000000000000000000..d2506d312b35c4e33b49ac878ad0509a5689b359 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/assist/expression/scalar_type_probe.md @@ -0,0 +1,321 @@ + + +# TypeScript Assist — Expression `Scalar Type Probe` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +Use the error's `toWire()` for structured diagnostics: `location` is the first +missing canonical path; `attemptedLocation` retains the full suffix and real +list indices. `expressionWithBrokenPoint` marks one `` in the complete +native chain. Use `suggestedFix.location` with Q Assist; never parse the message +or guess a preload method. + +```typescript +import { E } from './E'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; + +export function extractId(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).id().eval(); +} + +export function extractIdOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).id().orElse(fallback); +} + +export function extractRequiredString(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredString().eval(); +} + +export function extractRequiredStringOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredString().orElse(fallback); +} + +export function extractOptionalString(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalString().eval(); +} + +export function extractOptionalStringOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalString().orElse(fallback); +} + +export function extractLargeText(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).largeText().eval(); +} + +export function extractLargeTextOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).largeText().orElse(fallback); +} + +export function extractRequiredBoolean(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredBoolean().eval(); +} + +export function extractRequiredBooleanOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredBoolean().orElse(fallback); +} + +export function extractOptionalBoolean(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalBoolean().eval(); +} + +export function extractOptionalBooleanOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalBoolean().orElse(fallback); +} + +export function extractRequiredInteger(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredInteger().eval(); +} + +export function extractRequiredIntegerOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredInteger().orElse(fallback); +} + +export function extractOptionalInteger(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalInteger().eval(); +} + +export function extractOptionalIntegerOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalInteger().orElse(fallback); +} + +export function extractRequiredLong(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredLong().eval(); +} + +export function extractRequiredLongOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredLong().orElse(fallback); +} + +export function extractOptionalLong(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalLong().eval(); +} + +export function extractOptionalLongOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalLong().orElse(fallback); +} + +export function extractRequiredDecimal(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredDecimal().eval(); +} + +export function extractRequiredDecimalOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredDecimal().orElse(fallback); +} + +export function extractOptionalDecimal(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalDecimal().eval(); +} + +export function extractOptionalDecimalOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalDecimal().orElse(fallback); +} + +export function extractRequiredFloat(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredFloat().eval(); +} + +export function extractRequiredFloatOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredFloat().orElse(fallback); +} + +export function extractOptionalFloat(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalFloat().eval(); +} + +export function extractOptionalFloatOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalFloat().orElse(fallback); +} + +export function extractRequiredDouble(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredDouble().eval(); +} + +export function extractRequiredDoubleOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredDouble().orElse(fallback); +} + +export function extractOptionalDouble(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalDouble().eval(); +} + +export function extractOptionalDoubleOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalDouble().orElse(fallback); +} + +export function extractRequiredDate(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredDate().eval(); +} + +export function extractRequiredDateOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredDate().orElse(fallback); +} + +export function extractOptionalDate(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalDate().eval(); +} + +export function extractOptionalDateOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalDate().orElse(fallback); +} + +export function extractRequiredTime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredTime().eval(); +} + +export function extractRequiredTimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredTime().orElse(fallback); +} + +export function extractOptionalTime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalTime().eval(); +} + +export function extractOptionalTimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalTime().orElse(fallback); +} + +export function extractRequiredDatetime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).requiredDatetime().eval(); +} + +export function extractRequiredDatetimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).requiredDatetime().orElse(fallback); +} + +export function extractOptionalDatetime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).optionalDatetime().eval(); +} + +export function extractOptionalDatetimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).optionalDatetime().orElse(fallback); +} + +export function extractCreateTime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).createTime().eval(); +} + +export function extractCreateTimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).createTime().orElse(fallback); +} + +export function extractUpdateTime(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).updateTime().eval(); +} + +export function extractUpdateTimeOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).updateTime().orElse(fallback); +} + +export function extractVersion(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: ScalarTypeProbe, fallback: NonNullable, +) { + return E.scalarTypeProbe(entity).version().orElse(fallback); +} + +export function extractTypePlatformId(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).typePlatformId().eval(); +} + +export function traverseTypePlatform(entity: ScalarTypeProbe) { + return E.scalarTypeProbe(entity).typePlatform().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/scalar-type-probe/fixture-manifest.json b/source/teaql-ts/examples/scalar-type-probe/fixture-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f1245c8698c3e459ed607fbfab74286c2eb00e58 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/fixture-manifest.json @@ -0,0 +1,35 @@ +{ + "schema": "teaql.generated-example-fixture/v1", + "language": "typescript", + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762", + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "producerReceiptSha256": "80957fd5cd6b67aee4f598a2fb15d586a981504aeb0800f4a9f257774622361e", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "evaluatedScope": "typescript-node-lib-core", + "evaluationErrors": 0, + "evaluationWarnings": 0, + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "previousFixtureManifestSha256": "be42d67d25b63c74e85f8c859dc5db5397cd25b40dcf647dc913d783ca0b3d16", + "generatorCommit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "generatorSourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937", + "producerReportSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d" +} diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/package.json b/source/teaql-ts/examples/scalar-type-probe/generated/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc0449fe65f58906b3f4b83d82fd3074e3aaf88 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/package.json @@ -0,0 +1,18 @@ +{ + "name": "scalar-type-conformance-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-bootstrap.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..c32758df9a96057fe59280ac184fac252759e0b2 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { TypePlatform } from './generated/models/TypePlatform'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.typePlatforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = TypePlatform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Scalar Type Conformance"); + await domainRoot.auditAs('create generated Domain Root TypePlatform').save(context); + } + context.withActiveRoot({ entity: 'TypePlatform', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-search-models.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..40a79e6c3579b1785644cba497ee964459a779bc --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated-search-models.ts @@ -0,0 +1,130 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "TypePlatform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "scalarTypeProbeList": "ScalarTypeProbe", + }), + }), + "ScalarTypeProbe": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "type_platform": "integer" as const, + "typePlatform": "integer" as const, + "required_string": "string" as const, + "requiredString": "string" as const, + "optional_string": "string" as const, + "optionalString": "string" as const, + "large_text": "string" as const, + "largeText": "string" as const, + "required_boolean": "boolean" as const, + "requiredBoolean": "boolean" as const, + "optional_boolean": "boolean" as const, + "optionalBoolean": "boolean" as const, + "required_integer": "integer" as const, + "requiredInteger": "integer" as const, + "optional_integer": "integer" as const, + "optionalInteger": "integer" as const, + "required_long": "integer" as const, + "requiredLong": "integer" as const, + "optional_long": "integer" as const, + "optionalLong": "integer" as const, + "required_decimal": "decimal" as const, + "requiredDecimal": "decimal" as const, + "optional_decimal": "decimal" as const, + "optionalDecimal": "decimal" as const, + "required_float": "number" as const, + "requiredFloat": "number" as const, + "optional_float": "number" as const, + "optionalFloat": "number" as const, + "required_double": "number" as const, + "requiredDouble": "number" as const, + "optional_double": "number" as const, + "optionalDouble": "number" as const, + "required_date": "date" as const, + "requiredDate": "date" as const, + "optional_date": "date" as const, + "optionalDate": "date" as const, + "required_time": "unsupported" as const, + "requiredTime": "unsupported" as const, + "optional_time": "unsupported" as const, + "optionalTime": "unsupported" as const, + "required_datetime": "timestamp" as const, + "requiredDatetime": "timestamp" as const, + "optional_datetime": "timestamp" as const, + "optionalDatetime": "timestamp" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "type_platform": "typePlatform", + "typePlatform": "typePlatform", + "required_string": "requiredString", + "requiredString": "requiredString", + "optional_string": "optionalString", + "optionalString": "optionalString", + "large_text": "largeText", + "largeText": "largeText", + "required_boolean": "requiredBoolean", + "requiredBoolean": "requiredBoolean", + "optional_boolean": "optionalBoolean", + "optionalBoolean": "optionalBoolean", + "required_integer": "requiredInteger", + "requiredInteger": "requiredInteger", + "optional_integer": "optionalInteger", + "optionalInteger": "optionalInteger", + "required_long": "requiredLong", + "requiredLong": "requiredLong", + "optional_long": "optionalLong", + "optionalLong": "optionalLong", + "required_decimal": "requiredDecimal", + "requiredDecimal": "requiredDecimal", + "optional_decimal": "optionalDecimal", + "optionalDecimal": "optionalDecimal", + "required_float": "requiredFloat", + "requiredFloat": "requiredFloat", + "optional_float": "optionalFloat", + "optionalFloat": "optionalFloat", + "required_double": "requiredDouble", + "requiredDouble": "requiredDouble", + "optional_double": "optionalDouble", + "optionalDouble": "optionalDouble", + "required_date": "requiredDate", + "requiredDate": "requiredDate", + "optional_date": "optionalDate", + "optionalDate": "optionalDate", + "required_time": "requiredTime", + "requiredTime": "requiredTime", + "optional_time": "optionalTime", + "optionalTime": "optionalTime", + "required_datetime": "requiredDatetime", + "requiredDatetime": "requiredDatetime", + "optional_datetime": "optionalDatetime", + "optionalDatetime": "optionalDatetime", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "type_platform": "TypePlatform", + "typePlatform": "TypePlatform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/E.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc53535c21ddb69a38876cf65ab146fc893db4d0 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/E.ts @@ -0,0 +1,564 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { TypePlatform } from './models/TypePlatform'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class TypePlatformExpression { + constructor( + private readonly value: TypePlatform | null | undefined, + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.typePlatform()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TypePlatform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + scalarTypeProbeList(): ScalarTypeProbeListExpression { + const path = this.path.member('scalar_type_probe_list', 'scalarTypeProbeList'); + if (this.notLoaded) { + return new ScalarTypeProbeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return ScalarTypeProbeListExpression.missing(this.root, path); + if (!this.value.isLoaded('scalarTypeProbeList')) { + return new ScalarTypeProbeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'scalar_type_probe_list')); + } + return new ScalarTypeProbeListExpression( + this.value.scalarTypeProbeList(), this.root, path, + ); + } +} + +export class ScalarTypeProbeExpression { + constructor( + private readonly value: ScalarTypeProbe | null | undefined, + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.scalarTypeProbe()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): ScalarTypeProbe | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + requiredString(): ValueExpression { + const path = this.path.member('required_string', 'requiredString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_string'), + ); + } + return new ValueExpression(this.value.requiredString); + } + + optionalString(): ValueExpression { + const path = this.path.member('optional_string', 'optionalString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_string'), + ); + } + return new ValueExpression(this.value.optionalString); + } + + largeText(): ValueExpression { + const path = this.path.member('large_text', 'largeText'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('largeText')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'large_text'), + ); + } + return new ValueExpression(this.value.largeText); + } + + requiredBoolean(): ValueExpression { + const path = this.path.member('required_boolean', 'requiredBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_boolean'), + ); + } + return new ValueExpression(this.value.requiredBoolean); + } + + optionalBoolean(): ValueExpression { + const path = this.path.member('optional_boolean', 'optionalBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_boolean'), + ); + } + return new ValueExpression(this.value.optionalBoolean); + } + + requiredInteger(): ValueExpression { + const path = this.path.member('required_integer', 'requiredInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_integer'), + ); + } + const error = integer32Error(this.value.requiredInteger, 'ScalarTypeProbe', 'required_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.requiredInteger); + } + + optionalInteger(): ValueExpression { + const path = this.path.member('optional_integer', 'optionalInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_integer'), + ); + } + const error = integer32Error(this.value.optionalInteger, 'ScalarTypeProbe', 'optional_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.optionalInteger); + } + + requiredLong(): ValueExpression { + const path = this.path.member('required_long', 'requiredLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_long'), + ); + } + return new ValueExpression(this.value.requiredLong); + } + + optionalLong(): ValueExpression { + const path = this.path.member('optional_long', 'optionalLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_long'), + ); + } + return new ValueExpression(this.value.optionalLong); + } + + requiredDecimal(): ValueExpression { + const path = this.path.member('required_decimal', 'requiredDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_decimal'), + ); + } + return new ValueExpression(this.value.requiredDecimal); + } + + optionalDecimal(): ValueExpression { + const path = this.path.member('optional_decimal', 'optionalDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_decimal'), + ); + } + return new ValueExpression(this.value.optionalDecimal); + } + + requiredFloat(): ValueExpression { + const path = this.path.member('required_float', 'requiredFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_float'), + ); + } + return new ValueExpression(this.value.requiredFloat); + } + + optionalFloat(): ValueExpression { + const path = this.path.member('optional_float', 'optionalFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_float'), + ); + } + return new ValueExpression(this.value.optionalFloat); + } + + requiredDouble(): ValueExpression { + const path = this.path.member('required_double', 'requiredDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_double'), + ); + } + return new ValueExpression(this.value.requiredDouble); + } + + optionalDouble(): ValueExpression { + const path = this.path.member('optional_double', 'optionalDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_double'), + ); + } + return new ValueExpression(this.value.optionalDouble); + } + + requiredDate(): ValueExpression { + const path = this.path.member('required_date', 'requiredDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_date'), + ); + } + return new ValueExpression(this.value.requiredDate); + } + + optionalDate(): ValueExpression { + const path = this.path.member('optional_date', 'optionalDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_date'), + ); + } + return new ValueExpression(this.value.optionalDate); + } + + requiredTime(): ValueExpression { + const path = this.path.member('required_time', 'requiredTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_time'), + ); + } + return new ValueExpression(this.value.requiredTime); + } + + optionalTime(): ValueExpression { + const path = this.path.member('optional_time', 'optionalTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_time'), + ); + } + return new ValueExpression(this.value.optionalTime); + } + + requiredDatetime(): ValueExpression { + const path = this.path.member('required_datetime', 'requiredDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_datetime'), + ); + } + return new ValueExpression(this.value.requiredDatetime); + } + + optionalDatetime(): ValueExpression { + const path = this.path.member('optional_datetime', 'optionalDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_datetime'), + ); + } + return new ValueExpression(this.value.optionalDatetime); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + typePlatformId(): ValueExpression { + const path = this.path.member('type_platform', 'typePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('typePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'type_platform'), + ); + } + const reference = this.value.typePlatform; + return new ValueExpression( + reference instanceof TypePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + typePlatform(): TypePlatformExpression { + const path = this.path.member('type_platform', 'typePlatform'); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TypePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('typePlatform')) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const relation = this.value.typePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof TypePlatform)) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const target = relation instanceof TypePlatform ? relation : undefined; + return new TypePlatformExpression(target, this.root, path); + } + +} + +export class TypePlatformListExpression { + constructor( + private readonly items: readonly TypePlatform[], + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TypePlatformListExpression { + return new TypePlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TypePlatformExpression { + return this.item(0, true); + } + + get(index: number): TypePlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TypePlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TypePlatformExpression(undefined, this.root, itemPath) + : new TypePlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class ScalarTypeProbeListExpression { + constructor( + private readonly items: readonly ScalarTypeProbe[], + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): ScalarTypeProbeListExpression { + return new ScalarTypeProbeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): ScalarTypeProbeExpression { + return this.item(0, true); + } + + get(index: number): ScalarTypeProbeExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): ScalarTypeProbeExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new ScalarTypeProbeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new ScalarTypeProbeExpression(undefined, this.root, itemPath) + : new ScalarTypeProbeExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static typePlatform( + value: TypePlatform | null | undefined, + ): TypePlatformExpression { + return new TypePlatformExpression( + value, 'TypePlatform', ExpressionPath.root('E.typePlatform()', 'camelCase'), + ); + } + + static scalarTypeProbe( + value: ScalarTypeProbe | null | undefined, + ): ScalarTypeProbeExpression { + return new ScalarTypeProbeExpression( + value, 'ScalarTypeProbe', ExpressionPath.root('E.scalarTypeProbe()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/Q.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..5124d7963158b57d5460ab83052c5800791f46aa --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { TypePlatformRequest } from './requests/TypePlatformRequest'; +import { ScalarTypeProbeRequest } from './requests/ScalarTypeProbeRequest'; + +export class Q { + static typePlatforms(): TypePlatformRequest { + return new TypePlatformRequest(false); + } + + static typePlatformsWithMinimalFields(): TypePlatformRequest { + return new TypePlatformRequest(true); + } + static scalarTypeProbes(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(false); + } + + static scalarTypeProbesWithMinimalFields(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/ScalarTypeProbe.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/ScalarTypeProbe.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f93cf19ac480a4c610bf02ac8696c043c90b2d --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/ScalarTypeProbe.ts @@ -0,0 +1,576 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TypePlatform } from './TypePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class ScalarTypeProbe { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("ScalarTypeProbe", + ["id", "type_platform", "required_string", "optional_string", "large_text", "required_boolean", "optional_boolean", "required_integer", "optional_integer", "required_long", "optional_long", "required_decimal", "optional_decimal", "required_float", "optional_float", "required_double", "optional_double", "required_date", "optional_date", "required_time", "optional_time", "required_datetime", "optional_datetime", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + typePlatform?: TypePlatform | string; + requiredString?: string; + optionalString?: string | null; + largeText?: string | null; + requiredBoolean?: boolean; + optionalBoolean?: boolean | null; + requiredInteger?: number; + optionalInteger?: number | null; + requiredLong?: Long; + optionalLong?: Long | null; + requiredDecimal?: Decimal; + optionalDecimal?: Decimal | null; + requiredFloat?: number; + optionalFloat?: number | null; + requiredDouble?: number; + optionalDouble?: number | null; + requiredDate?: string; + optionalDate?: string | null; + requiredTime?: LocalTime; + optionalTime?: LocalTime | null; + requiredDatetime?: string; + optionalDatetime?: string | null; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(init?.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --ScalarTypeProbe.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).typePlatform && typeof (init as any).typePlatform === "object") { + this.typePlatform = (init as any).typePlatform instanceof TypePlatform + ? (init as any).typePlatform + : TypePlatform.fromRecord((init as any).typePlatform); + this.markLoaded("typePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "ScalarTypeProbe", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): ScalarTypeProbe { + const entity = EntityCreation.hydrated(new ScalarTypeProbe(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(this.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): ScalarTypeProbe { + return ScalarTypeProbe.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): ScalarTypeProbe { + return EntityCreation.bootstrap(context, "ScalarTypeProbe", id, + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "ScalarTypeProbe", + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "type_platform": "TypePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + ScalarTypeProbe.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "ScalarTypeProbe", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "ScalarTypeProbe", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "ScalarTypeProbe", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "ScalarTypeProbe", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "type_platform": this.typePlatform, + "required_string": this.requiredString, + "optional_string": this.optionalString, + "large_text": this.largeText, + "required_boolean": this.requiredBoolean, + "optional_boolean": this.optionalBoolean, + "required_integer": this.requiredInteger, + "optional_integer": this.optionalInteger, + "required_long": this.requiredLong, + "optional_long": this.optionalLong, + "required_decimal": this.requiredDecimal, + "optional_decimal": this.optionalDecimal, + "required_float": this.requiredFloat, + "optional_float": this.optionalFloat, + "required_double": this.requiredDouble, + "optional_double": this.optionalDouble, + "required_date": this.requiredDate, + "optional_date": this.optionalDate, + "required_time": this.requiredTime, + "optional_time": this.optionalTime, + "required_datetime": this.requiredDatetime, + "optional_datetime": this.optionalDatetime, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateRequiredString(value: string): this { + this.requiredString = value; + this.markLoaded("requiredString"); + (this as any)._root.set(this.teaqlEntityKey(), "required_string", value); + return this; + } + + updateOptionalString(value: string | null): this { + this.optionalString = value; + this.markLoaded("optionalString"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_string", value); + return this; + } + + updateLargeText(value: string | null): this { + this.largeText = value; + this.markLoaded("largeText"); + (this as any)._root.set(this.teaqlEntityKey(), "large_text", value); + return this; + } + + updateRequiredBoolean(value: boolean): this { + this.requiredBoolean = value; + this.markLoaded("requiredBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "required_boolean", value); + return this; + } + + updateOptionalBoolean(value: boolean | null): this { + this.optionalBoolean = value; + this.markLoaded("optionalBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_boolean", value); + return this; + } + + updateRequiredInteger(value: number): this { + this.requiredInteger = value; + this.markLoaded("requiredInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "required_integer", value); + return this; + } + + updateOptionalInteger(value: number | null): this { + this.optionalInteger = value; + this.markLoaded("optionalInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_integer", value); + return this; + } + + updateRequiredLong(value: Long): this { + if (value != null) value = long(value); + this.requiredLong = value; + this.markLoaded("requiredLong"); + (this as any)._root.set(this.teaqlEntityKey(), "required_long", value); + return this; + } + + updateOptionalLong(value: Long | null): this { + if (value != null) value = long(value); + this.optionalLong = value; + this.markLoaded("optionalLong"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_long", value); + return this; + } + + updateRequiredDecimal(value: Decimal): this { + if (value != null) value = decimal(value); + this.requiredDecimal = value; + this.markLoaded("requiredDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "required_decimal", value); + return this; + } + + updateOptionalDecimal(value: Decimal | null): this { + if (value != null) value = decimal(value); + this.optionalDecimal = value; + this.markLoaded("optionalDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_decimal", value); + return this; + } + + updateRequiredFloat(value: number): this { + this.requiredFloat = value; + this.markLoaded("requiredFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "required_float", value); + return this; + } + + updateOptionalFloat(value: number | null): this { + this.optionalFloat = value; + this.markLoaded("optionalFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_float", value); + return this; + } + + updateRequiredDouble(value: number): this { + this.requiredDouble = value; + this.markLoaded("requiredDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "required_double", value); + return this; + } + + updateOptionalDouble(value: number | null): this { + this.optionalDouble = value; + this.markLoaded("optionalDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_double", value); + return this; + } + + updateRequiredDate(value: string): this { + this.requiredDate = value; + this.markLoaded("requiredDate"); + (this as any)._root.set(this.teaqlEntityKey(), "required_date", value); + return this; + } + + updateOptionalDate(value: string | null): this { + this.optionalDate = value; + this.markLoaded("optionalDate"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_date", value); + return this; + } + + updateRequiredTime(value: LocalTime): this { + if (value != null) value = localTime(value); + this.requiredTime = value; + this.markLoaded("requiredTime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_time", value); + return this; + } + + updateOptionalTime(value: LocalTime | null): this { + if (value != null) value = localTime(value); + this.optionalTime = value; + this.markLoaded("optionalTime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_time", value); + return this; + } + + updateRequiredDatetime(value: string): this { + this.requiredDatetime = value; + this.markLoaded("requiredDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_datetime", value); + return this; + } + + updateOptionalDatetime(value: string | null): this { + this.optionalDatetime = value; + this.markLoaded("optionalDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_datetime", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateTypePlatform(value: any): this { + this.typePlatform = value?.id ?? value; + this.markLoaded("typePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "type_platform", this.typePlatform); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/TypePlatform.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/TypePlatform.ts new file mode 100644 index 0000000000000000000000000000000000000000..00fc9ee5d876db31834d06abe61c11f063127e61 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/models/TypePlatform.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { ScalarTypeProbe } from './ScalarTypeProbe'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class TypePlatform { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TypePlatform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TypePlatform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_scalarTypeProbeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["scalarTypeProbeList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).scalarTypeProbeList)) { + const selected = (init as any).scalarTypeProbeList; + (this as any)._scalarTypeProbeList = new SmartList(selected.map( + (child: unknown) => child instanceof ScalarTypeProbe + ? child + : ScalarTypeProbe.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("scalarTypeProbeList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TypePlatform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._scalarTypeProbeList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TypePlatform { + const entity = EntityCreation.hydrated(new TypePlatform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("scalarTypeProbeList")) result["scalarTypeProbeList"] = (this as any)._scalarTypeProbeList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TypePlatform { + return TypePlatform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TypePlatform { + return EntityCreation.bootstrap(context, "TypePlatform", id, + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TypePlatform", + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._scalarTypeProbeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._scalarTypeProbeList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "scalar_type_probe_list": graph.sourceMembers((this as any)._scalarTypeProbeList) + })); + for (const child of (this as any)._scalarTypeProbeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TypePlatform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TypePlatform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TypePlatform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TypePlatform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "TypePlatform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + scalarTypeProbeList(): SmartList { + return (this as any)._scalarTypeProbeList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/ScalarTypeProbeRequest.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/ScalarTypeProbeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aab674d36faae5691bcfb6d8a395878245cbaa4 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/ScalarTypeProbeRequest.ts @@ -0,0 +1,3073 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { ScalarTypeProbe } from '../models/ScalarTypeProbe'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class ScalarTypeProbeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("ScalarTypeProbe"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "ScalarTypeProbe" { + return "ScalarTypeProbe"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableScalarTypeProbeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableScalarTypeProbeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "typePlatform", "requiredString", "optionalString", "largeText", "requiredBoolean", "optionalBoolean", "requiredInteger", "optionalInteger", "requiredLong", "optionalLong", "requiredDecimal", "optionalDecimal", "requiredFloat", "optionalFloat", "requiredDouble", "optionalDouble", "requiredDate", "optionalDate", "requiredTime", "optionalTime", "requiredDatetime", "optionalDatetime", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectRequiredString(): this { + this.query.select(["requiredString"]); + return this; + } + + selectOptionalString(): this { + this.query.select(["optionalString"]); + return this; + } + + selectLargeText(): this { + this.query.select(["largeText"]); + return this; + } + + selectRequiredBoolean(): this { + this.query.select(["requiredBoolean"]); + return this; + } + + selectOptionalBoolean(): this { + this.query.select(["optionalBoolean"]); + return this; + } + + selectRequiredInteger(): this { + this.query.select(["requiredInteger"]); + return this; + } + + selectOptionalInteger(): this { + this.query.select(["optionalInteger"]); + return this; + } + + selectRequiredLong(): this { + this.query.select(["requiredLong"]); + return this; + } + + selectOptionalLong(): this { + this.query.select(["optionalLong"]); + return this; + } + + selectRequiredDecimal(): this { + this.query.select(["requiredDecimal"]); + return this; + } + + selectOptionalDecimal(): this { + this.query.select(["optionalDecimal"]); + return this; + } + + selectRequiredFloat(): this { + this.query.select(["requiredFloat"]); + return this; + } + + selectOptionalFloat(): this { + this.query.select(["optionalFloat"]); + return this; + } + + selectRequiredDouble(): this { + this.query.select(["requiredDouble"]); + return this; + } + + selectOptionalDouble(): this { + this.query.select(["optionalDouble"]); + return this; + } + + selectRequiredDate(): this { + this.query.select(["requiredDate"]); + return this; + } + + selectOptionalDate(): this { + this.query.select(["optionalDate"]); + return this; + } + + selectRequiredTime(): this { + this.query.select(["requiredTime"]); + return this; + } + + selectOptionalTime(): this { + this.query.select(["optionalTime"]); + return this; + } + + selectRequiredDatetime(): this { + this.query.select(["requiredDatetime"]); + return this; + } + + selectOptionalDatetime(): this { + this.query.select(["optionalDatetime"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTypePlatformWith(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["typePlatform"]); + this.query.relationQuery( + "typePlatform", request.toQuery(), "typePlatform", "id", false, + { kind: "relation-select", method: "selectTypePlatformWith", relation: "typePlatform" }); + return this; + } + + withTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTypePlatform(val: any): this { + this.filters.push({ "typePlatform": { "$eq": val } }); + return this; + } + + filterByTypePlatformIn(...vals: any[]): this { + this.filters.push({ "typePlatform": { "$in": vals } }); + return this; + } + + withTypePlatformIsKnown(): this { + this.filters.push({ "typePlatform": { "$isNull": false } }); + return this; + } + + withTypePlatformIsUnknown(): this { + this.filters.push({ "typePlatform": { "$isNull": true } }); + return this; + } + + withRequiredStringContaining(val: string): this { + this.filters.push({ "requiredString": { "$contains": val } }); + return this; + } + + withRequiredStringIs(val: string): this { + this.filters.push({ "requiredString": { "$eq": val } }); + return this; + } + + withRequiredStringIsNot(val: string): this { + this.filters.push({ "requiredString": { "$ne": val } }); + return this; + } + + withRequiredStringIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$in": vals } }); + return this; + } + + withRequiredStringNotIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$notIn": vals } }); + return this; + } + + withRequiredStringGreaterThan(val: string): this { + this.filters.push({ "requiredString": { "$gt": val } }); + return this; + } + + withRequiredStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$gte": val } }); + return this; + } + + withRequiredStringLessThan(val: string): this { + this.filters.push({ "requiredString": { "$lt": val } }); + return this; + } + + withRequiredStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$lte": val } }); + return this; + } + + withRequiredStringBetween(lower: string, upper: string): this { + this.filters.push({ "requiredString": { "$between": [lower, upper] } }); + return this; + } + + withRequiredStringIsKnown(): this { + this.filters.push({ "requiredString": { "$isNull": false } }); + return this; + } + + withRequiredStringIsUnknown(): this { + this.filters.push({ "requiredString": { "$isNull": true } }); + return this; + } + withRequiredStringNotContaining(val: string): this { + this.filters.push({ "requiredString": { "$notContains": val } }); + return this; + } + + withRequiredStringStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$startsWith": val } }); + return this; + } + + withRequiredStringNotStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$notStartsWith": val } }); + return this; + } + + withRequiredStringEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$endsWith": val } }); + return this; + } + + withRequiredStringNotEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$notEndsWith": val } }); + return this; + } + + withRequiredStringSoundingLike(val: string): this { + this.filters.push({ "requiredString": { "$soundLike": val } }); + return this; + } + + withOptionalStringContaining(val: string): this { + this.filters.push({ "optionalString": { "$contains": val } }); + return this; + } + + withOptionalStringIs(val: string): this { + this.filters.push({ "optionalString": { "$eq": val } }); + return this; + } + + withOptionalStringIsNot(val: string): this { + this.filters.push({ "optionalString": { "$ne": val } }); + return this; + } + + withOptionalStringIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$in": vals } }); + return this; + } + + withOptionalStringNotIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$notIn": vals } }); + return this; + } + + withOptionalStringGreaterThan(val: string): this { + this.filters.push({ "optionalString": { "$gt": val } }); + return this; + } + + withOptionalStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$gte": val } }); + return this; + } + + withOptionalStringLessThan(val: string): this { + this.filters.push({ "optionalString": { "$lt": val } }); + return this; + } + + withOptionalStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$lte": val } }); + return this; + } + + withOptionalStringBetween(lower: string, upper: string): this { + this.filters.push({ "optionalString": { "$between": [lower, upper] } }); + return this; + } + + withOptionalStringIsKnown(): this { + this.filters.push({ "optionalString": { "$isNull": false } }); + return this; + } + + withOptionalStringIsUnknown(): this { + this.filters.push({ "optionalString": { "$isNull": true } }); + return this; + } + withOptionalStringNotContaining(val: string): this { + this.filters.push({ "optionalString": { "$notContains": val } }); + return this; + } + + withOptionalStringStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$startsWith": val } }); + return this; + } + + withOptionalStringNotStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$notStartsWith": val } }); + return this; + } + + withOptionalStringEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$endsWith": val } }); + return this; + } + + withOptionalStringNotEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$notEndsWith": val } }); + return this; + } + + withOptionalStringSoundingLike(val: string): this { + this.filters.push({ "optionalString": { "$soundLike": val } }); + return this; + } + + withLargeTextContaining(val: string): this { + this.filters.push({ "largeText": { "$contains": val } }); + return this; + } + + withLargeTextIs(val: string): this { + this.filters.push({ "largeText": { "$eq": val } }); + return this; + } + + withLargeTextIsNot(val: string): this { + this.filters.push({ "largeText": { "$ne": val } }); + return this; + } + + withLargeTextIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$in": vals } }); + return this; + } + + withLargeTextNotIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$notIn": vals } }); + return this; + } + + withLargeTextGreaterThan(val: string): this { + this.filters.push({ "largeText": { "$gt": val } }); + return this; + } + + withLargeTextGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$gte": val } }); + return this; + } + + withLargeTextLessThan(val: string): this { + this.filters.push({ "largeText": { "$lt": val } }); + return this; + } + + withLargeTextLessThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$lte": val } }); + return this; + } + + withLargeTextBetween(lower: string, upper: string): this { + this.filters.push({ "largeText": { "$between": [lower, upper] } }); + return this; + } + + withLargeTextIsKnown(): this { + this.filters.push({ "largeText": { "$isNull": false } }); + return this; + } + + withLargeTextIsUnknown(): this { + this.filters.push({ "largeText": { "$isNull": true } }); + return this; + } + withLargeTextNotContaining(val: string): this { + this.filters.push({ "largeText": { "$notContains": val } }); + return this; + } + + withLargeTextStartingWith(val: string): this { + this.filters.push({ "largeText": { "$startsWith": val } }); + return this; + } + + withLargeTextNotStartingWith(val: string): this { + this.filters.push({ "largeText": { "$notStartsWith": val } }); + return this; + } + + withLargeTextEndingWith(val: string): this { + this.filters.push({ "largeText": { "$endsWith": val } }); + return this; + } + + withLargeTextNotEndingWith(val: string): this { + this.filters.push({ "largeText": { "$notEndsWith": val } }); + return this; + } + + withLargeTextSoundingLike(val: string): this { + this.filters.push({ "largeText": { "$soundLike": val } }); + return this; + } + + whichAreRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": true } }); + return this; + } + + whichAreNotRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": false } }); + return this; + } + withRequiredBooleanIsNot(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$ne": val } }); + return this; + } + + withRequiredBooleanIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$in": vals } }); + return this; + } + + withRequiredBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$notIn": vals } }); + return this; + } + + withRequiredBooleanGreaterThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gt": val } }); + return this; + } + + withRequiredBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gte": val } }); + return this; + } + + withRequiredBooleanLessThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lt": val } }); + return this; + } + + withRequiredBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lte": val } }); + return this; + } + + withRequiredBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "requiredBoolean": { "$between": [lower, upper] } }); + return this; + } + + withRequiredBooleanIsKnown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": false } }); + return this; + } + + withRequiredBooleanIsUnknown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": true } }); + return this; + } + + whichAreOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": true } }); + return this; + } + + whichAreNotOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": false } }); + return this; + } + withOptionalBooleanIsNot(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$ne": val } }); + return this; + } + + withOptionalBooleanIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$in": vals } }); + return this; + } + + withOptionalBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$notIn": vals } }); + return this; + } + + withOptionalBooleanGreaterThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gt": val } }); + return this; + } + + withOptionalBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gte": val } }); + return this; + } + + withOptionalBooleanLessThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lt": val } }); + return this; + } + + withOptionalBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lte": val } }); + return this; + } + + withOptionalBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "optionalBoolean": { "$between": [lower, upper] } }); + return this; + } + + withOptionalBooleanIsKnown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": false } }); + return this; + } + + withOptionalBooleanIsUnknown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": true } }); + return this; + } + + withRequiredIntegerIs(val: number): this { + this.filters.push({ "requiredInteger": { "$eq": val } }); + return this; + } + + withRequiredIntegerIsNot(val: number): this { + this.filters.push({ "requiredInteger": { "$ne": val } }); + return this; + } + + withRequiredIntegerIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$in": vals } }); + return this; + } + + withRequiredIntegerNotIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$notIn": vals } }); + return this; + } + + withRequiredIntegerGreaterThan(val: number): this { + this.filters.push({ "requiredInteger": { "$gt": val } }); + return this; + } + + withRequiredIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$gte": val } }); + return this; + } + + withRequiredIntegerLessThan(val: number): this { + this.filters.push({ "requiredInteger": { "$lt": val } }); + return this; + } + + withRequiredIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$lte": val } }); + return this; + } + + withRequiredIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "requiredInteger": { "$between": [lower, upper] } }); + return this; + } + + withRequiredIntegerIsKnown(): this { + this.filters.push({ "requiredInteger": { "$isNull": false } }); + return this; + } + + withRequiredIntegerIsUnknown(): this { + this.filters.push({ "requiredInteger": { "$isNull": true } }); + return this; + } + + withOptionalIntegerIs(val: number): this { + this.filters.push({ "optionalInteger": { "$eq": val } }); + return this; + } + + withOptionalIntegerIsNot(val: number): this { + this.filters.push({ "optionalInteger": { "$ne": val } }); + return this; + } + + withOptionalIntegerIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$in": vals } }); + return this; + } + + withOptionalIntegerNotIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$notIn": vals } }); + return this; + } + + withOptionalIntegerGreaterThan(val: number): this { + this.filters.push({ "optionalInteger": { "$gt": val } }); + return this; + } + + withOptionalIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$gte": val } }); + return this; + } + + withOptionalIntegerLessThan(val: number): this { + this.filters.push({ "optionalInteger": { "$lt": val } }); + return this; + } + + withOptionalIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$lte": val } }); + return this; + } + + withOptionalIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "optionalInteger": { "$between": [lower, upper] } }); + return this; + } + + withOptionalIntegerIsKnown(): this { + this.filters.push({ "optionalInteger": { "$isNull": false } }); + return this; + } + + withOptionalIntegerIsUnknown(): this { + this.filters.push({ "optionalInteger": { "$isNull": true } }); + return this; + } + + withRequiredLongIs(val: Long): this { + this.filters.push({ "requiredLong": { "$eq": val } }); + return this; + } + + withRequiredLongIsNot(val: Long): this { + this.filters.push({ "requiredLong": { "$ne": val } }); + return this; + } + + withRequiredLongIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$in": vals } }); + return this; + } + + withRequiredLongNotIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$notIn": vals } }); + return this; + } + + withRequiredLongGreaterThan(val: Long): this { + this.filters.push({ "requiredLong": { "$gt": val } }); + return this; + } + + withRequiredLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$gte": val } }); + return this; + } + + withRequiredLongLessThan(val: Long): this { + this.filters.push({ "requiredLong": { "$lt": val } }); + return this; + } + + withRequiredLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$lte": val } }); + return this; + } + + withRequiredLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "requiredLong": { "$between": [lower, upper] } }); + return this; + } + + withRequiredLongIsKnown(): this { + this.filters.push({ "requiredLong": { "$isNull": false } }); + return this; + } + + withRequiredLongIsUnknown(): this { + this.filters.push({ "requiredLong": { "$isNull": true } }); + return this; + } + + withOptionalLongIs(val: Long): this { + this.filters.push({ "optionalLong": { "$eq": val } }); + return this; + } + + withOptionalLongIsNot(val: Long): this { + this.filters.push({ "optionalLong": { "$ne": val } }); + return this; + } + + withOptionalLongIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$in": vals } }); + return this; + } + + withOptionalLongNotIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$notIn": vals } }); + return this; + } + + withOptionalLongGreaterThan(val: Long): this { + this.filters.push({ "optionalLong": { "$gt": val } }); + return this; + } + + withOptionalLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$gte": val } }); + return this; + } + + withOptionalLongLessThan(val: Long): this { + this.filters.push({ "optionalLong": { "$lt": val } }); + return this; + } + + withOptionalLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$lte": val } }); + return this; + } + + withOptionalLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "optionalLong": { "$between": [lower, upper] } }); + return this; + } + + withOptionalLongIsKnown(): this { + this.filters.push({ "optionalLong": { "$isNull": false } }); + return this; + } + + withOptionalLongIsUnknown(): this { + this.filters.push({ "optionalLong": { "$isNull": true } }); + return this; + } + + withRequiredDecimalIs(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$eq": val } }); + return this; + } + + withRequiredDecimalIsNot(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$ne": val } }); + return this; + } + + withRequiredDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$in": vals } }); + return this; + } + + withRequiredDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$notIn": vals } }); + return this; + } + + withRequiredDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gt": val } }); + return this; + } + + withRequiredDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gte": val } }); + return this; + } + + withRequiredDecimalLessThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lt": val } }); + return this; + } + + withRequiredDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lte": val } }); + return this; + } + + withRequiredDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "requiredDecimal": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDecimalIsKnown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": false } }); + return this; + } + + withRequiredDecimalIsUnknown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": true } }); + return this; + } + + withOptionalDecimalIs(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$eq": val } }); + return this; + } + + withOptionalDecimalIsNot(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$ne": val } }); + return this; + } + + withOptionalDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$in": vals } }); + return this; + } + + withOptionalDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$notIn": vals } }); + return this; + } + + withOptionalDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gt": val } }); + return this; + } + + withOptionalDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gte": val } }); + return this; + } + + withOptionalDecimalLessThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lt": val } }); + return this; + } + + withOptionalDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lte": val } }); + return this; + } + + withOptionalDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "optionalDecimal": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDecimalIsKnown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": false } }); + return this; + } + + withOptionalDecimalIsUnknown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": true } }); + return this; + } + + withRequiredFloatIs(val: number): this { + this.filters.push({ "requiredFloat": { "$eq": val } }); + return this; + } + + withRequiredFloatIsNot(val: number): this { + this.filters.push({ "requiredFloat": { "$ne": val } }); + return this; + } + + withRequiredFloatIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$in": vals } }); + return this; + } + + withRequiredFloatNotIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$notIn": vals } }); + return this; + } + + withRequiredFloatGreaterThan(val: number): this { + this.filters.push({ "requiredFloat": { "$gt": val } }); + return this; + } + + withRequiredFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$gte": val } }); + return this; + } + + withRequiredFloatLessThan(val: number): this { + this.filters.push({ "requiredFloat": { "$lt": val } }); + return this; + } + + withRequiredFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$lte": val } }); + return this; + } + + withRequiredFloatBetween(lower: number, upper: number): this { + this.filters.push({ "requiredFloat": { "$between": [lower, upper] } }); + return this; + } + + withRequiredFloatIsKnown(): this { + this.filters.push({ "requiredFloat": { "$isNull": false } }); + return this; + } + + withRequiredFloatIsUnknown(): this { + this.filters.push({ "requiredFloat": { "$isNull": true } }); + return this; + } + + withOptionalFloatIs(val: number): this { + this.filters.push({ "optionalFloat": { "$eq": val } }); + return this; + } + + withOptionalFloatIsNot(val: number): this { + this.filters.push({ "optionalFloat": { "$ne": val } }); + return this; + } + + withOptionalFloatIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$in": vals } }); + return this; + } + + withOptionalFloatNotIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$notIn": vals } }); + return this; + } + + withOptionalFloatGreaterThan(val: number): this { + this.filters.push({ "optionalFloat": { "$gt": val } }); + return this; + } + + withOptionalFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$gte": val } }); + return this; + } + + withOptionalFloatLessThan(val: number): this { + this.filters.push({ "optionalFloat": { "$lt": val } }); + return this; + } + + withOptionalFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$lte": val } }); + return this; + } + + withOptionalFloatBetween(lower: number, upper: number): this { + this.filters.push({ "optionalFloat": { "$between": [lower, upper] } }); + return this; + } + + withOptionalFloatIsKnown(): this { + this.filters.push({ "optionalFloat": { "$isNull": false } }); + return this; + } + + withOptionalFloatIsUnknown(): this { + this.filters.push({ "optionalFloat": { "$isNull": true } }); + return this; + } + + withRequiredDoubleIs(val: number): this { + this.filters.push({ "requiredDouble": { "$eq": val } }); + return this; + } + + withRequiredDoubleIsNot(val: number): this { + this.filters.push({ "requiredDouble": { "$ne": val } }); + return this; + } + + withRequiredDoubleIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$in": vals } }); + return this; + } + + withRequiredDoubleNotIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$notIn": vals } }); + return this; + } + + withRequiredDoubleGreaterThan(val: number): this { + this.filters.push({ "requiredDouble": { "$gt": val } }); + return this; + } + + withRequiredDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$gte": val } }); + return this; + } + + withRequiredDoubleLessThan(val: number): this { + this.filters.push({ "requiredDouble": { "$lt": val } }); + return this; + } + + withRequiredDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$lte": val } }); + return this; + } + + withRequiredDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "requiredDouble": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDoubleIsKnown(): this { + this.filters.push({ "requiredDouble": { "$isNull": false } }); + return this; + } + + withRequiredDoubleIsUnknown(): this { + this.filters.push({ "requiredDouble": { "$isNull": true } }); + return this; + } + + withOptionalDoubleIs(val: number): this { + this.filters.push({ "optionalDouble": { "$eq": val } }); + return this; + } + + withOptionalDoubleIsNot(val: number): this { + this.filters.push({ "optionalDouble": { "$ne": val } }); + return this; + } + + withOptionalDoubleIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$in": vals } }); + return this; + } + + withOptionalDoubleNotIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$notIn": vals } }); + return this; + } + + withOptionalDoubleGreaterThan(val: number): this { + this.filters.push({ "optionalDouble": { "$gt": val } }); + return this; + } + + withOptionalDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$gte": val } }); + return this; + } + + withOptionalDoubleLessThan(val: number): this { + this.filters.push({ "optionalDouble": { "$lt": val } }); + return this; + } + + withOptionalDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$lte": val } }); + return this; + } + + withOptionalDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "optionalDouble": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDoubleIsKnown(): this { + this.filters.push({ "optionalDouble": { "$isNull": false } }); + return this; + } + + withOptionalDoubleIsUnknown(): this { + this.filters.push({ "optionalDouble": { "$isNull": true } }); + return this; + } + + withRequiredDateIs(val: string): this { + this.filters.push({ "requiredDate": { "$eq": val } }); + return this; + } + + withRequiredDateIsNot(val: string): this { + this.filters.push({ "requiredDate": { "$ne": val } }); + return this; + } + + withRequiredDateIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$in": vals } }); + return this; + } + + withRequiredDateNotIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$notIn": vals } }); + return this; + } + + withRequiredDateGreaterThan(val: string): this { + this.filters.push({ "requiredDate": { "$gt": val } }); + return this; + } + + withRequiredDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$gte": val } }); + return this; + } + + withRequiredDateLessThan(val: string): this { + this.filters.push({ "requiredDate": { "$lt": val } }); + return this; + } + + withRequiredDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$lte": val } }); + return this; + } + + withRequiredDateBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDate": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDateIsKnown(): this { + this.filters.push({ "requiredDate": { "$isNull": false } }); + return this; + } + + withRequiredDateIsUnknown(): this { + this.filters.push({ "requiredDate": { "$isNull": true } }); + return this; + } + + withOptionalDateIs(val: string): this { + this.filters.push({ "optionalDate": { "$eq": val } }); + return this; + } + + withOptionalDateIsNot(val: string): this { + this.filters.push({ "optionalDate": { "$ne": val } }); + return this; + } + + withOptionalDateIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$in": vals } }); + return this; + } + + withOptionalDateNotIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$notIn": vals } }); + return this; + } + + withOptionalDateGreaterThan(val: string): this { + this.filters.push({ "optionalDate": { "$gt": val } }); + return this; + } + + withOptionalDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$gte": val } }); + return this; + } + + withOptionalDateLessThan(val: string): this { + this.filters.push({ "optionalDate": { "$lt": val } }); + return this; + } + + withOptionalDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$lte": val } }); + return this; + } + + withOptionalDateBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDate": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDateIsKnown(): this { + this.filters.push({ "optionalDate": { "$isNull": false } }); + return this; + } + + withOptionalDateIsUnknown(): this { + this.filters.push({ "optionalDate": { "$isNull": true } }); + return this; + } + + withRequiredTimeIs(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$eq": val } }); + return this; + } + + withRequiredTimeIsNot(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$ne": val } }); + return this; + } + + withRequiredTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$in": vals } }); + return this; + } + + withRequiredTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$notIn": vals } }); + return this; + } + + withRequiredTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gt": val } }); + return this; + } + + withRequiredTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gte": val } }); + return this; + } + + withRequiredTimeLessThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lt": val } }); + return this; + } + + withRequiredTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lte": val } }); + return this; + } + + withRequiredTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "requiredTime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredTimeIsKnown(): this { + this.filters.push({ "requiredTime": { "$isNull": false } }); + return this; + } + + withRequiredTimeIsUnknown(): this { + this.filters.push({ "requiredTime": { "$isNull": true } }); + return this; + } + + withOptionalTimeIs(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$eq": val } }); + return this; + } + + withOptionalTimeIsNot(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$ne": val } }); + return this; + } + + withOptionalTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$in": vals } }); + return this; + } + + withOptionalTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$notIn": vals } }); + return this; + } + + withOptionalTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gt": val } }); + return this; + } + + withOptionalTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gte": val } }); + return this; + } + + withOptionalTimeLessThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lt": val } }); + return this; + } + + withOptionalTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lte": val } }); + return this; + } + + withOptionalTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "optionalTime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalTimeIsKnown(): this { + this.filters.push({ "optionalTime": { "$isNull": false } }); + return this; + } + + withOptionalTimeIsUnknown(): this { + this.filters.push({ "optionalTime": { "$isNull": true } }); + return this; + } + + withRequiredDatetimeIs(val: string): this { + this.filters.push({ "requiredDatetime": { "$eq": val } }); + return this; + } + + withRequiredDatetimeIsNot(val: string): this { + this.filters.push({ "requiredDatetime": { "$ne": val } }); + return this; + } + + withRequiredDatetimeIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$in": vals } }); + return this; + } + + withRequiredDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$notIn": vals } }); + return this; + } + + withRequiredDatetimeGreaterThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$gt": val } }); + return this; + } + + withRequiredDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$gte": val } }); + return this; + } + + withRequiredDatetimeLessThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$lt": val } }); + return this; + } + + withRequiredDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$lte": val } }); + return this; + } + + withRequiredDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDatetime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDatetimeIsKnown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": false } }); + return this; + } + + withRequiredDatetimeIsUnknown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": true } }); + return this; + } + + withOptionalDatetimeIs(val: string): this { + this.filters.push({ "optionalDatetime": { "$eq": val } }); + return this; + } + + withOptionalDatetimeIsNot(val: string): this { + this.filters.push({ "optionalDatetime": { "$ne": val } }); + return this; + } + + withOptionalDatetimeIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$in": vals } }); + return this; + } + + withOptionalDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$notIn": vals } }); + return this; + } + + withOptionalDatetimeGreaterThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$gt": val } }); + return this; + } + + withOptionalDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$gte": val } }); + return this; + } + + withOptionalDatetimeLessThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$lt": val } }); + return this; + } + + withOptionalDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$lte": val } }); + return this; + } + + withOptionalDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDatetime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDatetimeIsKnown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": false } }); + return this; + } + + withOptionalDatetimeIsUnknown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByRequiredStringAscending(): this { + this.query.orderBy("requiredString", "asc"); + return this; + } + + orderByRequiredStringDescending(): this { + this.query.orderBy("requiredString", "desc"); + return this; + } + + orderByOptionalStringAscending(): this { + this.query.orderBy("optionalString", "asc"); + return this; + } + + orderByOptionalStringDescending(): this { + this.query.orderBy("optionalString", "desc"); + return this; + } + + orderByLargeTextAscending(): this { + this.query.orderBy("largeText", "asc"); + return this; + } + + orderByLargeTextDescending(): this { + this.query.orderBy("largeText", "desc"); + return this; + } + + orderByRequiredBooleanAscending(): this { + this.query.orderBy("requiredBoolean", "asc"); + return this; + } + + orderByRequiredBooleanDescending(): this { + this.query.orderBy("requiredBoolean", "desc"); + return this; + } + + orderByOptionalBooleanAscending(): this { + this.query.orderBy("optionalBoolean", "asc"); + return this; + } + + orderByOptionalBooleanDescending(): this { + this.query.orderBy("optionalBoolean", "desc"); + return this; + } + + orderByRequiredIntegerAscending(): this { + this.query.orderBy("requiredInteger", "asc"); + return this; + } + + orderByRequiredIntegerDescending(): this { + this.query.orderBy("requiredInteger", "desc"); + return this; + } + + orderByOptionalIntegerAscending(): this { + this.query.orderBy("optionalInteger", "asc"); + return this; + } + + orderByOptionalIntegerDescending(): this { + this.query.orderBy("optionalInteger", "desc"); + return this; + } + + orderByRequiredLongAscending(): this { + this.query.orderBy("requiredLong", "asc"); + return this; + } + + orderByRequiredLongDescending(): this { + this.query.orderBy("requiredLong", "desc"); + return this; + } + + orderByOptionalLongAscending(): this { + this.query.orderBy("optionalLong", "asc"); + return this; + } + + orderByOptionalLongDescending(): this { + this.query.orderBy("optionalLong", "desc"); + return this; + } + + orderByRequiredDecimalAscending(): this { + this.query.orderBy("requiredDecimal", "asc"); + return this; + } + + orderByRequiredDecimalDescending(): this { + this.query.orderBy("requiredDecimal", "desc"); + return this; + } + + orderByOptionalDecimalAscending(): this { + this.query.orderBy("optionalDecimal", "asc"); + return this; + } + + orderByOptionalDecimalDescending(): this { + this.query.orderBy("optionalDecimal", "desc"); + return this; + } + + orderByRequiredFloatAscending(): this { + this.query.orderBy("requiredFloat", "asc"); + return this; + } + + orderByRequiredFloatDescending(): this { + this.query.orderBy("requiredFloat", "desc"); + return this; + } + + orderByOptionalFloatAscending(): this { + this.query.orderBy("optionalFloat", "asc"); + return this; + } + + orderByOptionalFloatDescending(): this { + this.query.orderBy("optionalFloat", "desc"); + return this; + } + + orderByRequiredDoubleAscending(): this { + this.query.orderBy("requiredDouble", "asc"); + return this; + } + + orderByRequiredDoubleDescending(): this { + this.query.orderBy("requiredDouble", "desc"); + return this; + } + + orderByOptionalDoubleAscending(): this { + this.query.orderBy("optionalDouble", "asc"); + return this; + } + + orderByOptionalDoubleDescending(): this { + this.query.orderBy("optionalDouble", "desc"); + return this; + } + + orderByRequiredDateAscending(): this { + this.query.orderBy("requiredDate", "asc"); + return this; + } + + orderByRequiredDateDescending(): this { + this.query.orderBy("requiredDate", "desc"); + return this; + } + + orderByOptionalDateAscending(): this { + this.query.orderBy("optionalDate", "asc"); + return this; + } + + orderByOptionalDateDescending(): this { + this.query.orderBy("optionalDate", "desc"); + return this; + } + + orderByRequiredTimeAscending(): this { + this.query.orderBy("requiredTime", "asc"); + return this; + } + + orderByRequiredTimeDescending(): this { + this.query.orderBy("requiredTime", "desc"); + return this; + } + + orderByOptionalTimeAscending(): this { + this.query.orderBy("optionalTime", "asc"); + return this; + } + + orderByOptionalTimeDescending(): this { + this.query.orderBy("optionalTime", "desc"); + return this; + } + + orderByRequiredDatetimeAscending(): this { + this.query.orderBy("requiredDatetime", "asc"); + return this; + } + + orderByRequiredDatetimeDescending(): this { + this.query.orderBy("requiredDatetime", "desc"); + return this; + } + + orderByOptionalDatetimeAscending(): this { + this.query.orderBy("optionalDatetime", "asc"); + return this; + } + + orderByOptionalDatetimeDescending(): this { + this.query.orderBy("optionalDatetime", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minRequiredInteger(): this { + return this.minRequiredIntegerAs("minOfRequiredInteger"); + } + + minRequiredIntegerAs(retName: string): this { + this.query.aggregate("min", "requiredInteger", retName); + return this; + } + maxRequiredInteger(): this { + return this.maxRequiredIntegerAs("maxOfRequiredInteger"); + } + + maxRequiredIntegerAs(retName: string): this { + this.query.aggregate("max", "requiredInteger", retName); + return this; + } + sumRequiredInteger(): this { + return this.sumRequiredIntegerAs("sumOfRequiredInteger"); + } + + sumRequiredIntegerAs(retName: string): this { + this.query.aggregate("sum", "requiredInteger", retName); + return this; + } + avgRequiredInteger(): this { + return this.avgRequiredIntegerAs("avgOfRequiredInteger"); + } + + avgRequiredIntegerAs(retName: string): this { + this.query.aggregate("avg", "requiredInteger", retName); + return this; + } + standardDeviationRequiredInteger(): this { + return this.standardDeviationRequiredIntegerAs("standardDeviationOfRequiredInteger"); + } + + standardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev", "requiredInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredInteger(): this { + return this.squareRootOfPopulationStandardDeviationRequiredIntegerAs("squareRootOfPopulationStandardDeviationOfRequiredInteger"); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredInteger", retName); + return this; + } + sampleVarianceRequiredInteger(): this { + return this.sampleVarianceRequiredIntegerAs("sampleVarianceOfRequiredInteger"); + } + + sampleVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "requiredInteger", retName); + return this; + } + samplePopulationVarianceRequiredInteger(): this { + return this.samplePopulationVarianceRequiredIntegerAs("samplePopulationVarianceOfRequiredInteger"); + } + + samplePopulationVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "requiredInteger", retName); + return this; + } + minOptionalInteger(): this { + return this.minOptionalIntegerAs("minOfOptionalInteger"); + } + + minOptionalIntegerAs(retName: string): this { + this.query.aggregate("min", "optionalInteger", retName); + return this; + } + maxOptionalInteger(): this { + return this.maxOptionalIntegerAs("maxOfOptionalInteger"); + } + + maxOptionalIntegerAs(retName: string): this { + this.query.aggregate("max", "optionalInteger", retName); + return this; + } + sumOptionalInteger(): this { + return this.sumOptionalIntegerAs("sumOfOptionalInteger"); + } + + sumOptionalIntegerAs(retName: string): this { + this.query.aggregate("sum", "optionalInteger", retName); + return this; + } + avgOptionalInteger(): this { + return this.avgOptionalIntegerAs("avgOfOptionalInteger"); + } + + avgOptionalIntegerAs(retName: string): this { + this.query.aggregate("avg", "optionalInteger", retName); + return this; + } + standardDeviationOptionalInteger(): this { + return this.standardDeviationOptionalIntegerAs("standardDeviationOfOptionalInteger"); + } + + standardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev", "optionalInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalInteger(): this { + return this.squareRootOfPopulationStandardDeviationOptionalIntegerAs("squareRootOfPopulationStandardDeviationOfOptionalInteger"); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalInteger", retName); + return this; + } + sampleVarianceOptionalInteger(): this { + return this.sampleVarianceOptionalIntegerAs("sampleVarianceOfOptionalInteger"); + } + + sampleVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "optionalInteger", retName); + return this; + } + samplePopulationVarianceOptionalInteger(): this { + return this.samplePopulationVarianceOptionalIntegerAs("samplePopulationVarianceOfOptionalInteger"); + } + + samplePopulationVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "optionalInteger", retName); + return this; + } + minRequiredLong(): this { + return this.minRequiredLongAs("minOfRequiredLong"); + } + + minRequiredLongAs(retName: string): this { + this.query.aggregate("min", "requiredLong", retName); + return this; + } + maxRequiredLong(): this { + return this.maxRequiredLongAs("maxOfRequiredLong"); + } + + maxRequiredLongAs(retName: string): this { + this.query.aggregate("max", "requiredLong", retName); + return this; + } + sumRequiredLong(): this { + return this.sumRequiredLongAs("sumOfRequiredLong"); + } + + sumRequiredLongAs(retName: string): this { + this.query.aggregate("sum", "requiredLong", retName); + return this; + } + avgRequiredLong(): this { + return this.avgRequiredLongAs("avgOfRequiredLong"); + } + + avgRequiredLongAs(retName: string): this { + this.query.aggregate("avg", "requiredLong", retName); + return this; + } + standardDeviationRequiredLong(): this { + return this.standardDeviationRequiredLongAs("standardDeviationOfRequiredLong"); + } + + standardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev", "requiredLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLong(): this { + return this.squareRootOfPopulationStandardDeviationRequiredLongAs("squareRootOfPopulationStandardDeviationOfRequiredLong"); + } + + squareRootOfPopulationStandardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredLong", retName); + return this; + } + sampleVarianceRequiredLong(): this { + return this.sampleVarianceRequiredLongAs("sampleVarianceOfRequiredLong"); + } + + sampleVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_samp", "requiredLong", retName); + return this; + } + samplePopulationVarianceRequiredLong(): this { + return this.samplePopulationVarianceRequiredLongAs("samplePopulationVarianceOfRequiredLong"); + } + + samplePopulationVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_pop", "requiredLong", retName); + return this; + } + minOptionalLong(): this { + return this.minOptionalLongAs("minOfOptionalLong"); + } + + minOptionalLongAs(retName: string): this { + this.query.aggregate("min", "optionalLong", retName); + return this; + } + maxOptionalLong(): this { + return this.maxOptionalLongAs("maxOfOptionalLong"); + } + + maxOptionalLongAs(retName: string): this { + this.query.aggregate("max", "optionalLong", retName); + return this; + } + sumOptionalLong(): this { + return this.sumOptionalLongAs("sumOfOptionalLong"); + } + + sumOptionalLongAs(retName: string): this { + this.query.aggregate("sum", "optionalLong", retName); + return this; + } + avgOptionalLong(): this { + return this.avgOptionalLongAs("avgOfOptionalLong"); + } + + avgOptionalLongAs(retName: string): this { + this.query.aggregate("avg", "optionalLong", retName); + return this; + } + standardDeviationOptionalLong(): this { + return this.standardDeviationOptionalLongAs("standardDeviationOfOptionalLong"); + } + + standardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev", "optionalLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLong(): this { + return this.squareRootOfPopulationStandardDeviationOptionalLongAs("squareRootOfPopulationStandardDeviationOfOptionalLong"); + } + + squareRootOfPopulationStandardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalLong", retName); + return this; + } + sampleVarianceOptionalLong(): this { + return this.sampleVarianceOptionalLongAs("sampleVarianceOfOptionalLong"); + } + + sampleVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_samp", "optionalLong", retName); + return this; + } + samplePopulationVarianceOptionalLong(): this { + return this.samplePopulationVarianceOptionalLongAs("samplePopulationVarianceOfOptionalLong"); + } + + samplePopulationVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_pop", "optionalLong", retName); + return this; + } + minRequiredDecimal(): this { + return this.minRequiredDecimalAs("minOfRequiredDecimal"); + } + + minRequiredDecimalAs(retName: string): this { + this.query.aggregate("min", "requiredDecimal", retName); + return this; + } + maxRequiredDecimal(): this { + return this.maxRequiredDecimalAs("maxOfRequiredDecimal"); + } + + maxRequiredDecimalAs(retName: string): this { + this.query.aggregate("max", "requiredDecimal", retName); + return this; + } + sumRequiredDecimal(): this { + return this.sumRequiredDecimalAs("sumOfRequiredDecimal"); + } + + sumRequiredDecimalAs(retName: string): this { + this.query.aggregate("sum", "requiredDecimal", retName); + return this; + } + avgRequiredDecimal(): this { + return this.avgRequiredDecimalAs("avgOfRequiredDecimal"); + } + + avgRequiredDecimalAs(retName: string): this { + this.query.aggregate("avg", "requiredDecimal", retName); + return this; + } + standardDeviationRequiredDecimal(): this { + return this.standardDeviationRequiredDecimalAs("standardDeviationOfRequiredDecimal"); + } + + standardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev", "requiredDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimal(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDecimalAs("squareRootOfPopulationStandardDeviationOfRequiredDecimal"); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDecimal", retName); + return this; + } + sampleVarianceRequiredDecimal(): this { + return this.sampleVarianceRequiredDecimalAs("sampleVarianceOfRequiredDecimal"); + } + + sampleVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDecimal", retName); + return this; + } + samplePopulationVarianceRequiredDecimal(): this { + return this.samplePopulationVarianceRequiredDecimalAs("samplePopulationVarianceOfRequiredDecimal"); + } + + samplePopulationVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDecimal", retName); + return this; + } + minOptionalDecimal(): this { + return this.minOptionalDecimalAs("minOfOptionalDecimal"); + } + + minOptionalDecimalAs(retName: string): this { + this.query.aggregate("min", "optionalDecimal", retName); + return this; + } + maxOptionalDecimal(): this { + return this.maxOptionalDecimalAs("maxOfOptionalDecimal"); + } + + maxOptionalDecimalAs(retName: string): this { + this.query.aggregate("max", "optionalDecimal", retName); + return this; + } + sumOptionalDecimal(): this { + return this.sumOptionalDecimalAs("sumOfOptionalDecimal"); + } + + sumOptionalDecimalAs(retName: string): this { + this.query.aggregate("sum", "optionalDecimal", retName); + return this; + } + avgOptionalDecimal(): this { + return this.avgOptionalDecimalAs("avgOfOptionalDecimal"); + } + + avgOptionalDecimalAs(retName: string): this { + this.query.aggregate("avg", "optionalDecimal", retName); + return this; + } + standardDeviationOptionalDecimal(): this { + return this.standardDeviationOptionalDecimalAs("standardDeviationOfOptionalDecimal"); + } + + standardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev", "optionalDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimal(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDecimalAs("squareRootOfPopulationStandardDeviationOfOptionalDecimal"); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDecimal", retName); + return this; + } + sampleVarianceOptionalDecimal(): this { + return this.sampleVarianceOptionalDecimalAs("sampleVarianceOfOptionalDecimal"); + } + + sampleVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDecimal", retName); + return this; + } + samplePopulationVarianceOptionalDecimal(): this { + return this.samplePopulationVarianceOptionalDecimalAs("samplePopulationVarianceOfOptionalDecimal"); + } + + samplePopulationVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDecimal", retName); + return this; + } + minRequiredFloat(): this { + return this.minRequiredFloatAs("minOfRequiredFloat"); + } + + minRequiredFloatAs(retName: string): this { + this.query.aggregate("min", "requiredFloat", retName); + return this; + } + maxRequiredFloat(): this { + return this.maxRequiredFloatAs("maxOfRequiredFloat"); + } + + maxRequiredFloatAs(retName: string): this { + this.query.aggregate("max", "requiredFloat", retName); + return this; + } + sumRequiredFloat(): this { + return this.sumRequiredFloatAs("sumOfRequiredFloat"); + } + + sumRequiredFloatAs(retName: string): this { + this.query.aggregate("sum", "requiredFloat", retName); + return this; + } + avgRequiredFloat(): this { + return this.avgRequiredFloatAs("avgOfRequiredFloat"); + } + + avgRequiredFloatAs(retName: string): this { + this.query.aggregate("avg", "requiredFloat", retName); + return this; + } + standardDeviationRequiredFloat(): this { + return this.standardDeviationRequiredFloatAs("standardDeviationOfRequiredFloat"); + } + + standardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev", "requiredFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloat(): this { + return this.squareRootOfPopulationStandardDeviationRequiredFloatAs("squareRootOfPopulationStandardDeviationOfRequiredFloat"); + } + + squareRootOfPopulationStandardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredFloat", retName); + return this; + } + sampleVarianceRequiredFloat(): this { + return this.sampleVarianceRequiredFloatAs("sampleVarianceOfRequiredFloat"); + } + + sampleVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_samp", "requiredFloat", retName); + return this; + } + samplePopulationVarianceRequiredFloat(): this { + return this.samplePopulationVarianceRequiredFloatAs("samplePopulationVarianceOfRequiredFloat"); + } + + samplePopulationVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_pop", "requiredFloat", retName); + return this; + } + minOptionalFloat(): this { + return this.minOptionalFloatAs("minOfOptionalFloat"); + } + + minOptionalFloatAs(retName: string): this { + this.query.aggregate("min", "optionalFloat", retName); + return this; + } + maxOptionalFloat(): this { + return this.maxOptionalFloatAs("maxOfOptionalFloat"); + } + + maxOptionalFloatAs(retName: string): this { + this.query.aggregate("max", "optionalFloat", retName); + return this; + } + sumOptionalFloat(): this { + return this.sumOptionalFloatAs("sumOfOptionalFloat"); + } + + sumOptionalFloatAs(retName: string): this { + this.query.aggregate("sum", "optionalFloat", retName); + return this; + } + avgOptionalFloat(): this { + return this.avgOptionalFloatAs("avgOfOptionalFloat"); + } + + avgOptionalFloatAs(retName: string): this { + this.query.aggregate("avg", "optionalFloat", retName); + return this; + } + standardDeviationOptionalFloat(): this { + return this.standardDeviationOptionalFloatAs("standardDeviationOfOptionalFloat"); + } + + standardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev", "optionalFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloat(): this { + return this.squareRootOfPopulationStandardDeviationOptionalFloatAs("squareRootOfPopulationStandardDeviationOfOptionalFloat"); + } + + squareRootOfPopulationStandardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalFloat", retName); + return this; + } + sampleVarianceOptionalFloat(): this { + return this.sampleVarianceOptionalFloatAs("sampleVarianceOfOptionalFloat"); + } + + sampleVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_samp", "optionalFloat", retName); + return this; + } + samplePopulationVarianceOptionalFloat(): this { + return this.samplePopulationVarianceOptionalFloatAs("samplePopulationVarianceOfOptionalFloat"); + } + + samplePopulationVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_pop", "optionalFloat", retName); + return this; + } + minRequiredDouble(): this { + return this.minRequiredDoubleAs("minOfRequiredDouble"); + } + + minRequiredDoubleAs(retName: string): this { + this.query.aggregate("min", "requiredDouble", retName); + return this; + } + maxRequiredDouble(): this { + return this.maxRequiredDoubleAs("maxOfRequiredDouble"); + } + + maxRequiredDoubleAs(retName: string): this { + this.query.aggregate("max", "requiredDouble", retName); + return this; + } + sumRequiredDouble(): this { + return this.sumRequiredDoubleAs("sumOfRequiredDouble"); + } + + sumRequiredDoubleAs(retName: string): this { + this.query.aggregate("sum", "requiredDouble", retName); + return this; + } + avgRequiredDouble(): this { + return this.avgRequiredDoubleAs("avgOfRequiredDouble"); + } + + avgRequiredDoubleAs(retName: string): this { + this.query.aggregate("avg", "requiredDouble", retName); + return this; + } + standardDeviationRequiredDouble(): this { + return this.standardDeviationRequiredDoubleAs("standardDeviationOfRequiredDouble"); + } + + standardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev", "requiredDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDouble(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDoubleAs("squareRootOfPopulationStandardDeviationOfRequiredDouble"); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDouble", retName); + return this; + } + sampleVarianceRequiredDouble(): this { + return this.sampleVarianceRequiredDoubleAs("sampleVarianceOfRequiredDouble"); + } + + sampleVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDouble", retName); + return this; + } + samplePopulationVarianceRequiredDouble(): this { + return this.samplePopulationVarianceRequiredDoubleAs("samplePopulationVarianceOfRequiredDouble"); + } + + samplePopulationVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDouble", retName); + return this; + } + minOptionalDouble(): this { + return this.minOptionalDoubleAs("minOfOptionalDouble"); + } + + minOptionalDoubleAs(retName: string): this { + this.query.aggregate("min", "optionalDouble", retName); + return this; + } + maxOptionalDouble(): this { + return this.maxOptionalDoubleAs("maxOfOptionalDouble"); + } + + maxOptionalDoubleAs(retName: string): this { + this.query.aggregate("max", "optionalDouble", retName); + return this; + } + sumOptionalDouble(): this { + return this.sumOptionalDoubleAs("sumOfOptionalDouble"); + } + + sumOptionalDoubleAs(retName: string): this { + this.query.aggregate("sum", "optionalDouble", retName); + return this; + } + avgOptionalDouble(): this { + return this.avgOptionalDoubleAs("avgOfOptionalDouble"); + } + + avgOptionalDoubleAs(retName: string): this { + this.query.aggregate("avg", "optionalDouble", retName); + return this; + } + standardDeviationOptionalDouble(): this { + return this.standardDeviationOptionalDoubleAs("standardDeviationOfOptionalDouble"); + } + + standardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev", "optionalDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDouble(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDoubleAs("squareRootOfPopulationStandardDeviationOfOptionalDouble"); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDouble", retName); + return this; + } + sampleVarianceOptionalDouble(): this { + return this.sampleVarianceOptionalDoubleAs("sampleVarianceOfOptionalDouble"); + } + + sampleVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDouble", retName); + return this; + } + samplePopulationVarianceOptionalDouble(): this { + return this.samplePopulationVarianceOptionalDoubleAs("samplePopulationVarianceOfOptionalDouble"); + } + + samplePopulationVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDouble", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByTypePlatform(): this { + this.query.groupBy("typePlatform"); + return this; + } + + groupByTypePlatformAs(retName: string): this { + this.query.groupBy("typePlatform", retName); + return this; + } + groupByRequiredString(): this { + this.query.groupBy("requiredString"); + return this; + } + + groupByRequiredStringAs(retName: string): this { + this.query.groupBy("requiredString", retName); + return this; + } + groupByOptionalString(): this { + this.query.groupBy("optionalString"); + return this; + } + + groupByOptionalStringAs(retName: string): this { + this.query.groupBy("optionalString", retName); + return this; + } + groupByLargeText(): this { + this.query.groupBy("largeText"); + return this; + } + + groupByLargeTextAs(retName: string): this { + this.query.groupBy("largeText", retName); + return this; + } + groupByRequiredBoolean(): this { + this.query.groupBy("requiredBoolean"); + return this; + } + + groupByRequiredBooleanAs(retName: string): this { + this.query.groupBy("requiredBoolean", retName); + return this; + } + groupByOptionalBoolean(): this { + this.query.groupBy("optionalBoolean"); + return this; + } + + groupByOptionalBooleanAs(retName: string): this { + this.query.groupBy("optionalBoolean", retName); + return this; + } + groupByRequiredInteger(): this { + this.query.groupBy("requiredInteger"); + return this; + } + + groupByRequiredIntegerAs(retName: string): this { + this.query.groupBy("requiredInteger", retName); + return this; + } + groupByOptionalInteger(): this { + this.query.groupBy("optionalInteger"); + return this; + } + + groupByOptionalIntegerAs(retName: string): this { + this.query.groupBy("optionalInteger", retName); + return this; + } + groupByRequiredLong(): this { + this.query.groupBy("requiredLong"); + return this; + } + + groupByRequiredLongAs(retName: string): this { + this.query.groupBy("requiredLong", retName); + return this; + } + groupByOptionalLong(): this { + this.query.groupBy("optionalLong"); + return this; + } + + groupByOptionalLongAs(retName: string): this { + this.query.groupBy("optionalLong", retName); + return this; + } + groupByRequiredDecimal(): this { + this.query.groupBy("requiredDecimal"); + return this; + } + + groupByRequiredDecimalAs(retName: string): this { + this.query.groupBy("requiredDecimal", retName); + return this; + } + groupByOptionalDecimal(): this { + this.query.groupBy("optionalDecimal"); + return this; + } + + groupByOptionalDecimalAs(retName: string): this { + this.query.groupBy("optionalDecimal", retName); + return this; + } + groupByRequiredFloat(): this { + this.query.groupBy("requiredFloat"); + return this; + } + + groupByRequiredFloatAs(retName: string): this { + this.query.groupBy("requiredFloat", retName); + return this; + } + groupByOptionalFloat(): this { + this.query.groupBy("optionalFloat"); + return this; + } + + groupByOptionalFloatAs(retName: string): this { + this.query.groupBy("optionalFloat", retName); + return this; + } + groupByRequiredDouble(): this { + this.query.groupBy("requiredDouble"); + return this; + } + + groupByRequiredDoubleAs(retName: string): this { + this.query.groupBy("requiredDouble", retName); + return this; + } + groupByOptionalDouble(): this { + this.query.groupBy("optionalDouble"); + return this; + } + + groupByOptionalDoubleAs(retName: string): this { + this.query.groupBy("optionalDouble", retName); + return this; + } + groupByRequiredDate(): this { + this.query.groupBy("requiredDate"); + return this; + } + + groupByRequiredDateAs(retName: string): this { + this.query.groupBy("requiredDate", retName); + return this; + } + groupByOptionalDate(): this { + this.query.groupBy("optionalDate"); + return this; + } + + groupByOptionalDateAs(retName: string): this { + this.query.groupBy("optionalDate", retName); + return this; + } + groupByRequiredTime(): this { + this.query.groupBy("requiredTime"); + return this; + } + + groupByRequiredTimeAs(retName: string): this { + this.query.groupBy("requiredTime", retName); + return this; + } + groupByOptionalTime(): this { + this.query.groupBy("optionalTime"); + return this; + } + + groupByOptionalTimeAs(retName: string): this { + this.query.groupBy("optionalTime", retName); + return this; + } + groupByRequiredDatetime(): this { + this.query.groupBy("requiredDatetime"); + return this; + } + + groupByRequiredDatetimeAs(retName: string): this { + this.query.groupBy("requiredDatetime", retName); + return this; + } + groupByOptionalDatetime(): this { + this.query.groupBy("optionalDatetime"); + return this; + } + + groupByOptionalDatetimeAs(retName: string): this { + this.query.groupBy("optionalDatetime", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByTypePlatformAs( + facetName: string, + request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "typePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByTypePlatformAs", relation: "typePlatform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof ScalarTypeProbe + ? entity + : ScalarTypeProbe.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableScalarTypeProbeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return ScalarTypeProbe.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/TypePlatformRequest.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/TypePlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d0caed3d9719c20a917e89fdcad7bad64597fb0 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/generated/requests/TypePlatformRequest.ts @@ -0,0 +1,1736 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { TypePlatform } from '../models/TypePlatform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class TypePlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("TypePlatform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TypePlatform" { + return "TypePlatform"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTypePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableTypePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectScalarTypeProbeListWith(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "scalarTypeProbeList", request.toQuery(), "id", "typePlatform", true, + { kind: "relation-select", method: "selectScalarTypeProbeListWith", relation: "scalarTypeProbeList" }); + return this; + } + + haveScalarTypeProbes(): this { + return this.withScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + haveNoScalarTypeProbes(): this { + return this.withoutScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + withScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + withoutScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + countScalarTypeProbes(): this { + return this.countScalarTypeProbesAs("countScalarTypeProbes"); + } + + countScalarTypeProbesAs(alias: string): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + this.countScalarTypeProbesWith(alias, { entityName: "ScalarTypeProbe", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }; + return this; + } + + countScalarTypeProbesWith(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "relation-count", method: "countScalarTypeProbesWith", relation: "scalarTypeProbeList", alias }); + return this; + } + + minRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredIntegerOfScalarTypeProbesAs( + "minOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredIntegerOfScalarTypeProbesAs( + "maxOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredIntegerOfScalarTypeProbesAs( + "sumOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredIntegerOfScalarTypeProbesAs( + "avgOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredIntegerOfScalarTypeProbesAs( + "standardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredIntegerOfScalarTypeProbesAs( + "sampleVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalIntegerOfScalarTypeProbesAs( + "minOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalIntegerOfScalarTypeProbesAs( + "maxOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalIntegerOfScalarTypeProbesAs( + "sumOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalIntegerOfScalarTypeProbesAs( + "avgOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalIntegerOfScalarTypeProbesAs( + "standardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalIntegerOfScalarTypeProbesAs( + "sampleVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredLongOfScalarTypeProbesAs( + "minOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredLongOfScalarTypeProbesAs( + "maxOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredLongOfScalarTypeProbesAs( + "sumOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredLongOfScalarTypeProbesAs( + "avgOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredLongOfScalarTypeProbesAs( + "standardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredLongOfScalarTypeProbesAs( + "sampleVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalLongOfScalarTypeProbesAs( + "minOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalLongOfScalarTypeProbesAs( + "maxOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalLongOfScalarTypeProbesAs( + "sumOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalLongOfScalarTypeProbesAs( + "avgOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalLongOfScalarTypeProbesAs( + "standardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalLongOfScalarTypeProbesAs( + "sampleVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDecimalOfScalarTypeProbesAs( + "minOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDecimalOfScalarTypeProbesAs( + "maxOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDecimalOfScalarTypeProbesAs( + "sumOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDecimalOfScalarTypeProbesAs( + "avgOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDecimalOfScalarTypeProbesAs( + "standardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDecimalOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDecimalOfScalarTypeProbesAs( + "minOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDecimalOfScalarTypeProbesAs( + "maxOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDecimalOfScalarTypeProbesAs( + "sumOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDecimalOfScalarTypeProbesAs( + "avgOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDecimalOfScalarTypeProbesAs( + "standardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDecimalOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredFloatOfScalarTypeProbesAs( + "minOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredFloatOfScalarTypeProbesAs( + "maxOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredFloatOfScalarTypeProbesAs( + "sumOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredFloatOfScalarTypeProbesAs( + "avgOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredFloatOfScalarTypeProbesAs( + "standardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredFloatOfScalarTypeProbesAs( + "sampleVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalFloatOfScalarTypeProbesAs( + "minOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalFloatOfScalarTypeProbesAs( + "maxOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalFloatOfScalarTypeProbesAs( + "sumOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalFloatOfScalarTypeProbesAs( + "avgOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalFloatOfScalarTypeProbesAs( + "standardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalFloatOfScalarTypeProbesAs( + "sampleVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDoubleOfScalarTypeProbesAs( + "minOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDoubleOfScalarTypeProbesAs( + "maxOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDoubleOfScalarTypeProbesAs( + "sumOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDoubleOfScalarTypeProbesAs( + "avgOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDoubleOfScalarTypeProbesAs( + "standardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDoubleOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDoubleOfScalarTypeProbesAs( + "minOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDoubleOfScalarTypeProbesAs( + "maxOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDoubleOfScalarTypeProbesAs( + "sumOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDoubleOfScalarTypeProbesAs( + "avgOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDoubleOfScalarTypeProbesAs( + "standardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDoubleOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TypePlatform + ? entity + : TypePlatform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTypePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TypePlatform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/runtime-module.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c4f061abab6174cf25a15f41f2a3367792bb284 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/runtime-module.ts @@ -0,0 +1,128 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "TypePlatform": Object.freeze({ + entityType: "TypePlatform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "ScalarTypeProbe": Object.freeze({ + entityType: "ScalarTypeProbe", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "type_platform": Object.freeze({ canonicalName: "type_platform", wireName: "typePlatform", aliases: Object.freeze([] as string[]) }), + "required_string": Object.freeze({ canonicalName: "required_string", wireName: "requiredString", aliases: Object.freeze([] as string[]) }), + "optional_string": Object.freeze({ canonicalName: "optional_string", wireName: "optionalString", aliases: Object.freeze([] as string[]) }), + "large_text": Object.freeze({ canonicalName: "large_text", wireName: "largeText", aliases: Object.freeze([] as string[]) }), + "required_boolean": Object.freeze({ canonicalName: "required_boolean", wireName: "requiredBoolean", aliases: Object.freeze([] as string[]) }), + "optional_boolean": Object.freeze({ canonicalName: "optional_boolean", wireName: "optionalBoolean", aliases: Object.freeze([] as string[]) }), + "required_integer": Object.freeze({ canonicalName: "required_integer", wireName: "requiredInteger", aliases: Object.freeze([] as string[]) }), + "optional_integer": Object.freeze({ canonicalName: "optional_integer", wireName: "optionalInteger", aliases: Object.freeze([] as string[]) }), + "required_long": Object.freeze({ canonicalName: "required_long", wireName: "requiredLong", aliases: Object.freeze([] as string[]) }), + "optional_long": Object.freeze({ canonicalName: "optional_long", wireName: "optionalLong", aliases: Object.freeze([] as string[]) }), + "required_decimal": Object.freeze({ canonicalName: "required_decimal", wireName: "requiredDecimal", aliases: Object.freeze([] as string[]) }), + "optional_decimal": Object.freeze({ canonicalName: "optional_decimal", wireName: "optionalDecimal", aliases: Object.freeze([] as string[]) }), + "required_float": Object.freeze({ canonicalName: "required_float", wireName: "requiredFloat", aliases: Object.freeze([] as string[]) }), + "optional_float": Object.freeze({ canonicalName: "optional_float", wireName: "optionalFloat", aliases: Object.freeze([] as string[]) }), + "required_double": Object.freeze({ canonicalName: "required_double", wireName: "requiredDouble", aliases: Object.freeze([] as string[]) }), + "optional_double": Object.freeze({ canonicalName: "optional_double", wireName: "optionalDouble", aliases: Object.freeze([] as string[]) }), + "required_date": Object.freeze({ canonicalName: "required_date", wireName: "requiredDate", aliases: Object.freeze([] as string[]) }), + "optional_date": Object.freeze({ canonicalName: "optional_date", wireName: "optionalDate", aliases: Object.freeze([] as string[]) }), + "required_time": Object.freeze({ canonicalName: "required_time", wireName: "requiredTime", aliases: Object.freeze([] as string[]) }), + "optional_time": Object.freeze({ canonicalName: "optional_time", wireName: "optionalTime", aliases: Object.freeze([] as string[]) }), + "required_datetime": Object.freeze({ canonicalName: "required_datetime", wireName: "requiredDatetime", aliases: Object.freeze([] as string[]) }), + "optional_datetime": Object.freeze({ canonicalName: "optional_datetime", wireName: "optionalDatetime", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "TypePlatform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "ScalarTypeProbe": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["type_platform"] === undefined) || mutation.payload["type_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("type_platform") }); + + if ((mutation.action === "Create" && mutation.payload["required_string"] === undefined) || mutation.payload["required_string"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_string") }); + if (mutation.payload["required_string"] != null && [...String(mutation.payload["required_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("required_string"), inputValue: mutation.payload["required_string"], systemValue: 100 }); + + if (mutation.payload["optional_string"] != null && [...String(mutation.payload["optional_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("optional_string"), inputValue: mutation.payload["optional_string"], systemValue: 100 }); + + + if ((mutation.action === "Create" && mutation.payload["required_boolean"] === undefined) || mutation.payload["required_boolean"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_boolean") }); + + + if ((mutation.action === "Create" && mutation.payload["required_integer"] === undefined) || mutation.payload["required_integer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_integer") }); + + + if ((mutation.action === "Create" && mutation.payload["required_long"] === undefined) || mutation.payload["required_long"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_long") }); + + + if ((mutation.action === "Create" && mutation.payload["required_decimal"] === undefined) || mutation.payload["required_decimal"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_decimal") }); + + + if ((mutation.action === "Create" && mutation.payload["required_float"] === undefined) || mutation.payload["required_float"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_float") }); + + + if ((mutation.action === "Create" && mutation.payload["required_double"] === undefined) || mutation.payload["required_double"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_double") }); + + + if ((mutation.action === "Create" && mutation.payload["required_date"] === undefined) || mutation.payload["required_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_date") }); + + + if ((mutation.action === "Create" && mutation.payload["required_time"] === undefined) || mutation.payload["required_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_time") }); + + + if ((mutation.action === "Create" && mutation.payload["required_datetime"] === undefined) || mutation.payload["required_datetime"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_datetime") }); + + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "TypePlatform", id: "1", values: { "name": "Scalar Type Conformance" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sql.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f5d108d228a1dbec1140e735022c1d72d704eb6 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"TypePlatform": { + table: "type_platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"scalarTypeProbeList": { targetEntity: "ScalarTypeProbe", localKey: "id", foreignKey: "typePlatform", many: true }} +}, +"ScalarTypeProbe": { + table: "scalar_type_probe_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "typePlatform": { columnName: "type_platform", modelName: "type_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "requiredString": { columnName: "required_string", modelName: "required_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "optionalString": { columnName: "optional_string", modelName: "optional_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "largeText": { columnName: "large_text", modelName: "large_text", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "requiredBoolean": { columnName: "required_boolean", modelName: "required_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "optionalBoolean": { columnName: "optional_boolean", modelName: "optional_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: true }, "requiredInteger": { columnName: "required_integer", modelName: "required_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "optionalInteger": { columnName: "optional_integer", modelName: "optional_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: true, integer32: true }, "requiredLong": { columnName: "required_long", modelName: "required_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: false }, "optionalLong": { columnName: "optional_long", modelName: "optional_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: true }, "requiredDecimal": { columnName: "required_decimal", modelName: "required_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "optionalDecimal": { columnName: "optional_decimal", modelName: "optional_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: true }, "requiredFloat": { columnName: "required_float", modelName: "required_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalFloat": { columnName: "optional_float", modelName: "optional_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDouble": { columnName: "required_double", modelName: "required_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalDouble": { columnName: "optional_double", modelName: "optional_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDate": { columnName: "required_date", modelName: "required_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "optionalDate": { columnName: "optional_date", modelName: "optional_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: true }, "requiredTime": { columnName: "required_time", modelName: "required_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: false }, "optionalTime": { columnName: "optional_time", modelName: "optional_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: true }, "requiredDatetime": { columnName: "required_datetime", modelName: "required_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "optionalDatetime": { columnName: "optional_datetime", modelName: "optional_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: true }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"typePlatform": { targetEntity: "TypePlatform", localKey: "typePlatform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-ts.ts b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/teaql-i18n.json b/source/teaql-ts/examples/scalar-type-probe/generated/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..9bccc83b0cb5f837bc4c9ee6a49415974e1a4d50 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/teaql-i18n.json @@ -0,0 +1,127 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.scalarTypeProbe.largeText": "Large Text", + "property.scalarTypeProbe.requiredString": "Required String", + "property.scalarTypeProbe.id": "Id", + "property.scalarTypeProbe.optionalDecimal": "Optional Decimal", + "property.scalarTypeProbe.requiredDate": "Required Date", + "property.scalarTypeProbe.optionalString": "Optional String", + "property.scalarTypeProbe.requiredLong": "Required Long", + "property.typePlatform.version": "Version", + "entity.scalarTypeProbe": "Scalar Type Probe", + "property.scalarTypeProbe.optionalTime": "Optional Time", + "property.scalarTypeProbe.typePlatform": "Type Platform", + "property.scalarTypeProbe.optionalLong": "Optional Long", + "property.scalarTypeProbe.requiredDatetime": "Required Datetime", + "property.scalarTypeProbe.requiredTime": "Required Time", + "property.scalarTypeProbe.optionalBoolean": "Optional Boolean", + "property.scalarTypeProbe.optionalInteger": "Optional Integer", + "property.scalarTypeProbe.requiredDouble": "Required Double", + "entity.typePlatform": "Type Platform", + "property.scalarTypeProbe.requiredInteger": "Required Integer", + "property.scalarTypeProbe.optionalDouble": "Optional Double", + "property.scalarTypeProbe.optionalDatetime": "Optional Datetime", + "property.scalarTypeProbe.createTime": "Create Time", + "property.scalarTypeProbe.requiredFloat": "Required Float", + "property.typePlatform.id": "Id", + "property.scalarTypeProbe.requiredDecimal": "Required Decimal", + "property.scalarTypeProbe.optionalFloat": "Optional Float", + "property.scalarTypeProbe.version": "Version", + "property.scalarTypeProbe.requiredBoolean": "Required Boolean", + "property.scalarTypeProbe.updateTime": "Update Time", + "property.typePlatform.name": "Name", + "property.scalarTypeProbe.optionalDate": "Optional Date" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/generated/tsconfig.json b/source/teaql-ts/examples/scalar-type-probe/generated/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/generated/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/scalar-type-probe/integer32.test.ts b/source/teaql-ts/examples/scalar-type-probe/integer32.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a784a535c099c62199cfe5fbce3124319359a6a4 --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/integer32.test.ts @@ -0,0 +1,119 @@ +import {internalId} from 'teaql-ts'; +// Application-owned generated Q/E/Mutation acceptance; spellings come from +// main.test.ts and the retained file-client Checker probe, not source discovery. +import {Q} from 'scalar-lib/generated/Q'; +import {E,TeaQLNotLoadedError} from 'scalar-lib/generated/E'; +import {ScalarTypeProbe} from 'scalar-lib/generated/models/ScalarTypeProbe'; +import {SQLiteTeaQLClient} from 'scalar-lib/teaql-node-sqlite'; +import {TeaQLClient} from 'scalar-lib/teaql-ts'; +import {GENERATED_RUNTIME_MODULE} from 'scalar-lib/runtime-module'; +import {CheckException,EntityChecker,FixedBusinessClock,RuntimeModule,UserContext,decimal,long,localTime} from 'teaql-ts'; +import {dirname,join} from 'node:path'; +import {readFileSync,writeFileSync} from 'node:fs'; + +async function prepare(context:UserContext,name:string){ + const root=await Q.typePlatforms().withIdIs(String(context.requireActiveRoot('TypePlatform').id)).limit(1).comment('reuse width-test root').purpose('prepare modeled Integer acceptance').executeForOne(context); + if(!root)throw Error('seeded root missing'); + return (await Q.scalarTypeProbes().comment('prepare one complete width-test entity').purpose('verify modeled Integer through generated APIs').newEntity(context)) + .updateTypePlatform(root).updateRequiredString(name).updateRequiredBoolean(true).updateRequiredInteger(7).updateOptionalInteger(null) + .updateRequiredLong(long('9223372036854775807')).updateRequiredDecimal(decimal('1.00')) + .updateRequiredFloat(1.25).updateRequiredDouble(2.5).updateRequiredDate('2024-02-29') + .updateRequiredTime(localTime('12:34:56')).updateRequiredDatetime('2024-02-29T12:34:56.789Z'); +} +async function load(context:UserContext,id:string){ + const row=await Q.scalarTypeProbes().withIdIs(id).limit(1).comment('reload exact width-test entity').purpose('verify immutable value and version').executeForOne(context); + if(!row)throw Error('saved width-test row missing');return row; +} +function precise(error:unknown,field:string){ + expect(error).toBeInstanceOf(CheckException); + expect((error as CheckException).violations.some(v=>v.ruleId==='invalid_type'&&v.entityType==='ScalarTypeProbe'&&v.location.modelPath()===field)).toBe(true); +} +for(const backend of ['sqlite','file'] as const)test(`generated Integer32 ${backend} save Fix native JSON and E`,async()=>{ + const base=process.env.TEAQL_FULL_SCALAR_DB,round=Number(process.env.TEAQL_INTEGER32_ROUND); + if(!base||![1,2].includes(round))throw Error('explicit retained scalar database and width round required'); + const file=join(dirname(base),'integer32-'+backend+(backend==='sqlite'?'.sqlite':'.json')); + const context=new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30.125Z'))); + const client=backend==='sqlite'?new SQLiteTeaQLClient(file).setUserContext(context) + :new TeaQLClient(file).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService',client);const native=client as any; + native.setQueryLoggingEnabled?.(false);native.setMutationLoggingEnabled?.(false); + const cases:Array<{name:string;passed:true;zeroEffects?:boolean;fixCalls?:number}>=[],prefix=`integer32-${backend}-round-${round}`; + const record=(name:string,other:Record={})=>cases.push({name,passed:true,...other}); + try{ + await context.ensureSchema(); + let control=await prepare(context,prefix+'-control');await control.auditAs('persist a complete generated width control').save(context); + const id=control.id!; + const providers=backend==='sqlite'?[jest.spyOn(native.driver,'query'),jest.spyOn(native.driver,'transaction'),jest.spyOn(native.driver,'nextId'),jest.spyOn(native.driver,'ensureIdFloor')] + :[jest.spyOn(native,'persist')]; + const initial=await load(context,id);expect(E.scalarTypeProbe(initial).requiredLong().eval()).toBe('9223372036854775807'); + const mutation=(row:ScalarTypeProbe,field:string,value:number)=>field==='required_integer'?row.updateRequiredInteger(value):row.updateOptionalInteger(value); + for(const field of ['required_integer','optional_integer'])for(const [bound,value]of [['below',-2147483649],['above',2147483648]] as const){ + for(const update of [false,true]){ + let row=update?await load(context,id):await prepare(context,prefix+'-invalid-'+field+'-'+bound);mutation(row,field,value); + const key={entity:'ScalarTypeProbe',id:(row as any)._ledgerId},pending=JSON.stringify((row as any)._root.change(key)),audits=native.auditTrace.length; + providers.forEach(p=>p.mockClear());let failure:unknown; + try{await row.auditAs('reject invalid Integer before provider work').save(context);}catch(error){failure=error;} + precise(failure,field);providers.forEach(p=>expect(p).not.toHaveBeenCalled());expect(native.auditTrace.length).toBe(audits); + expect(JSON.stringify((row as any)._root.change(key))).toBe(pending); + record(`${update?'update':'create'}-${field}-${bound}`,{zeroEffects:true}); + row=await load(context,id);expect(row.version).toBe(1);expect(E.scalarTypeProbe(row).requiredInteger().eval()).toBe(7);expect(E.scalarTypeProbe(row).optionalInteger().eval()).toBeNull(); + } + for(const update of [false,true]){ + const generated=GENERATED_RUNTIME_MODULE.checkers.ScalarTypeProbe;let calls=0; + const checker:EntityChecker={checkAndFix(c,m,r){calls++;generated.checkAndFix(c,m,r);m.payload[field]=value;}}; + native.install(new RuntimeModule({}, {ScalarTypeProbe:checker})); + const row=update?await load(context,id):await prepare(context,prefix+'-fix-'+field+'-'+bound); + mutation(row,field,8);const key={entity:'ScalarTypeProbe',id:(row as any)._ledgerId},pending=JSON.stringify((row as any)._root.change(key)); + providers.forEach(p=>p.mockClear());let failure:unknown; + try{await row.auditAs('reject a final Fix outside the model domain').save(context);}catch(error){failure=error;} + precise(failure,field);expect(calls).toBe(1);providers.forEach(p=>expect(p).not.toHaveBeenCalled()); + expect(JSON.stringify((row as any)._root.change(key))).toBe(pending); + record(`fix-${update?'update':'create'}-${field}-${bound}`,{zeroEffects:true,fixCalls:calls}); + native.install(new RuntimeModule({}, {ScalarTypeProbe:generated})); + } + expect(()=>ScalarTypeProbe.fromRecord({id:'9',version:1,[field==='required_integer'?'requiredInteger':'optionalInteger']:value})).toThrow(CheckException); + record(`construct-${field}-${bound}`); + const invalid=await load(context,id);mutation(invalid,field,value); + for(const terminal of ['eval','present','fallback','json']){ + let failure:unknown; + try{if(terminal==='json')JSON.stringify(invalid);else{ + const expression=field==='required_integer'?E.scalarTypeProbe(invalid).requiredInteger():E.scalarTypeProbe(invalid).optionalInteger(); + if(terminal==='eval')expression.eval();else if(terminal==='present')expression.isPresent();else expression.orElse(123); + }}catch(error){failure=error;} + precise(failure,field);record(`${terminal}-${field}-${bound}`); + } + } + const generated=GENERATED_RUNTIME_MODULE.checkers.ScalarTypeProbe;let calls=0; + native.install(new RuntimeModule({}, {ScalarTypeProbe:{checkAndFix(c,m,r){calls++;m.payload.required_integer=2147483647;generated.checkAndFix(c,m,r);}}})); + control=await load(context,id);control.updateRequiredInteger(2147483648);await control.auditAs('repair Integer once before final model admission').save(context); + expect(calls).toBe(1);expect(control.version).toBe(2);expect(E.scalarTypeProbe(control).requiredInteger().eval()).toBe(2147483647); + native.install(new RuntimeModule({}, {ScalarTypeProbe:generated}));record('one-valid-repair',{fixCalls:calls}); + const partial=await Q.scalarTypeProbesWithMinimalFields().withIdIs(id).limit(1).comment('omit modeled Integer deliberately').purpose('retain NotLoaded semantics').executeForOne(context); + expect(partial).toBeDefined();expect(()=>E.scalarTypeProbe(partial!).requiredInteger().eval()).toThrow(TeaQLNotLoadedError);record('partial-not-loaded'); + expect(E.scalarTypeProbe(await load(context,id)).requiredLong().eval()).toBe('9223372036854775807');record('wide-long-and-version'); + providers.forEach(p=>p.mockRestore()); + const legacy:Array<{id:string;field:string;fault:string;value:unknown}>=[]; + for(const field of ['required_integer','optional_integer'])for(const [fault,value]of [['below',-2147483649],['above',2147483648],['fraction',1.5],['text','PRIVATE-INTEGER-INPUT']] as const){ + const row=await prepare(context,`${prefix}-legacy-${field}-${fault}`);await row.auditAs('prepare valid row before explicit legacy corruption').save(context); + legacy.push({id:row.id!,field,fault,value}); + } + // Deliberately bypass domain validation only for test-owned corruption. + // Create all rows first, so a later ordinary persist cannot erase a fault. + if(backend==='sqlite')for(const fault of legacy)await native.driver.query(`UPDATE scalar_type_probe_data SET ${fault.field} = ? WHERE id = ?`,[fault.value,fault.id]); + else{ + const state=JSON.parse(readFileSync(file,'utf8')); + for(const fault of legacy)state.data.ScalarTypeProbe[fault.id][fault.field]=fault.value; + writeFileSync(file,JSON.stringify(state)); + const reader=new TeaQLClient(file).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService',reader); + } + for(const fault of legacy){ + let failure:unknown;try{await load(context,fault.id);}catch(error){failure=error;}precise(failure,fault.field);record(`legacy-${fault.field}-${fault.fault}`); + const projected=await Q.scalarTypeProbesWithMinimalFields().withIdIs(internalId(fault.id)).limit(1).comment('omit corrupt Integer deliberately').purpose('verify safe projected reads remain NotLoaded').executeForOne(context); + expect(projected?.id).toBe(fault.id);expect(projected?.version).toBe(1); + expect(()=>E.scalarTypeProbe(projected!).requiredInteger().eval()).toThrow(TeaQLNotLoadedError);record(`legacy-projection-${fault.field}-${fault.fault}`); + } + process.stdout.write('TYPESCRIPT_INTEGER32='+JSON.stringify({language:'typescript',backend,round,passed:true,id,cases,legacy,controlVersion:2,controlLong:'9223372036854775807',file, + bootstrapMode:'context.ensureSchema',automaticBootstrapAccepted:true})+'\n'); + }finally{if(backend==='sqlite')await (client as SQLiteTeaQLClient).close();} +},30000); diff --git a/source/teaql-ts/examples/scalar-type-probe/main.test.ts b/source/teaql-ts/examples/scalar-type-probe/main.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2db17f8da00bb571fb41f73f3b1763e9c296155e --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/main.test.ts @@ -0,0 +1,240 @@ +// Application-owned acceptance. API spellings follow the existing +// TypescriptGeneratedCompileTest canonical scalar consumer, not generated-source discovery. +import {Q} from 'scalar-lib/generated/Q'; +import {E, TeaQLNotLoadedError} from 'scalar-lib/generated/E'; +import {ScalarTypeProbe} from 'scalar-lib/generated/models/ScalarTypeProbe'; +import {SQLiteTeaQLClient} from 'scalar-lib/teaql-node-sqlite'; +import {GENERATED_WIRE_MODEL_METADATA} from 'scalar-lib/runtime-module'; +import { + UserContext, decimal, long, localTime, createWireEntityMetadata, + encodeWireOutput, normalizeWireInput, WireInputError, +} from 'teaql-ts'; +import Database from 'better-sqlite3'; + +function values(entity: ScalarTypeProbe) { + const e = E.scalarTypeProbe(entity); + return { + requiredString: e.requiredString().eval(), optionalString: e.optionalString().eval(), + largeText: e.largeText().eval(), requiredBoolean: e.requiredBoolean().eval(), + optionalBoolean: e.optionalBoolean().eval(), requiredInteger: e.requiredInteger().eval(), + optionalInteger: e.optionalInteger().eval(), requiredLong: e.requiredLong().eval(), + optionalLong: e.optionalLong().eval(), requiredDecimal: e.requiredDecimal().eval(), + optionalDecimal: e.optionalDecimal().eval(), requiredFloat: e.requiredFloat().eval(), + optionalFloat: e.optionalFloat().eval(), requiredDouble: e.requiredDouble().eval(), + optionalDouble: e.optionalDouble().eval(), requiredDate: e.requiredDate().eval(), + optionalDate: e.optionalDate().eval(), requiredTime: e.requiredTime().eval(), + optionalTime: e.optionalTime().eval(), requiredDatetime: e.requiredDatetime().eval(), + optionalDatetime: e.optionalDatetime().eval(), + }; +} + +async function prepared(context: UserContext, name: string) { + const root = await Q.typePlatforms().withIdIs('1').limit(1) + .comment('reuse the generated scalar root').purpose('prepare typed scalar acceptance').executeForOne(context); + if (!root) throw new Error('scalar root missing'); + const entity = (await Q.scalarTypeProbes().comment('prepare portable scalar values') + .purpose('verify the selected runtime through generated scalar APIs').newEntity(context)); + entity.updateTypePlatform(root); + entity.updateRequiredString(name).updateOptionalString(''); + entity.updateLargeText('Unicode 雪 and a long text field'); + entity.updateRequiredBoolean(true).updateOptionalBoolean(false); + entity.updateRequiredInteger(2147483647).updateOptionalInteger(-2147483648); + entity.updateRequiredLong(long('9007199254740993')); + entity.updateOptionalLong(long('-9223372036854775808')); + entity.updateRequiredDecimal(decimal('123456789012.3456789')); + entity.updateOptionalDecimal(decimal('3.50')); + entity.updateRequiredFloat(1.5).updateOptionalFloat(-3.5); + entity.updateRequiredDouble(2.25).updateOptionalDouble(-0.125); + entity.updateRequiredDate('2024-02-29').updateOptionalDate('2025-01-01'); + entity.updateRequiredTime(localTime('00:00:00')); + entity.updateOptionalTime(localTime('23:59:59.123456')); + entity.updateRequiredDatetime('2024-02-29T12:34:56.789Z'); + entity.updateOptionalDatetime('2025-01-01T00:00:00.000Z'); + return entity; +} + +async function load(context: UserContext, id: string) { + const row = await Q.scalarTypeProbes().withIdIs(id).limit(1) + .comment('reload the exact scalar row').purpose('verify Q E and JSON agree').executeForOne(context); + if (!row) throw new Error('saved scalar row missing'); + return row; +} + +test('all portable scalar families survive generated mutation Q E and JSON', async () => { + const filename = process.env.TEAQL_FULL_SCALAR_DB; + if (!filename) throw new Error('explicit retained scalar database required'); + const client = new SQLiteTeaQLClient(filename); + const context = new UserContext().insertResource('dataService', client); + try { + await context.ensureSchema(); + const entity = await prepared(context, 'All typed scalar families'); + await entity.auditAs('persist typed scalar boundary values').save(context); + const row = await load(context, entity.id!); + const expected = { + requiredString: 'All typed scalar families', optionalString: '', + largeText: 'Unicode 雪 and a long text field', requiredBoolean: true, + optionalBoolean: false, requiredInteger: 2147483647, optionalInteger: -2147483648, + requiredLong: '9007199254740993', optionalLong: '-9223372036854775808', + requiredDecimal: '123456789012.3456789', optionalDecimal: '3.50', + requiredFloat: 1.5, optionalFloat: -3.5, requiredDouble: 2.25, + optionalDouble: -0.125, requiredDate: '2024-02-29', optionalDate: '2025-01-01', + requiredTime: '00:00:00', optionalTime: '23:59:59.123456', + requiredDatetime: '2024-02-29T12:34:56.789Z', optionalDatetime: '2025-01-01T00:00:00.000Z', + }; + expect(values(row)).toEqual(expected); + const json = JSON.parse(JSON.stringify(row)); + for (const [field, value] of Object.entries(expected)) expect(json[field]).toEqual(value); + expect(json.id).toBe(row.id); expect(json.version).toBe(1); + for (const field of ['_root', '_loadedFields', '_fullyLoaded', '_fixTime', 'entityMutationLedger']) expect(json).not.toHaveProperty(field); + const restored = ScalarTypeProbe.fromRecord(json); + expect(values(restored)).toEqual(expected); + expect(restored.id).toBe(row.id); expect(restored.version).toBe(1); + + const logical = Object.fromEntries(Object.entries(expected).map(([field, value]) => + [field.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase()), value])); + for (const profile of ['camelCase', 'snake_case', 'PascalCase'] as const) { + const metadata = createWireEntityMetadata('ScalarTypeProbe', Object.keys(logical), profile); + const wire = JSON.parse(JSON.stringify(encodeWireOutput(logical, metadata))); + expect(normalizeWireInput(wire, metadata).values).toEqual(logical); + } + const metadata = GENERATED_WIRE_MODEL_METADATA.entities.ScalarTypeProbe; + const fullWire = JSON.parse(JSON.stringify(encodeWireOutput(logical, metadata))); + expect(normalizeWireInput(fullWire, metadata).values).toEqual(logical); + const aliases = createWireEntityMetadata('ScalarTypeProbe', ['required_string'], 'camelCase', {required_string: ['legacyName']}); + expect(() => normalizeWireInput({requiredString: 'same', legacyName: 'same'}, aliases)).toThrow(WireInputError); + + row.updateRequiredLong(long('9223372036854775807')); + row.updateRequiredDecimal(decimal('-0.0000001')); + row.updateOptionalDecimal(decimal('0.1')); + row.updateOptionalTime(null); + row.updateOptionalString(null); + await row.auditAs('update exact values and explicit nulls').save(context); + const updated = await load(context, row.id!); + expect(updated.version).toBe(2); + expect(E.scalarTypeProbe(updated).requiredLong().eval()).toBe('9223372036854775807'); + expect(E.scalarTypeProbe(updated).requiredDecimal().eval()).toBe('-0.0000001'); + expect(E.scalarTypeProbe(updated).optionalDecimal().eval()).toBe('0.1'); + expect(E.scalarTypeProbe(updated).optionalTime().eval()).toBeNull(); + const nullable = JSON.parse(JSON.stringify(updated)); + expect(nullable).toHaveProperty('optionalTime', null); + expect(nullable).toHaveProperty('optionalString', null); + const restoredNull = ScalarTypeProbe.fromRecord(nullable); + expect(E.scalarTypeProbe(restoredNull).optionalTime().eval()).toBeNull(); + const sparse = await Q.scalarTypeProbesWithMinimalFields().withIdIs(row.id!).selectRequiredString().limit(1) + .comment('load a scalar projection').purpose('preserve NotLoaded through JSON').executeForOne(context); + if (!sparse) throw new Error('projected row missing'); + const sparseJson = JSON.parse(JSON.stringify(sparse)); + expect(sparseJson).not.toHaveProperty('optionalTime'); + const sparseRestored = ScalarTypeProbe.fromRecord(sparseJson); + expect(() => E.scalarTypeProbe(sparseRestored).optionalTime().eval()).toThrow(TeaQLNotLoadedError); + expect(E.scalarTypeProbe(sparseRestored).requiredString().eval()).toBe(expected.requiredString); + process.stdout.write('CORE_SCALAR_WIRE=' + JSON.stringify({language: 'typescript', passed: true, + families: 12, exactLong: true, exactDecimal: true, allProfiles: true, + loadedNull: true, projectionNotLoaded: true, entityJsonRoundTrip: true, version: 2}) + '\n'); + } finally {await client.close();} +}); + +const nonFiniteCases = ['required_float', 'required_double'].flatMap(field => + [NaN, Infinity, -Infinity].map(value => [field, value] as const)); +test.each(nonFiniteCases)('a non-finite %s cannot silently become JSON null (%s)', async (field, bad) => { + const filename = process.env.TEAQL_FULL_SCALAR_DB; + if (!filename) throw new Error('explicit scalar database required'); + const client = new SQLiteTeaQLClient(filename); + const context = new UserContext().insertResource('dataService', client); + try { + await context.ensureSchema(); + const entity = await prepared(context, 'Invalid floating point ' + String(bad)); + const before = client.auditTrace.length; + const transaction = jest.spyOn((client as any).driver, 'transaction'); + try { + if (field === 'required_float') entity.updateRequiredFloat(bad); + else entity.updateRequiredDouble(bad); + await entity.auditAs('reject non-finite portable Float').save(context); + } catch (error) { + expect(String(error)).toMatch(/finite/i); + expect(String(error)).toContain(field); + expect(transaction).not.toHaveBeenCalled(); + expect(client.auditTrace.length).toBe(before); + process.stdout.write('CORE_NONFINITE_REJECTED=' + JSON.stringify({language: 'typescript', field, value: String(bad), rejected: true, providerTransactions: 0}) + '\n'); + return; + } + const row = await load(context, entity.id!); + const native = field === 'required_float' ? E.scalarTypeProbe(row).requiredFloat().eval() : E.scalarTypeProbe(row).requiredDouble().eval(); + const wire = JSON.parse(JSON.stringify(row)); + // An explicit portable representation would be permissible; silently + // converting a stored NaN/Infinity into an ordinary null is not. + expect(native).toBe(bad); + expect(wire[field === 'required_float' ? 'requiredFloat' : 'requiredDouble']).not.toBeNull(); + throw new Error('non-finite Float was persisted without an explicit portable representation'); + } finally {await client.close();} +}); + +test('generated exact scalars restore to known baselines without discarding real scale or signed-zero intent', async () => { + const filename = process.env.TEAQL_FULL_SCALAR_DB; + if (!filename) throw new Error('retained scalar database required'); + const context = new UserContext(), client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + try { + await context.ensureSchema(); + const entity = await prepared(context, 'Restoration exact scalars'); + entity.updateOptionalString(null).updateOptionalTime(null).updateRequiredDouble(0); + await entity.auditAs('create the exact scalar restoration baseline').save(context); + const row = await load(context, entity.id!); + const original = values(row), json = JSON.stringify(row); + const driver = (client as any).driver; + const transaction = jest.spyOn(driver, 'transaction'), query = jest.spyOn(driver, 'query'); + const policy = jest.spyOn(context, 'enterMutationPolicy'); + const noops: unknown[] = []; + const reset = () => {transaction.mockClear(); query.mockClear(); policy.mockClear(); return client.auditTrace.length;}; + const noIO = (scenario: string, audits: number, version: number, before: string) => { + const result = {scenario, transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length, + policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - audits, + version: row.version, projectionUnchanged: JSON.stringify(row) === before}; + expect(result).toMatchObject({transactions: 0, providerQueries: 0, policyReviews: 0, auditEvents: 0, version, projectionUnchanged: true}); + noops.push(result); + }; + row.updateRequiredInteger(5).updateRequiredInteger(2147483647); + row.updateRequiredLong(long('7')).updateRequiredLong(long('9007199254740993')); + row.updateRequiredDecimal(decimal('9.1')).updateRequiredDecimal(decimal('123456789012.3456789')); + row.updateOptionalDecimal(decimal('9.1')).updateOptionalDecimal(decimal('3.50')); + row.updateRequiredFloat(8.5).updateRequiredFloat(1.5); + row.updateRequiredDouble(8.5).updateRequiredDouble(0); + row.updateRequiredBoolean(false).updateRequiredBoolean(true); + row.updateOptionalString('temporary').updateOptionalString(null); + row.updateRequiredDate('2025-01-01').updateRequiredDate('2024-02-29'); + row.updateRequiredTime(localTime('01:02:03')).updateRequiredTime(localTime('00:00:00')); + row.updateOptionalTime(localTime('01:02:03')).updateOptionalTime(null); + row.updateRequiredDatetime('2025-01-01T00:00:00.000Z').updateRequiredDatetime('2024-02-29T12:34:56.789Z'); + let audits = reset(); await row.auditAs('save the restored exact typed scalar values').save(context); + noIO('typed-scalars-and-nulls', audits, 1, json); expect(values(row)).toEqual(original); + const key = {entity: 'ScalarTypeProbe', id: (row as any)._ledgerId}; + (row as any)._root.set(key, 'required_long', long('7')); + (row as any)._root.set(key, 'required_long', long('9007199254740993')); + (row as any)._root.set(key, 'optional_decimal', decimal('3.50')); + audits = reset(); await row.auditAs('save admitted raw canonical scalar intents restored to baseline').save(context); + noIO('raw-canonical-scalars', audits, 1, json); + + audits = reset(); row.updateOptionalDecimal(decimal('3.500')); + await row.auditAs('preserve a genuine decimal scale edit').save(context); + expect(row.version).toBe(2); expect(transaction).toHaveBeenCalledTimes(1); expect(query.mock.calls.length).toBeGreaterThan(0); + expect(policy).toHaveBeenCalledTimes(1); expect(client.auditTrace.length - audits).toBe(1); + expect(E.scalarTypeProbe(row).optionalDecimal().eval()).toBe('3.500'); + audits = reset(); row.updateRequiredDouble(-0); + await row.auditAs('preserve signed floating zero mutation intent').save(context); + expect(row.version).toBe(3); expect(transaction).toHaveBeenCalledTimes(1); expect(query.mock.calls.length).toBeGreaterThan(0); + expect(policy).toHaveBeenCalledTimes(1); expect(client.auditTrace.length - audits).toBe(1); + const committed = JSON.stringify(row); + row.updateOptionalDecimal(decimal('4.00')).updateOptionalDecimal(decimal('3.500')); + audits = reset(); await row.auditAs('restore against the refreshed committed snapshot').save(context); + noIO('committed-snapshot-refreshed', audits, 3, committed); + const oracle = new Database(filename, {readonly: true, fileMustExist: true}); + let physical; + try {physical = oracle.prepare('SELECT required_long, required_decimal, optional_decimal, required_double, version FROM scalar_type_probe_data WHERE id = ?').get(row.id);} + finally {oracle.close();} + expect(physical).toEqual({required_long: '9007199254740993', required_decimal: '123456789012.3456789', optional_decimal: '3.500', required_double: 0, version: 3}); + process.stdout.write('CORE_SCALAR_RESTORATION=' + JSON.stringify({language: 'typescript', passed: true, + id: row.id, noops, decimalScaleIntent: true, signedZeroIntent: true, sqliteSignedZeroBitsClaimed: false, + committedSnapshotRefreshed: true, physical}) + '\n'); + } finally {jest.restoreAllMocks(); await client.close();} +}); + diff --git a/source/teaql-ts/examples/scalar-type-probe/model.xml b/source/teaql-ts/examples/scalar-type-probe/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..6fd6f2bc503caa1608c4dec93acc85a8d3a345ea --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/model.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/source/teaql-ts/examples/scalar-type-probe/verify-local.cjs b/source/teaql-ts/examples/scalar-type-probe/verify-local.cjs new file mode 100644 index 0000000000000000000000000000000000000000..803765d89752c74d82fc7f1c97bac3a40f632dcb --- /dev/null +++ b/source/teaql-ts/examples/scalar-type-probe/verify-local.cjs @@ -0,0 +1,70 @@ +#!/usr/bin/env node +'use strict'; +const fs = require('node:fs'), path = require('node:path'), os = require('node:os'), assert = require('node:assert/strict'), crypto = require('node:crypto'); +const {createOwnedRunner, ownedBytes} = require('../fix-e-alignment/owned-command.cjs'); +const repo = path.resolve(__dirname, '../..'), sha = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +function fingerprint() { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixture-manifest.json'))); + assert.equal(manifest.schema, 'teaql.generated-example-fixture/v1'); assert.equal(manifest.language, 'typescript'); assert.equal(manifest.evaluationErrors, 0); + assert.equal(sha(fs.readFileSync(path.join(__dirname, 'model.xml'))), manifest.modelSha256); + const actual = []; + function walk(dir, prefix = '') { for (const entry of fs.readdirSync(dir, {withFileTypes: true})) { + assert(!entry.isSymbolicLink()); const file = path.join(dir, entry.name), relative = path.join(prefix, entry.name); + if (entry.isDirectory()) walk(file, relative); else { assert(entry.isFile()); actual.push(relative); } + }} + walk(path.join(__dirname, 'generated')); assert.deepEqual(actual.sort(), Object.keys(manifest.files).sort()); + for (const [file, expected] of Object.entries(manifest.files)) assert.equal(sha(fs.readFileSync(path.join(__dirname, 'generated', file))), expected, file); + return manifest; +} +async function main() { + const requested = process.env.TEAQL_SCALAR_EVIDENCE_DIR; + const evidence = requested ? path.resolve(requested) : fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-ts-scalar-evidence-')); + if (requested) {assert(path.isAbsolute(requested) && !fs.existsSync(evidence)); fs.mkdirSync(evidence, {recursive: true});} + const report = {schema: 'teaql.typescript-scalar-example/v1', passed: false, rounds: [], sameDatabase: true, databaseRetained: true}; + let scratch, runner; + try { + scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-ts-scalar-build-')); runner = createOwnedRunner(); + const manifest = fingerprint(); report.modelSha256 = manifest.modelSha256; + const tsconfig = path.join(scratch, 'tsconfig.json'), config = path.join(scratch, 'jest.cjs'); + fs.writeFileSync(tsconfig, JSON.stringify({extends: path.join(repo, 'tsconfig.json'), compilerOptions: {baseUrl: repo, + types: ['node', 'jest'], typeRoots: [path.join(repo, 'node_modules/@types')], lib: ['ES2022', 'DOM'], + paths: {'teaql-ts': [path.join(repo, 'src/index.ts')], 'teaql-ts/*': [path.join(repo, 'src/*')], + 'scalar-lib/*': [path.join(__dirname, 'generated/src/*')]}}})); + fs.writeFileSync(config, 'module.exports = ' + JSON.stringify({rootDir: repo, roots: [__dirname], testEnvironment: 'node', + testMatch: ['**/examples/scalar-type-probe/*.test.ts'], moduleNameMapper: {'^teaql-ts$': path.join(repo, 'src/index.ts'), + '^teaql-ts/(.*)$': path.join(repo, 'src/$1'), '^scalar-lib/(.*)$': path.join(__dirname, 'generated/src/$1')}, + transform: {'^.+\\.tsx?$': ['ts-jest', {tsconfig}]}}) + ';\n'); + for (const round of [1, 2]) { + const command = [process.execPath, path.join(repo, 'node_modules/jest/bin/jest.js'), '--config', config, + '--runInBand', '--cacheDirectory', path.join(scratch, 'jest')]; + const log = path.join(evidence, `round-${round}.log`), fd = fs.openSync(log, 'wx'); let result; + try {result = await runner.run(command, {cwd: repo, timeout: 120000, + env: {...process.env, TEAQL_FULL_SCALAR_DB: path.join(evidence, 'fixture.sqlite'), TEAQL_INTEGER32_ROUND: String(round)}, stdio: ['ignore', fd, fd]});} + finally {fs.closeSync(fd);} + const bytes = fs.readFileSync(log), text = bytes.toString(); + report.rounds.push({command, exitCode: result.status, signal: result.signal, logSha256: sha(bytes)}); + assert.equal(result.status, 0, text.slice(-16000)); + for (const prefix of ['CORE_SCALAR_WIRE=', 'CORE_SCALAR_RESTORATION=']) { + const records = text.split(/\r?\n/).filter(line => line.startsWith(prefix)).map(line => JSON.parse(line.slice(prefix.length))); + assert.equal(records.length, 1, prefix); assert.equal(records[0].passed, true); + } + const rejected = text.split(/\r?\n/).filter(line => line.startsWith('CORE_NONFINITE_REJECTED=')); assert.equal(rejected.length, 6); + const width=text.split(/\r?\n/).filter(line=>line.startsWith('TYPESCRIPT_INTEGER32=')).map(line=>JSON.parse(line.slice('TYPESCRIPT_INTEGER32='.length))); + assert.equal(width.length,2);assert.deepEqual(width.map(r=>r.backend).sort(),['file','sqlite']); + for(const r of width){assert.equal(r.round,round);assert.equal(r.passed,true);assert.equal(r.cases.length,55);assert(r.cases.every(c=>c.passed));assert.equal(r.legacy.length,8);} + assert.deepEqual(fingerprint(), manifest); + } + report.databaseSha256 = sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite'))); report.passed = true; + console.log('PASS TypeScript generated scalar Q/E/JSON/restoration: twice on one database'); + } catch (error) {console.error(error.stack); process.exitCode ||= 1;} + finally { + const safe = !runner || runner.safeToClean; + report.disposedOwnedBytes = scratch && safe ? ownedBytes(scratch) : 0; + if (scratch && safe) fs.rmSync(scratch, {recursive: true}); + if (!safe) report.unsafeBuildRetention = {path: scratch, processGroup: runner.unsafeGroup}; + report.scratchRemoved = !scratch || !fs.existsSync(scratch); runner?.dispose(); + fs.writeFileSync(path.join(evidence, 'receipt.json'), JSON.stringify(report, null, 2) + '\n'); + console.log('Retained compact scalar evidence: ' + evidence); + } +} +main().catch(error => {console.error(error.stack); process.exitCode ||= 1;}); diff --git a/source/teaql-ts/examples/school-management/app.ts b/source/teaql-ts/examples/school-management/app.ts index 746d401f377edd979bd6d5d871cf554f1629cee8..c7cbb7e9c79cec8c16d2f105aacf21a5f176e909 100644 --- a/source/teaql-ts/examples/school-management/app.ts +++ b/source/teaql-ts/examples/school-management/app.ts @@ -1,11 +1,12 @@ +import {internalId} from 'teaql-ts'; import { Q } from "./src/generated/Q"; import { E } from "./src/generated/E"; import { Platform } from "./src/generated/models/Platform"; import { SchoolType } from "./src/generated/models/SchoolType"; -import { UserContext } from "./src/teaql-ts"; +import { UserContext, nextEntityVersion, decimal } from "./src/teaql-ts"; import { normalizeDynamicSearch, SearchModel } from "teaql-ts"; import { GENERATED_RUNTIME_MODULE } from "./src/runtime-module"; -import { SQLiteDriver, SQLiteTeaQLClient } from "./src/teaql-node-sqlite"; +import { SQLiteTeaQLClient } from "./src/teaql-node-sqlite"; import { mkdirSync } from "node:fs"; import { verifyRequestIntent } from './request-intent'; import { SQLiteTeaQLClient as ReconciledSQLiteTeaQLClient } from './src/reconciled/teaql-node-sqlite'; @@ -13,12 +14,6 @@ import { SQLiteTeaQLClient as ReconciledSQLiteTeaQLClient } from './src/reconcil async function main(): Promise { mkdirSync(".local", { recursive: true }); const database = ".local/school.sqlite"; - const cleanup = new SQLiteDriver(database); - for (const table of ["school_data", "school_type_data", "platform_data", "teaql_id_space"]) { - await cleanup.query(`DROP TABLE IF EXISTS ${table}`); - } - await cleanup.close(); - const client = new SQLiteTeaQLClient(database); client.install(GENERATED_RUNTIME_MODULE); const context = new UserContext().insertResource("dataService", client); @@ -31,7 +26,7 @@ async function main(): Promise { const types = await Q.schoolTypes().comment("Read repeated constant seeds") .purpose("Verify School bootstrap idempotency").executeForList(context); if (roots.length !== 1 || roots[0].id !== "1") throw new Error("Platform(1) bootstrap is not idempotent"); - if (types.length !== 2 || !types.some(value => value.id === "1001") || !types.some(value => value.id === "1002")) { + if (types.filter(value => value.id === "1001" || value.id === "1002").length !== 2) { throw new Error("SchoolType bootstrap is not idempotent"); } // Retained second generated library changes only Primary's presentation name. @@ -44,19 +39,20 @@ async function main(): Promise { .comment("Read reconciled Primary constant") .purpose("Verify versioned constant reconciliation") .executeForOne(changedContext); - if (changedPrimary?.name !== "Primary School" || changedPrimary.version !== 2) { + const originalPrimary = types.find(value => value.id === "1001"); + if (changedPrimary?.name !== "Primary School" || changedPrimary.version !== nextEntityVersion('Update', originalPrimary!.version!)) { throw new Error("Changed SchoolType constant was not reconciled exactly once"); } await changedClient.close(); - const extraType = Q.schoolTypes().comment("Create a post-bootstrap school type") - .purpose("Verify bootstrap ID floor").newEntity(context); + const extraType = (await Q.schoolTypes().comment("Create a post-bootstrap school type") + .purpose("Verify bootstrap ID floor").newEntity(context)); extraType.updatePlatform(Platform.refer("1")); - extraType.updateName("Other").updateCode("OTHER").updateDisplayOrder(3); + extraType.updateName("Other").updateCode("OTHER").updateDisplayOrder(decimal('3')); await extraType.auditAs("Verify SchoolType ID floor").save(context); if (Number(extraType.id) <= 1002) throw new Error("SchoolType ID floor did not advance beyond 1002"); - const school = Q.schools().comment("Create the example school") - .purpose("Verify generated TypeScript mutations").newEntity(context); + const school = (await Q.schools().comment("Create the example school") + .purpose("Verify generated TypeScript mutations").newEntity(context)); school.updatePlatform(Platform.refer("1")); school.updateSchoolTypeToPrimary(); school.updateName("Riverside Primary School"); @@ -67,7 +63,7 @@ async function main(): Promise { await school.auditAs("Create Riverside Primary School").save(context); await verifyDynamicSearch(context); - const primarySchools = await Q.schools().withSchoolTypeIsPrimary() + const primarySchools = await Q.schools().withSchoolTypeIsPrimary().withIdIs(school.id!) .comment("Read schools linked through the PRIMARY helper") .purpose("Verify constant helper mutation-ledger semantics") .executeForList(context); @@ -75,7 +71,7 @@ async function main(): Promise { throw new Error("PRIMARY helper did not persist and hydrate school_type=1001"); } - const loaded = await Q.schools().withIdIs(school.id) + const loaded = await Q.schools().withIdIs(internalId(school.id)) .selectPlatformWith(Q.platformsWithMinimalFields().selectName().selectBaseUrl()) .selectSchoolTypeWith(Q.schoolTypesWithMinimalFields().selectName().selectCode().selectDisplayOrder()) .comment("Load a school with its forward relations") @@ -87,7 +83,7 @@ async function main(): Promise { if (platform.name !== "Campus Learning Platform") { throw new Error("Platform forward relation was not hydrated"); } - if (schoolType.code !== "PRIMARY" || schoolType.displayOrder !== 1) { + if (schoolType.code !== "PRIMARY" || schoolType.displayOrder !== decimal('1')) { throw new Error("SchoolType forward relation was not hydrated"); } @@ -112,12 +108,12 @@ async function main(): Promise { ["constant relation", Q.schools().withSchoolTypeIsPrimary(), 1], ]; for (const [label, request, expected] of queryCases) { - const result = await request.comment(`Query parity: ${label}`) + const result = await request.withIdIs(school.id!).comment(`Query parity: ${label}`) .purpose("Execute the shared School Query conformance case") .executeForList(context); if (result.length !== expected) throw new Error(`${label}: expected ${expected}, got ${result.length}`); } - const projected = await Q.schools().selectName().orderByIdDescending() + const projected = await Q.schools().withIdIs(school.id!).selectName().orderByIdDescending() .comment("Query parity: projection and ordering") .purpose("Execute the shared School Query conformance case") .executeForList(context); @@ -128,8 +124,8 @@ async function main(): Promise { if (previousVersion === undefined) throw new Error("Loaded school has no version"); loaded.updateName("Riverside Primary School — verified"); await loaded.auditAs("Verify TypeScript update fixes").save(context); - if (loaded.version !== previousVersion + 1) throw new Error("Update did not advance version"); - const updated = await Q.schools().withIdIs(loaded.id) + if (loaded.version !== nextEntityVersion('Update', previousVersion)) throw new Error("Update did not advance version"); + const updated = await Q.schools().withIdIs(internalId(loaded.id)) .comment("Reload the updated school") .purpose("Verify update_time fix and persisted mutation").executeForOne(context); if (updated?.name !== "Riverside Primary School — verified") { diff --git a/source/teaql-ts/examples/school-management/current-generator-fixture.json b/source/teaql-ts/examples/school-management/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..1175976f50c0c0be0a1c59b71f47ee0d655afef9 --- /dev/null +++ b/source/teaql-ts/examples/school-management/current-generator-fixture.json @@ -0,0 +1,32 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "b5cd06ae44464fc29ed24de82654b47c80f546110496756aa15923cee1c511b4", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "src/generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "src/generated/requests/SchoolRequest.ts": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "src/generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "src/generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "src/generated/models/School.ts": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "391026fe13cbf33022400658621a8c4ee5ff134cff1ecd73b2b98134aba0f2bb", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/school-management/file-bootstrap.test.ts b/source/teaql-ts/examples/school-management/file-bootstrap.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..37b1b10ab7effda5c287682883e0626330f13194 --- /dev/null +++ b/source/teaql-ts/examples/school-management/file-bootstrap.test.ts @@ -0,0 +1,121 @@ +// Application-owned acceptance. APIs are the same ones exercised in app.ts. +import {Q} from './src/generated/Q'; +import {E} from './src/generated/E'; +import {Platform} from './src/generated/models/Platform'; +import {TeaQLClient} from './src/teaql-ts'; +import {GENERATED_RUNTIME_MODULE} from './src/runtime-module'; +import {GENERATED_RUNTIME_MODULE as RECONCILED_MODULE} from './src/reconciled/runtime-module'; +import {FixedBusinessClock,RuntimeModule,UserContext,decimal} from 'teaql-ts'; +import {existsSync,readFileSync,writeFileSync} from 'node:fs'; +import {join} from 'node:path'; + +const directory=process.env.TEAQL_FILE_BOOTSTRAP_EVIDENCE_DIR,round=Number(process.env.TEAQL_FILE_BOOTSTRAP_ROUND); +if(!directory||![1,2].includes(round))throw Error('explicit evidence directory and round required'); +const now=new Date(round===1?'2032-02-29T10:15:30.125Z':'2033-03-01T11:16:31.250Z'); +const makeContext=()=>new UserContext().withBusinessClock(new FixedBusinessClock(now)) + .insertResource('bootstrapActor','caller actor').insertResource('bootstrapCategory','caller category'); +const schoolTypes=(context:UserContext)=>Q.schoolTypes().limit(10).comment('read fixed SchoolType identities').purpose('verify generated file bootstrap').executeForList(context); +const platform=(context:UserContext)=>Q.platforms().withIdIs('1').limit(1).comment('read the default Domain Root').purpose('verify generated file bootstrap').executeForOne(context); +function hidden(client:TeaQLClient,context:UserContext){ + // @ts-expect-error The workspace must execute schema only through Context. + void client.ensureSchema; + // @ts-expect-error There is no descriptor/array overload on the workspace API. + context.ensureSchema([]); +} +void hidden; +function restored(context:UserContext){ + expect(context.getResource('bootstrapActor')).toBe('caller actor');expect(context.getResource('bootstrapCategory')).toBe('caller category'); +} +function fileBytes(file:string){return existsSync(file)?readFileSync(file).toString('hex'):null;} +function scoped(file:string,module=GENERATED_RUNTIME_MODULE){ + const context=makeContext(),client=new TeaQLClient(file).install(module).setUserContext(context); + context.insertResource('dataService',client);return{client,context}; +} + +test('file provider creates the generated root and constants, then preserves an unchanged repeated seed',async()=>{ + const file=join(directory!,'school-file.json'),before=fileBytes(file),{client,context}=scoped(file); + const persist=jest.spyOn(client as any,'persist');expect(fileBytes(file)).toBe(before);expect(client.auditTrace).toHaveLength(0);expect(persist).not.toHaveBeenCalled(); + expect('ensureSchema' in client).toBe(false); + await context.ensureSchema();restored(context); + expect(client.auditTrace).toHaveLength(round===1?3:0); + if(round===1)for(const event of client.auditTrace){expect(event.actor).toBe('teaql-generated-bootstrap');expect(event.category).toBe('runtime-bootstrap');expect(event.recordedAt).toBe(now.toISOString());} + const root=await platform(context);expect(root?.id).toBe('1'); + const types=await schoolTypes(context);for(const [id,code]of [['1001','PRIMARY'],['1002','SECONDARY']])expect(types.find(x=>x.id===id)?.code).toBe(code); + expect(context.requireActiveRoot('Platform').id).toBe('1'); + const snapshot=fileBytes(file),audits=client.auditTrace.length;persist.mockClear(); + await context.ensureSchema();restored(context);expect(persist).not.toHaveBeenCalled();expect(client.auditTrace).toHaveLength(audits);expect(fileBytes(file)).toBe(snapshot); + const created=JSON.stringify(root!.createTime);root!.updateName('User-maintained platform '+round); + await root!.auditAs('keep an application-owned Domain Root customization').save(context); + const version=root!.version;await context.ensureSchema(); + const preserved=await platform(context);expect(preserved?.name).toBe('User-maintained platform '+round);expect(preserved?.version).toBe(version);expect(JSON.stringify(preserved?.createTime)).toBe(created); + const extra=(await Q.schoolTypes().comment('allocate a type after fixed model identities').purpose('verify the file ID floor').newEntity(context)) + .updatePlatform(Platform.refer('1')).updateName('Other '+round).updateCode('OTHER_'+round).updateDisplayOrder(decimal('3')); + await extra.auditAs('verify normal allocation never collides with model constants').save(context);expect(Number(extra.id)).toBe(1002+round); + const school=(await Q.schools().comment('prepare a file-backed School').purpose('verify the bootstrap graph is usable').newEntity(context)) + .updatePlatform(Platform.refer('1')).updateSchoolTypeToPrimary().updateName('File School '+round).updateAddress('12 River Road') + .updateEstablishedDate('1995-09-01').updateStudentCapacity(800).updateActive(true); + await school.auditAs('create a School against the generated constants').save(context); + const load=()=>Q.schools().withIdIs(school.id!).selectSchoolTypeWith(Q.schoolTypesWithMinimalFields().selectCode()) + .limit(1).comment('load a School and its seeded SchoolType').purpose('verify generated Q/E in a file-backed store').executeForOne(context); + let loaded=await load();expect(loaded).toBeDefined();expect(E.school(loaded!).schoolTypeId().eval()).toBe('1001'); + expect((loaded!.schoolType as {code:string}).code).toBe('PRIMARY');loaded!.updateName('File Academy '+round); + await loaded!.auditAs('update a complete School after automatic file bootstrap').save(context); + loaded=await load();expect(loaded?.name).toBe('File Academy '+round);expect(loaded?.version).toBe(2); + restored(context);persist.mockRestore(); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'school',round,passed:true,firstAudits:round===1?3:0,repeatWrites:0, + root:{id:'1',version:version,name:preserved!.name},school:{id:loaded!.id,version:2,typeId:'1001'},extraTypeId:extra.id,file})+'\n'); +},30000); + +test('fresh file client reconciles a new generated constant model exactly once',async()=>{ + const file=join(directory!,'school-reconcile.json'),base=scoped(file);await base.context.ensureSchema(); + const first=(await schoolTypes(base.context)).find(x=>x.id==='1001')!;const changed=scoped(file,RECONCILED_MODULE); + await changed.context.ensureSchema();const primary=(await schoolTypes(changed.context)).find(x=>x.id==='1001')!; + expect(primary.name).toBe('Primary School');expect(primary.version).toBe(Number(first.version)+1); + const secondary=(await schoolTypes(changed.context)).find(x=>x.id==='1002')!;expect(secondary.version).toBe(1); + expect(changed.client.auditTrace).toHaveLength(1);expect(changed.client.auditTrace[0].actor).toBe('teaql-generated-bootstrap'); + expect(changed.client.auditTrace[0].category).toBe('runtime-bootstrap');expect(changed.client.auditTrace[0].recordedAt).toBe(now.toISOString()); + const persist=jest.spyOn(changed.client as any,'persist'),bytes=fileBytes(file);await changed.context.ensureSchema(); + expect(persist).not.toHaveBeenCalled();expect(fileBytes(file)).toBe(bytes);expect(changed.client.auditTrace).toHaveLength(1);restored(changed.context);persist.mockRestore(); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'reconcile',round,passed:true,primaryVersion:primary.version, + secondaryVersion:1,audits:1,repeatWrites:0,file})+'\n'); +},30000); + +test('concurrent Context callers share one seed without actor leakage',async()=>{ + const file=join(directory!,'school-concurrent.json'),client=new TeaQLClient(file).install(GENERATED_RUNTIME_MODULE),callers=[makeContext(),makeContext()]; + for(const context of callers)context.insertResource('dataService',client); + await Promise.all(callers.map(context=>context.ensureSchema())); + expect(client.auditTrace).toHaveLength(round===1?3:0);for(const caller of callers){restored(caller);expect((await platform(caller))?.id).toBe('1');} + expect((await schoolTypes(callers[0])).map(x=>x.id).sort()).toEqual(['1001','1002']); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'concurrent',round,passed:true,audits:round===1?3:0,contexts:2,file})+'\n'); +},30000); + +test('failed bootstrap leaves no committed file/audit and restores the caller Context',async()=>{ + const file=join(directory!,'school-rejected.json'),{client,context}=scoped(file),failure=new Error('intentional bootstrap structural rejection'); + client.install(new RuntimeModule({}, {Platform:{checkAndFix(){throw failure;}}})); + const persist=jest.spyOn(client as any,'persist');await expect(context.ensureSchema()).rejects.toBe(failure); + expect(persist).not.toHaveBeenCalled();expect(existsSync(file)).toBe(false);expect(client.auditTrace).toHaveLength(0);restored(context);persist.mockRestore(); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'rejected',round,passed:true,writes:0,audits:0,fileAbsent:true,file})+'\n'); +},30000); + +test('conflicting bootstrap roots reject during passive installation',()=>{ + const file=join(directory!,'school-conflict.json'),{client}=scoped(file); + expect(()=>client.install(new RuntimeModule({}, {}, {defaultDomainRoot:{entity:'Platform',id:'99'}}))).toThrow('different Default Domain Roots'); + expect(existsSync(file)).toBe(false);expect(client.auditTrace).toHaveLength(0); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'conflict',round,passed:true,writes:0,fileAbsent:true,file})+'\n'); +}); + +// Additional allocator regression; ordinary setup/recreation uses generated +// Mutation. Only this test-owned legacy-state injection bypasses domain APIs. +test('recreating lower fixed model IDs never moves an existing ID floor backwards',async()=>{ + const file=join(directory!,'school-floor.json'),initial=scoped(file);await initial.context.ensureSchema(); + const state=JSON.parse(readFileSync(file,'utf8')),floor=9000+round*100; + delete state.data.SchoolType['1001'];delete state.data.SchoolType['1002'];state.nextIds.SchoolType=floor; + writeFileSync(file,JSON.stringify(state)); + const {client,context}=scoped(file);await context.ensureSchema(); + expect(client.auditTrace).toHaveLength(2);expect((await schoolTypes(context)).filter(x=>['1001','1002'].includes(x.id!))).toHaveLength(2); + const next=(await Q.schoolTypes().comment('allocate after restoring lower fixed identities').purpose('verify persistent monotonic ID floors').newEntity(context)) + .updatePlatform(Platform.refer('1')).updateName('Floor control '+round).updateCode('FLOOR_'+round).updateDisplayOrder(decimal('4')); + await next.auditAs('verify fixed bootstrap identities cannot rewind allocation').save(context);expect(next.id).toBe(String(floor)); + const stored=JSON.parse(readFileSync(file,'utf8'));expect(stored.nextIds.SchoolType).toBe(floor+1);restored(context); + process.stdout.write('FILE_BOOTSTRAP='+JSON.stringify({scenario:'floor',round,passed:true,recreatedConstants:2,allocatedId:next.id,nextFloor:floor+1,file})+'\n'); +},30000); diff --git a/source/teaql-ts/examples/school-management/package-lock.json b/source/teaql-ts/examples/school-management/package-lock.json index 23c5ae333ccb990be8cd81a64ca0da75d326e13b..87d2fb60e870b5411b72e0bc4ba993213daff231 100644 --- a/source/teaql-ts/examples/school-management/package-lock.json +++ b/source/teaql-ts/examples/school-management/package-lock.json @@ -8,7 +8,7 @@ "name": "school-management-service-lib", "version": "1.0.0", "dependencies": { - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../.." }, "devDependencies": { @@ -16,11 +16,14 @@ "@types/node": "^22.0.0", "ts-node": "^10.9.2", "typescript": "^5.0.0" + }, + "engines": { + "node": ">=22" } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -44,7 +47,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -71,7 +74,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", @@ -262,90 +265,19 @@ "dev": true, "license": "MIT" }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/better-sqlite3": { - "version": "12.11.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", - "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" + "node-addon-api": "^8.0.0" }, "engines": { - "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" + "node": ">=22" } }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", @@ -353,39 +285,6 @@ "dev": true, "license": "MIT" }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, "node_modules/diff": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", @@ -396,74 +295,6 @@ "node": ">=0.3.1" } }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", @@ -471,247 +302,13 @@ "dev": true, "license": "ISC" }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.95.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", - "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" + "node": "^18 || ^20 || >= 21" } }, "node_modules/teaql-ts": { @@ -762,18 +359,6 @@ } } }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -795,12 +380,6 @@ "dev": true, "license": "MIT" }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", @@ -808,12 +387,6 @@ "dev": true, "license": "MIT" }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", diff --git a/source/teaql-ts/examples/school-management/package.json b/source/teaql-ts/examples/school-management/package.json index 49bf2e86bd8b3e061035e74719d8df8a6d0b9ea6..442f1bc9896fc0d6530e5cc776d3cbfea041925b 100644 --- a/source/teaql-ts/examples/school-management/package.json +++ b/source/teaql-ts/examples/school-management/package.json @@ -8,7 +8,8 @@ }, "dependencies": { "teaql-ts": "file:../..", - "better-sqlite3": "^12.10.0"}, + "better-sqlite3": "^13.0.3"}, + "engines": { "node": ">=22" }, "devDependencies": { "typescript": "^5.0.0", "ts-node": "^10.9.2", diff --git a/source/teaql-ts/examples/school-management/request-intent.ts b/source/teaql-ts/examples/school-management/request-intent.ts index 18a993e07eaa593e31cf56678c354b83b3214926..aca26f1718efe162aef914ec63375d0f887b2309 100644 --- a/source/teaql-ts/examples/school-management/request-intent.ts +++ b/source/teaql-ts/examples/school-management/request-intent.ts @@ -21,7 +21,7 @@ export async function verifyRequestIntent(context: UserContext, client: SQLiteTe await reject(() => Q.schools().limit(1).comment('\u0085').purpose('verify request gate').executeForList(context), 'query', 'comment'); await reject(() => Q.schools().limit(1).comment('verify request gate').purpose('').executeForList(context), 'query', 'purpose'); await reject(() => Q.schools().limit(1).comment('verify request gate').purpose('\u0085').executeForList(context), 'query', 'purpose'); - const school = Q.schools().comment('construct rejected school').purpose('verify request gate').newEntity(context); + const school = (await Q.schools().comment('construct rejected school').purpose('verify request gate').newEntity(context)); await reject(() => school.auditAs('').save(context), 'mutation', 'comment'); await reject(() => school.auditAs('\u0085').save(context), 'mutation', 'comment'); if (client.sqlTrace.length !== before) throw new Error('Invalid request reached SQL compilation'); diff --git a/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts b/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts index d3da68070cb03b66985d084711a3d4e417fb6d5a..d52b51f063d2e55d6b28c5187bdeceeb2b71aa9a 100644 --- a/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts +++ b/source/teaql-ts/examples/school-management/src/generated-bootstrap.ts @@ -1,4 +1,4 @@ -import { UserContext } from './teaql-ts'; +import { UserContext, decimal, long, localTime } from './teaql-ts'; import { Q } from './generated/Q'; import { Platform } from './generated/models/Platform'; import { SchoolType } from './generated/models/SchoolType'; @@ -7,7 +7,7 @@ import { SchoolType } from './generated/models/SchoolType'; export async function ensureGeneratedBootstrap(context: UserContext): Promise { let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!domainRoot) { - domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot = Platform.teaqlBootstrapNew(context, '1'); domainRoot.updateName("Campus Learning Platform"); domainRoot.updateBaseUrl("https://campus.example.com"); await domainRoot.auditAs('create generated Domain Root Platform').save(context); @@ -15,34 +15,34 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -46,18 +21,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -66,98 +49,98 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } baseUrl(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('base_url', 'baseUrl'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'baseUrl'); if (!this.value.isLoaded('baseUrl')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + new TeaQLNotLoadedError(path.markMissing(), 'base_url'), ); } return new ValueExpression(this.value.baseUrl); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } schoolTypeList(): SchoolTypeListExpression { - const path = expressionPath(this.path, 'schoolTypeList'); + const path = this.path.member('school_type_list', 'schoolTypeList'); if (this.notLoaded) { - return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolTypeListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolTypeList')) { return new SchoolTypeListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type_list')); } return new SchoolTypeListExpression( this.value.schoolTypeList(), this.root, path, @@ -165,14 +148,14 @@ export class PlatformExpression { } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -184,82 +167,82 @@ export class SchoolTypeExpression { constructor( private readonly value: SchoolType | null | undefined, private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.schoolType()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): SchoolType | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } code(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'code'); if (!this.value.isLoaded('code')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'code'), + new TeaQLNotLoadedError(path.markMissing(), 'code'), ); } return new ValueExpression(this.value.code); } - displayOrder(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'displayOrder'); + displayOrder(): ValueExpression { + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('displayOrder')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), ); } - return new ValueExpression(this.value.displayOrder); + return new ValueExpression(this.value.displayOrder); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -270,33 +253,35 @@ export class SchoolTypeExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -308,130 +293,132 @@ export class SchoolExpression { constructor( private readonly value: School | null | undefined, private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.school()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): School | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } address(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('address', 'address'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'address'); if (!this.value.isLoaded('address')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'address'), + new TeaQLNotLoadedError(path.markMissing(), 'address'), ); } return new ValueExpression(this.value.address); } establishedDate(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('established_date', 'establishedDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'establishedDate'); if (!this.value.isLoaded('establishedDate')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + new TeaQLNotLoadedError(path.markMissing(), 'established_date'), ); } return new ValueExpression(this.value.establishedDate); } studentCapacity(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('student_capacity', 'studentCapacity'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'studentCapacity'); if (!this.value.isLoaded('studentCapacity')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + new TeaQLNotLoadedError(path.markMissing(), 'student_capacity'), ); } + const error = integer32Error(this.value.studentCapacity, 'School', 'student_capacity'); + if (error) return ValueExpression.invalid(error); return new ValueExpression(this.value.studentCapacity); } active(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('active', 'active'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'active'); if (!this.value.isLoaded('active')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'active'), + new TeaQLNotLoadedError(path.markMissing(), 'active'), ); } return new ValueExpression(this.value.active); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -442,12 +429,12 @@ export class SchoolExpression { } schoolTypeId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('school_type', 'schoolTypeId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'schoolType'); if (!this.value.isLoaded('schoolType')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'schoolType'), + new TeaQLNotLoadedError(path.markMissing(), 'school_type'), ); } const reference = this.value.schoolType; @@ -458,40 +445,44 @@ export class SchoolExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolType(): SchoolTypeExpression { - const path = expressionPath(this.path, 'schoolType'); + const path = this.path.member('school_type', 'schoolType'); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); if (!this.value.isLoaded('schoolType')) { return new SchoolTypeExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'schoolType')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); } const relation = this.value.schoolType; - const target = relation == null - ? undefined - : relation instanceof SchoolType - ? relation - : SchoolType.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof SchoolType)) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); + } + const target = relation instanceof SchoolType ? relation : undefined; return new SchoolTypeExpression(target, this.root, path); } @@ -501,30 +492,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -536,30 +531,34 @@ export class SchoolTypeListExpression { constructor( private readonly items: readonly SchoolType[], private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolTypeListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolTypeListExpression { return new SchoolTypeListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolTypeExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolTypeExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolTypeExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolTypeExpression(undefined, this.root, itemPath) @@ -571,30 +570,34 @@ export class SchoolListExpression { constructor( private readonly items: readonly School[], private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolListExpression { return new SchoolListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolExpression(undefined, this.root, itemPath) @@ -607,7 +610,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -615,7 +618,7 @@ export class E { value: SchoolType | null | undefined, ): SchoolTypeExpression { return new SchoolTypeExpression( - value, `SchoolType(id=${value?.id ?? 'null'})`, + value, 'SchoolType', ExpressionPath.root('E.schoolType()', 'camelCase'), ); } @@ -623,7 +626,7 @@ export class E { value: School | null | undefined, ): SchoolExpression { return new SchoolExpression( - value, `School(id=${value?.id ?? 'null'})`, + value, 'School', ExpressionPath.root('E.school()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts b/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts index 6290c60e32711869d3b5361d5553bf014d622502..e9520de760e12f353c9c66ec6176df004eafaf47 100644 --- a/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/school-management/src/generated/models/Platform.ts @@ -1,27 +1,33 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { SchoolType } from './SchoolType'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "base_url", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; baseUrl?: string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolTypeList"]; delete fields["schoolList"]; Object.assign(this, fields); @@ -47,25 +53,34 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolTypeList")) result["schoolTypeList"] = (this as any)._schoolTypeList; + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -84,12 +99,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -99,23 +121,153 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolTypeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolTypeList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_type_list": graph.sourceMembers((this as any)._schoolTypeList), + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolTypeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -123,6 +275,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -133,7 +286,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -142,36 +296,40 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -179,7 +337,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -191,42 +349,42 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -235,12 +393,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -251,38 +413,44 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -298,6 +466,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -333,7 +505,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/generated/models/School.ts b/source/teaql-ts/examples/school-management/src/generated/models/School.ts index a0e0932d518e97acbecdeed78ef3e6749956f366..c958b9019590aa7772ade5bad19100e3dd4e825e 100644 --- a/source/teaql-ts/examples/school-management/src/generated/models/School.ts +++ b/source/teaql-ts/examples/school-management/src/generated/models/School.ts @@ -1,9 +1,13 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { SchoolType } from './SchoolType'; +const teaqlConstruction = Symbol("managed entity construction"); + export class School { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("School", + ["id", "platform", "school_type", "name", "address", "established_date", "student_capacity", "active", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; platform?: Platform | string; schoolType?: SchoolType | string; @@ -14,17 +18,25 @@ export class School { active?: boolean; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { this.platform = (init as any).platform instanceof Platform @@ -40,13 +52,15 @@ export class School { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -55,8 +69,19 @@ export class School { } static fromRecord(record: Record, root?: EntityRoot): School { - const entity = new School(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new School(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -75,12 +100,19 @@ export class School { } static refer(id: string | number): School { - return new School({ id: String(id) } as Partial); + return School.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): School { - return new School().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): School { + return EntityCreation.bootstrap(context, "School", id, + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "School", + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -90,23 +122,101 @@ export class School { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform", + "school_type": "SchoolType" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + School.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "School", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -114,6 +224,7 @@ export class School { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "School", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -124,7 +235,8 @@ export class School { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -133,8 +245,10 @@ export class School { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -142,7 +256,7 @@ export class School { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -154,14 +268,12 @@ export class School { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -170,12 +282,16 @@ export class School { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -186,10 +302,14 @@ export class School { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -210,6 +330,10 @@ export class School { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -266,7 +390,7 @@ export class School { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts b/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts index 0677cb7d71363977bb4b42d7d44bce7d089cc983..3c933c84081b6a06762ebfe3453dc4551f5b8196 100644 --- a/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts +++ b/source/teaql-ts/examples/school-management/src/generated/models/SchoolType.ts @@ -1,26 +1,32 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class SchoolType { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("SchoolType", + ["platform", "id", "name", "code", "display_order", "version"], { id: "immutable_field", version: "immutable_field" }); platform?: Platform | string; id?: string; name?: string; code?: string; - displayOrder?: number; - version?: number; + displayOrder?: Decimal; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolList"]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { @@ -41,24 +47,32 @@ export class SchoolType { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): SchoolType { - const entity = new SchoolType(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new SchoolType(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -77,12 +91,19 @@ export class SchoolType { } static refer(id: string | number): SchoolType { - return new SchoolType({ id: String(id) } as Partial); + return SchoolType.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): SchoolType { - return new SchoolType().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): SchoolType { + return EntityCreation.bootstrap(context, "SchoolType", id, + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "SchoolType", + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -92,23 +113,127 @@ export class SchoolType { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + SchoolType.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] @@ -116,6 +241,7 @@ export class SchoolType { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -126,7 +252,8 @@ export class SchoolType { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -135,22 +262,25 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -158,7 +288,7 @@ export class SchoolType { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -170,28 +300,27 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -200,12 +329,16 @@ export class SchoolType { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -216,24 +349,29 @@ export class SchoolType { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -249,6 +387,10 @@ export class SchoolType { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -270,14 +412,15 @@ export class SchoolType { return this; } - updateDisplayOrder(value: number): this { + updateDisplayOrder(value: Decimal): this { + if (value != null) value = decimal(value); this.displayOrder = value; this.markLoaded("displayOrder"); (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts index af9cf03a986e08d02115cba30825e5e6b3bbfdf6..a36d62e09bcd438cc795838878869315b4813268 100644 --- a/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/school-management/src/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -147,13 +154,13 @@ export class PlatformRequest { - selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeListWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolTypeList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -162,17 +169,19 @@ export class PlatformRequest { haveSchoolTypes(): this { return this.withSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } haveNoSchoolTypes(): this { return this.withoutSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } - withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -183,7 +192,7 @@ export class PlatformRequest { return this; } - withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -195,17 +204,19 @@ export class PlatformRequest { } haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -216,7 +227,7 @@ export class PlatformRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -233,13 +244,13 @@ export class PlatformRequest { countSchoolTypesAs(alias: string): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); - this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.countSchoolTypesWith(alias, { entityName: "SchoolType", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; return this; } - countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolTypesWith(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -251,10 +262,10 @@ export class PlatformRequest { minDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.minDisplayOrderOfSchoolTypesAs( - "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "minOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + minDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "displayOrder", alias); @@ -265,10 +276,10 @@ export class PlatformRequest { maxDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.maxDisplayOrderOfSchoolTypesAs( - "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "maxOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "displayOrder", alias); @@ -279,10 +290,10 @@ export class PlatformRequest { sumDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sumDisplayOrderOfSchoolTypesAs( - "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sumOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "displayOrder", alias); @@ -293,10 +304,10 @@ export class PlatformRequest { avgDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.avgDisplayOrderOfSchoolTypesAs( - "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "avgOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "displayOrder", alias); @@ -307,10 +318,10 @@ export class PlatformRequest { standardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.standardDeviationDisplayOrderOfSchoolTypesAs( - "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "standardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "displayOrder", alias); @@ -321,10 +332,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( - "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "displayOrder", alias); @@ -335,10 +346,10 @@ export class PlatformRequest { sampleVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sampleVarianceDisplayOrderOfSchoolTypesAs( - "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sampleVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "displayOrder", alias); @@ -349,10 +360,10 @@ export class PlatformRequest { samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( - "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "displayOrder", alias); @@ -366,13 +377,13 @@ export class PlatformRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -384,10 +395,10 @@ export class PlatformRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -398,10 +409,10 @@ export class PlatformRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -412,10 +423,10 @@ export class PlatformRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -426,10 +437,10 @@ export class PlatformRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -440,10 +451,10 @@ export class PlatformRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -454,10 +465,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -468,10 +479,10 @@ export class PlatformRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -482,10 +493,10 @@ export class PlatformRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -494,47 +505,47 @@ export class PlatformRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -559,42 +570,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -648,42 +659,42 @@ export class PlatformRequest { return this; } - withBaseUrlIsNot(val: any): this { + withBaseUrlIsNot(val: string): this { this.filters.push({ "baseUrl": { "$ne": val } }); return this; } - withBaseUrlIn(...vals: any[]): this { + withBaseUrlIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$in": vals } }); return this; } - withBaseUrlNotIn(...vals: any[]): this { + withBaseUrlNotIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$notIn": vals } }); return this; } - withBaseUrlGreaterThan(val: any): this { + withBaseUrlGreaterThan(val: string): this { this.filters.push({ "baseUrl": { "$gt": val } }); return this; } - withBaseUrlGreaterThanOrEqualTo(val: any): this { + withBaseUrlGreaterThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$gte": val } }); return this; } - withBaseUrlLessThan(val: any): this { + withBaseUrlLessThan(val: string): this { this.filters.push({ "baseUrl": { "$lt": val } }); return this; } - withBaseUrlLessThanOrEqualTo(val: any): this { + withBaseUrlLessThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$lte": val } }); return this; } - withBaseUrlBetween(lower: any, upper: any): this { + withBaseUrlBetween(lower: string, upper: string): this { this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); return this; } @@ -727,47 +738,47 @@ export class PlatformRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -782,47 +793,47 @@ export class PlatformRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -837,47 +848,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -976,7 +987,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -985,7 +996,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByBaseUrl(): this { @@ -994,7 +1005,7 @@ export class PlatformRequest { } groupByBaseUrlAs(retName: string): this { - this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + this.query.groupBy("baseUrl", retName); return this; } groupByCreateTime(): this { @@ -1003,7 +1014,7 @@ export class PlatformRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1012,7 +1023,7 @@ export class PlatformRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1021,7 +1032,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -1134,9 +1145,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts index 394ab2a4fb412ab2b2e47194914185b0857cf66b..de1a516165f2696796a626baf893ca4140235532 100644 --- a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts +++ b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { School } from '../models/School'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolRequest { else this.selectSelfFields(); } + get entityName(): "School" { + return "School"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -162,14 +169,14 @@ export class SchoolRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); return this; } - selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.select(["schoolType"]); this.query.relationQuery( "schoolType", request.toQuery(), "schoolType", "id", false, @@ -177,7 +184,7 @@ export class SchoolRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -186,7 +193,7 @@ export class SchoolRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -194,7 +201,7 @@ export class SchoolRequest { }); return this; } - withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -203,7 +210,7 @@ export class SchoolRequest { return this; } - withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -215,47 +222,47 @@ export class SchoolRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -328,42 +335,42 @@ export class SchoolRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -417,42 +424,42 @@ export class SchoolRequest { return this; } - withAddressIsNot(val: any): this { + withAddressIsNot(val: string): this { this.filters.push({ "address": { "$ne": val } }); return this; } - withAddressIn(...vals: any[]): this { + withAddressIn(...vals: string[]): this { this.filters.push({ "address": { "$in": vals } }); return this; } - withAddressNotIn(...vals: any[]): this { + withAddressNotIn(...vals: string[]): this { this.filters.push({ "address": { "$notIn": vals } }); return this; } - withAddressGreaterThan(val: any): this { + withAddressGreaterThan(val: string): this { this.filters.push({ "address": { "$gt": val } }); return this; } - withAddressGreaterThanOrEqualTo(val: any): this { + withAddressGreaterThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$gte": val } }); return this; } - withAddressLessThan(val: any): this { + withAddressLessThan(val: string): this { this.filters.push({ "address": { "$lt": val } }); return this; } - withAddressLessThanOrEqualTo(val: any): this { + withAddressLessThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$lte": val } }); return this; } - withAddressBetween(lower: any, upper: any): this { + withAddressBetween(lower: string, upper: string): this { this.filters.push({ "address": { "$between": [lower, upper] } }); return this; } @@ -496,47 +503,47 @@ export class SchoolRequest { return this; } - withEstablishedDateIs(val: any): this { + withEstablishedDateIs(val: string): this { this.filters.push({ "establishedDate": { "$eq": val } }); return this; } - withEstablishedDateIsNot(val: any): this { + withEstablishedDateIsNot(val: string): this { this.filters.push({ "establishedDate": { "$ne": val } }); return this; } - withEstablishedDateIn(...vals: any[]): this { + withEstablishedDateIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$in": vals } }); return this; } - withEstablishedDateNotIn(...vals: any[]): this { + withEstablishedDateNotIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$notIn": vals } }); return this; } - withEstablishedDateGreaterThan(val: any): this { + withEstablishedDateGreaterThan(val: string): this { this.filters.push({ "establishedDate": { "$gt": val } }); return this; } - withEstablishedDateGreaterThanOrEqualTo(val: any): this { + withEstablishedDateGreaterThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$gte": val } }); return this; } - withEstablishedDateLessThan(val: any): this { + withEstablishedDateLessThan(val: string): this { this.filters.push({ "establishedDate": { "$lt": val } }); return this; } - withEstablishedDateLessThanOrEqualTo(val: any): this { + withEstablishedDateLessThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$lte": val } }); return this; } - withEstablishedDateBetween(lower: any, upper: any): this { + withEstablishedDateBetween(lower: string, upper: string): this { this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); return this; } @@ -551,47 +558,47 @@ export class SchoolRequest { return this; } - withStudentCapacityIs(val: any): this { + withStudentCapacityIs(val: number): this { this.filters.push({ "studentCapacity": { "$eq": val } }); return this; } - withStudentCapacityIsNot(val: any): this { + withStudentCapacityIsNot(val: number): this { this.filters.push({ "studentCapacity": { "$ne": val } }); return this; } - withStudentCapacityIn(...vals: any[]): this { + withStudentCapacityIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$in": vals } }); return this; } - withStudentCapacityNotIn(...vals: any[]): this { + withStudentCapacityNotIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$notIn": vals } }); return this; } - withStudentCapacityGreaterThan(val: any): this { + withStudentCapacityGreaterThan(val: number): this { this.filters.push({ "studentCapacity": { "$gt": val } }); return this; } - withStudentCapacityGreaterThanOrEqualTo(val: any): this { + withStudentCapacityGreaterThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$gte": val } }); return this; } - withStudentCapacityLessThan(val: any): this { + withStudentCapacityLessThan(val: number): this { this.filters.push({ "studentCapacity": { "$lt": val } }); return this; } - withStudentCapacityLessThanOrEqualTo(val: any): this { + withStudentCapacityLessThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$lte": val } }); return this; } - withStudentCapacityBetween(lower: any, upper: any): this { + withStudentCapacityBetween(lower: number, upper: number): this { this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); return this; } @@ -615,42 +622,42 @@ export class SchoolRequest { this.filters.push({ "active": { "$eq": false } }); return this; } - withActiveIsNot(val: any): this { + withActiveIsNot(val: boolean): this { this.filters.push({ "active": { "$ne": val } }); return this; } - withActiveIn(...vals: any[]): this { + withActiveIn(...vals: boolean[]): this { this.filters.push({ "active": { "$in": vals } }); return this; } - withActiveNotIn(...vals: any[]): this { + withActiveNotIn(...vals: boolean[]): this { this.filters.push({ "active": { "$notIn": vals } }); return this; } - withActiveGreaterThan(val: any): this { + withActiveGreaterThan(val: boolean): this { this.filters.push({ "active": { "$gt": val } }); return this; } - withActiveGreaterThanOrEqualTo(val: any): this { + withActiveGreaterThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$gte": val } }); return this; } - withActiveLessThan(val: any): this { + withActiveLessThan(val: boolean): this { this.filters.push({ "active": { "$lt": val } }); return this; } - withActiveLessThanOrEqualTo(val: any): this { + withActiveLessThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$lte": val } }); return this; } - withActiveBetween(lower: any, upper: any): this { + withActiveBetween(lower: boolean, upper: boolean): this { this.filters.push({ "active": { "$between": [lower, upper] } }); return this; } @@ -665,47 +672,47 @@ export class SchoolRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -720,47 +727,47 @@ export class SchoolRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -775,47 +782,47 @@ export class SchoolRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -1010,7 +1017,7 @@ export class SchoolRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPlatform(): this { @@ -1019,7 +1026,7 @@ export class SchoolRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupBySchoolType(): this { @@ -1028,7 +1035,7 @@ export class SchoolRequest { } groupBySchoolTypeAs(retName: string): this { - this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + this.query.groupBy("schoolType", retName); return this; } groupByName(): this { @@ -1037,7 +1044,7 @@ export class SchoolRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByAddress(): this { @@ -1046,7 +1053,7 @@ export class SchoolRequest { } groupByAddressAs(retName: string): this { - this.query.groupBy("address"); // In TS we don't alias group by yet natively + this.query.groupBy("address", retName); return this; } groupByEstablishedDate(): this { @@ -1055,7 +1062,7 @@ export class SchoolRequest { } groupByEstablishedDateAs(retName: string): this { - this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + this.query.groupBy("establishedDate", retName); return this; } groupByStudentCapacity(): this { @@ -1064,7 +1071,7 @@ export class SchoolRequest { } groupByStudentCapacityAs(retName: string): this { - this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + this.query.groupBy("studentCapacity", retName); return this; } groupByActive(): this { @@ -1073,7 +1080,7 @@ export class SchoolRequest { } groupByActiveAs(retName: string): this { - this.query.groupBy("active"); // In TS we don't alias group by yet natively + this.query.groupBy("active", retName); return this; } groupByCreateTime(): this { @@ -1082,7 +1089,7 @@ export class SchoolRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1091,7 +1098,7 @@ export class SchoolRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1100,14 +1107,14 @@ export class SchoolRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1117,7 +1124,7 @@ export class SchoolRequest { facetBySchoolTypeAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "schoolType", request, includeAllFacets, @@ -1233,9 +1240,10 @@ export class ExecutableSchoolRequest { return this; } - newEntity(context: UserContext): School { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new School(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return School.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts index 8d09b5f34a9b4b2aeee292bcfb05406959efef90..0eb932a414f079e38f575598bd0212c567b84edb 100644 --- a/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts +++ b/source/teaql-ts/examples/school-management/src/generated/requests/SchoolTypeRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { SchoolType } from '../models/SchoolType'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolTypeRequest { else this.selectSelfFields(); } + get entityName(): "SchoolType" { + return "SchoolType"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolTypeRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -140,7 +147,7 @@ export class SchoolTypeRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -148,7 +155,7 @@ export class SchoolTypeRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -157,7 +164,7 @@ export class SchoolTypeRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -166,7 +173,7 @@ export class SchoolTypeRequest { return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "schoolType", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -175,17 +182,19 @@ export class SchoolTypeRequest { haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -196,7 +205,7 @@ export class SchoolTypeRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -213,13 +222,13 @@ export class SchoolTypeRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -231,10 +240,10 @@ export class SchoolTypeRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -245,10 +254,10 @@ export class SchoolTypeRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -259,10 +268,10 @@ export class SchoolTypeRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -273,10 +282,10 @@ export class SchoolTypeRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -287,10 +296,10 @@ export class SchoolTypeRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -301,10 +310,10 @@ export class SchoolTypeRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -315,10 +324,10 @@ export class SchoolTypeRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -329,10 +338,10 @@ export class SchoolTypeRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -361,47 +370,47 @@ export class SchoolTypeRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -426,42 +435,42 @@ export class SchoolTypeRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -515,42 +524,42 @@ export class SchoolTypeRequest { return this; } - withCodeIsNot(val: any): this { + withCodeIsNot(val: string): this { this.filters.push({ "code": { "$ne": val } }); return this; } - withCodeIn(...vals: any[]): this { + withCodeIn(...vals: string[]): this { this.filters.push({ "code": { "$in": vals } }); return this; } - withCodeNotIn(...vals: any[]): this { + withCodeNotIn(...vals: string[]): this { this.filters.push({ "code": { "$notIn": vals } }); return this; } - withCodeGreaterThan(val: any): this { + withCodeGreaterThan(val: string): this { this.filters.push({ "code": { "$gt": val } }); return this; } - withCodeGreaterThanOrEqualTo(val: any): this { + withCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$gte": val } }); return this; } - withCodeLessThan(val: any): this { + withCodeLessThan(val: string): this { this.filters.push({ "code": { "$lt": val } }); return this; } - withCodeLessThanOrEqualTo(val: any): this { + withCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$lte": val } }); return this; } - withCodeBetween(lower: any, upper: any): this { + withCodeBetween(lower: string, upper: string): this { this.filters.push({ "code": { "$between": [lower, upper] } }); return this; } @@ -594,47 +603,47 @@ export class SchoolTypeRequest { return this; } - withDisplayOrderIs(val: any): this { + withDisplayOrderIs(val: Decimal): this { this.filters.push({ "displayOrder": { "$eq": val } }); return this; } - withDisplayOrderIsNot(val: any): this { + withDisplayOrderIsNot(val: Decimal): this { this.filters.push({ "displayOrder": { "$ne": val } }); return this; } - withDisplayOrderIn(...vals: any[]): this { + withDisplayOrderIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$in": vals } }); return this; } - withDisplayOrderNotIn(...vals: any[]): this { + withDisplayOrderNotIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$notIn": vals } }); return this; } - withDisplayOrderGreaterThan(val: any): this { + withDisplayOrderGreaterThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$gt": val } }); return this; } - withDisplayOrderGreaterThanOrEqualTo(val: any): this { + withDisplayOrderGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$gte": val } }); return this; } - withDisplayOrderLessThan(val: any): this { + withDisplayOrderLessThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$lt": val } }); return this; } - withDisplayOrderLessThanOrEqualTo(val: any): this { + withDisplayOrderLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$lte": val } }); return this; } - withDisplayOrderBetween(lower: any, upper: any): this { + withDisplayOrderBetween(lower: Decimal, upper: Decimal): this { this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); return this; } @@ -649,47 +658,47 @@ export class SchoolTypeRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -842,7 +851,7 @@ export class SchoolTypeRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupById(): this { @@ -851,7 +860,7 @@ export class SchoolTypeRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -860,7 +869,7 @@ export class SchoolTypeRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCode(): this { @@ -869,7 +878,7 @@ export class SchoolTypeRequest { } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } groupByDisplayOrder(): this { @@ -878,7 +887,7 @@ export class SchoolTypeRequest { } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } groupByVersion(): this { @@ -887,14 +896,14 @@ export class SchoolTypeRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1010,9 +1019,10 @@ export class ExecutableSchoolTypeRequest { return this; } - newEntity(context: UserContext): SchoolType { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new SchoolType(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return SchoolType.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/reconciled/current-generator-fixture.json b/source/teaql-ts/examples/school-management/src/reconciled/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..340d7feb26e8e3dcf1c4f2a2fe27bf24deaf9fa7 --- /dev/null +++ b/source/teaql-ts/examples/school-management/src/reconciled/current-generator-fixture.json @@ -0,0 +1,32 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "896c579f3c9dded55c9728cb4af23cc8b920776e93ddcb95c8b0e95efdbcb451", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "generated/requests/SchoolRequest.ts": "d3325cc673acf6e25c847f57e5a6912a0135c1a8cf675c1d5cd3548d8d54c76b", + "generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "runtime-module.ts": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "generated-bootstrap.ts": "6a29d81e4bbc4c5fd76ed3fa5e87f79b9e4ace4fc02a0afa29cfefc12e32b323", + "generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "generated/models/School.ts": "63cc850cdd588ff0b83185e608183381aca7ffc63d41bb6cf381a13eecb095f2" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "8a5602a2b4eaeb81fc73a65c8233a32240e4f9728c839b1920adf90b7489bb93", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts index 238fab8253ff2d3df49ec3b3a1b77922e2b3b07f..695c343600be228e4961b974121e951182ab6450 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated-bootstrap.ts @@ -1,4 +1,4 @@ -import { UserContext } from './teaql-ts'; +import { UserContext, decimal, long, localTime } from './teaql-ts'; import { Q } from './generated/Q'; import { Platform } from './generated/models/Platform'; import { SchoolType } from './generated/models/SchoolType'; @@ -7,7 +7,7 @@ import { SchoolType } from './generated/models/SchoolType'; export async function ensureGeneratedBootstrap(context: UserContext): Promise { let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!domainRoot) { - domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot = Platform.teaqlBootstrapNew(context, '1'); domainRoot.updateName("Campus Learning Platform"); domainRoot.updateBaseUrl("https://campus.example.com"); await domainRoot.auditAs('create generated Domain Root Platform').save(context); @@ -15,34 +15,34 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -46,18 +21,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -66,98 +49,98 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } baseUrl(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('base_url', 'baseUrl'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'baseUrl'); if (!this.value.isLoaded('baseUrl')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + new TeaQLNotLoadedError(path.markMissing(), 'base_url'), ); } return new ValueExpression(this.value.baseUrl); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } schoolTypeList(): SchoolTypeListExpression { - const path = expressionPath(this.path, 'schoolTypeList'); + const path = this.path.member('school_type_list', 'schoolTypeList'); if (this.notLoaded) { - return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolTypeListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolTypeList')) { return new SchoolTypeListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type_list')); } return new SchoolTypeListExpression( this.value.schoolTypeList(), this.root, path, @@ -165,14 +148,14 @@ export class PlatformExpression { } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -184,82 +167,82 @@ export class SchoolTypeExpression { constructor( private readonly value: SchoolType | null | undefined, private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.schoolType()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): SchoolType | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } code(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'code'); if (!this.value.isLoaded('code')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'code'), + new TeaQLNotLoadedError(path.markMissing(), 'code'), ); } return new ValueExpression(this.value.code); } - displayOrder(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'displayOrder'); + displayOrder(): ValueExpression { + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('displayOrder')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), ); } - return new ValueExpression(this.value.displayOrder); + return new ValueExpression(this.value.displayOrder); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -270,33 +253,35 @@ export class SchoolTypeExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -308,130 +293,132 @@ export class SchoolExpression { constructor( private readonly value: School | null | undefined, private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.school()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): School | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } address(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('address', 'address'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'address'); if (!this.value.isLoaded('address')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'address'), + new TeaQLNotLoadedError(path.markMissing(), 'address'), ); } return new ValueExpression(this.value.address); } establishedDate(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('established_date', 'establishedDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'establishedDate'); if (!this.value.isLoaded('establishedDate')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + new TeaQLNotLoadedError(path.markMissing(), 'established_date'), ); } return new ValueExpression(this.value.establishedDate); } studentCapacity(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('student_capacity', 'studentCapacity'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'studentCapacity'); if (!this.value.isLoaded('studentCapacity')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + new TeaQLNotLoadedError(path.markMissing(), 'student_capacity'), ); } + const error = integer32Error(this.value.studentCapacity, 'School', 'student_capacity'); + if (error) return ValueExpression.invalid(error); return new ValueExpression(this.value.studentCapacity); } active(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('active', 'active'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'active'); if (!this.value.isLoaded('active')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'active'), + new TeaQLNotLoadedError(path.markMissing(), 'active'), ); } return new ValueExpression(this.value.active); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -442,12 +429,12 @@ export class SchoolExpression { } schoolTypeId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('school_type', 'schoolTypeId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'schoolType'); if (!this.value.isLoaded('schoolType')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'schoolType'), + new TeaQLNotLoadedError(path.markMissing(), 'school_type'), ); } const reference = this.value.schoolType; @@ -458,40 +445,44 @@ export class SchoolExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolType(): SchoolTypeExpression { - const path = expressionPath(this.path, 'schoolType'); + const path = this.path.member('school_type', 'schoolType'); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); if (!this.value.isLoaded('schoolType')) { return new SchoolTypeExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'schoolType')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); } const relation = this.value.schoolType; - const target = relation == null - ? undefined - : relation instanceof SchoolType - ? relation - : SchoolType.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof SchoolType)) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); + } + const target = relation instanceof SchoolType ? relation : undefined; return new SchoolTypeExpression(target, this.root, path); } @@ -501,30 +492,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -536,30 +531,34 @@ export class SchoolTypeListExpression { constructor( private readonly items: readonly SchoolType[], private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolTypeListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolTypeListExpression { return new SchoolTypeListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolTypeExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolTypeExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolTypeExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolTypeExpression(undefined, this.root, itemPath) @@ -571,30 +570,34 @@ export class SchoolListExpression { constructor( private readonly items: readonly School[], private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolListExpression { return new SchoolListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolExpression(undefined, this.root, itemPath) @@ -607,7 +610,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -615,7 +618,7 @@ export class E { value: SchoolType | null | undefined, ): SchoolTypeExpression { return new SchoolTypeExpression( - value, `SchoolType(id=${value?.id ?? 'null'})`, + value, 'SchoolType', ExpressionPath.root('E.schoolType()', 'camelCase'), ); } @@ -623,7 +626,7 @@ export class E { value: School | null | undefined, ): SchoolExpression { return new SchoolExpression( - value, `School(id=${value?.id ?? 'null'})`, + value, 'School', ExpressionPath.root('E.school()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts index 6290c60e32711869d3b5361d5553bf014d622502..e9520de760e12f353c9c66ec6176df004eafaf47 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/Platform.ts @@ -1,27 +1,33 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { SchoolType } from './SchoolType'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "base_url", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; baseUrl?: string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolTypeList"]; delete fields["schoolList"]; Object.assign(this, fields); @@ -47,25 +53,34 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolTypeList")) result["schoolTypeList"] = (this as any)._schoolTypeList; + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -84,12 +99,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -99,23 +121,153 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolTypeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolTypeList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_type_list": graph.sourceMembers((this as any)._schoolTypeList), + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolTypeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -123,6 +275,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -133,7 +286,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -142,36 +296,40 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -179,7 +337,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -191,42 +349,42 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -235,12 +393,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -251,38 +413,44 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -298,6 +466,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -333,7 +505,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts index 97ad757e263a8d123a8ab8c98088257003058861..77bd9113209b27e0d2a5b62cf0633c1ba8bdf6ab 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/School.ts @@ -1,9 +1,13 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { SchoolType } from './SchoolType'; +const teaqlConstruction = Symbol("managed entity construction"); + export class School { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("School", + ["id", "platform", "school_type", "name", "address", "established_date", "student_capacity", "active", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; platform?: Platform | string; schoolType?: SchoolType | string; @@ -14,17 +18,25 @@ export class School { active?: boolean; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { this.platform = (init as any).platform instanceof Platform @@ -40,13 +52,15 @@ export class School { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -55,8 +69,19 @@ export class School { } static fromRecord(record: Record, root?: EntityRoot): School { - const entity = new School(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new School(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -75,12 +100,19 @@ export class School { } static refer(id: string | number): School { - return new School({ id: String(id) } as Partial); + return School.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): School { - return new School().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): School { + return EntityCreation.bootstrap(context, "School", id, + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "School", + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -90,23 +122,101 @@ export class School { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform", + "school_type": "SchoolType" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + School.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "School", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -114,6 +224,7 @@ export class School { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "School", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -124,7 +235,8 @@ export class School { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -133,8 +245,10 @@ export class School { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -142,7 +256,7 @@ export class School { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -154,14 +268,12 @@ export class School { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -170,12 +282,16 @@ export class School { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -186,10 +302,14 @@ export class School { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -210,6 +330,10 @@ export class School { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -266,7 +390,7 @@ export class School { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts index 0677cb7d71363977bb4b42d7d44bce7d089cc983..3c933c84081b6a06762ebfe3453dc4551f5b8196 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/models/SchoolType.ts @@ -1,26 +1,32 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class SchoolType { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("SchoolType", + ["platform", "id", "name", "code", "display_order", "version"], { id: "immutable_field", version: "immutable_field" }); platform?: Platform | string; id?: string; name?: string; code?: string; - displayOrder?: number; - version?: number; + displayOrder?: Decimal; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolList"]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { @@ -41,24 +47,32 @@ export class SchoolType { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): SchoolType { - const entity = new SchoolType(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new SchoolType(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -77,12 +91,19 @@ export class SchoolType { } static refer(id: string | number): SchoolType { - return new SchoolType({ id: String(id) } as Partial); + return SchoolType.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): SchoolType { - return new SchoolType().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): SchoolType { + return EntityCreation.bootstrap(context, "SchoolType", id, + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "SchoolType", + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -92,23 +113,127 @@ export class SchoolType { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + SchoolType.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] @@ -116,6 +241,7 @@ export class SchoolType { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -126,7 +252,8 @@ export class SchoolType { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -135,22 +262,25 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -158,7 +288,7 @@ export class SchoolType { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -170,28 +300,27 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -200,12 +329,16 @@ export class SchoolType { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -216,24 +349,29 @@ export class SchoolType { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -249,6 +387,10 @@ export class SchoolType { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -270,14 +412,15 @@ export class SchoolType { return this; } - updateDisplayOrder(value: number): this { + updateDisplayOrder(value: Decimal): this { + if (value != null) value = decimal(value); this.displayOrder = value; this.markLoaded("displayOrder"); (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts index af9cf03a986e08d02115cba30825e5e6b3bbfdf6..a36d62e09bcd438cc795838878869315b4813268 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -147,13 +154,13 @@ export class PlatformRequest { - selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeListWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolTypeList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -162,17 +169,19 @@ export class PlatformRequest { haveSchoolTypes(): this { return this.withSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } haveNoSchoolTypes(): this { return this.withoutSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } - withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -183,7 +192,7 @@ export class PlatformRequest { return this; } - withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -195,17 +204,19 @@ export class PlatformRequest { } haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -216,7 +227,7 @@ export class PlatformRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -233,13 +244,13 @@ export class PlatformRequest { countSchoolTypesAs(alias: string): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); - this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.countSchoolTypesWith(alias, { entityName: "SchoolType", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; return this; } - countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolTypesWith(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -251,10 +262,10 @@ export class PlatformRequest { minDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.minDisplayOrderOfSchoolTypesAs( - "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "minOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + minDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "displayOrder", alias); @@ -265,10 +276,10 @@ export class PlatformRequest { maxDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.maxDisplayOrderOfSchoolTypesAs( - "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "maxOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "displayOrder", alias); @@ -279,10 +290,10 @@ export class PlatformRequest { sumDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sumDisplayOrderOfSchoolTypesAs( - "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sumOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "displayOrder", alias); @@ -293,10 +304,10 @@ export class PlatformRequest { avgDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.avgDisplayOrderOfSchoolTypesAs( - "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "avgOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "displayOrder", alias); @@ -307,10 +318,10 @@ export class PlatformRequest { standardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.standardDeviationDisplayOrderOfSchoolTypesAs( - "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "standardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "displayOrder", alias); @@ -321,10 +332,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( - "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "displayOrder", alias); @@ -335,10 +346,10 @@ export class PlatformRequest { sampleVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sampleVarianceDisplayOrderOfSchoolTypesAs( - "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sampleVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "displayOrder", alias); @@ -349,10 +360,10 @@ export class PlatformRequest { samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( - "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "displayOrder", alias); @@ -366,13 +377,13 @@ export class PlatformRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -384,10 +395,10 @@ export class PlatformRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -398,10 +409,10 @@ export class PlatformRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -412,10 +423,10 @@ export class PlatformRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -426,10 +437,10 @@ export class PlatformRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -440,10 +451,10 @@ export class PlatformRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -454,10 +465,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -468,10 +479,10 @@ export class PlatformRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -482,10 +493,10 @@ export class PlatformRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -494,47 +505,47 @@ export class PlatformRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -559,42 +570,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -648,42 +659,42 @@ export class PlatformRequest { return this; } - withBaseUrlIsNot(val: any): this { + withBaseUrlIsNot(val: string): this { this.filters.push({ "baseUrl": { "$ne": val } }); return this; } - withBaseUrlIn(...vals: any[]): this { + withBaseUrlIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$in": vals } }); return this; } - withBaseUrlNotIn(...vals: any[]): this { + withBaseUrlNotIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$notIn": vals } }); return this; } - withBaseUrlGreaterThan(val: any): this { + withBaseUrlGreaterThan(val: string): this { this.filters.push({ "baseUrl": { "$gt": val } }); return this; } - withBaseUrlGreaterThanOrEqualTo(val: any): this { + withBaseUrlGreaterThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$gte": val } }); return this; } - withBaseUrlLessThan(val: any): this { + withBaseUrlLessThan(val: string): this { this.filters.push({ "baseUrl": { "$lt": val } }); return this; } - withBaseUrlLessThanOrEqualTo(val: any): this { + withBaseUrlLessThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$lte": val } }); return this; } - withBaseUrlBetween(lower: any, upper: any): this { + withBaseUrlBetween(lower: string, upper: string): this { this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); return this; } @@ -727,47 +738,47 @@ export class PlatformRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -782,47 +793,47 @@ export class PlatformRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -837,47 +848,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -976,7 +987,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -985,7 +996,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByBaseUrl(): this { @@ -994,7 +1005,7 @@ export class PlatformRequest { } groupByBaseUrlAs(retName: string): this { - this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + this.query.groupBy("baseUrl", retName); return this; } groupByCreateTime(): this { @@ -1003,7 +1014,7 @@ export class PlatformRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1012,7 +1023,7 @@ export class PlatformRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1021,7 +1032,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -1134,9 +1145,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts index b1d1f11cae603fc771ec91ab1a91723a69b72a0e..02c627e0ba4cb3f175cc3d740f2094c95096eb23 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { School } from '../models/School'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolRequest { else this.selectSelfFields(); } + get entityName(): "School" { + return "School"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -162,14 +169,14 @@ export class SchoolRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); return this; } - selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.select(["schoolType"]); this.query.relationQuery( "schoolType", request.toQuery(), "schoolType", "id", false, @@ -177,7 +184,7 @@ export class SchoolRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -186,7 +193,7 @@ export class SchoolRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -194,7 +201,7 @@ export class SchoolRequest { }); return this; } - withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -203,7 +210,7 @@ export class SchoolRequest { return this; } - withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -215,47 +222,47 @@ export class SchoolRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -328,42 +335,42 @@ export class SchoolRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -417,42 +424,42 @@ export class SchoolRequest { return this; } - withAddressIsNot(val: any): this { + withAddressIsNot(val: string): this { this.filters.push({ "address": { "$ne": val } }); return this; } - withAddressIn(...vals: any[]): this { + withAddressIn(...vals: string[]): this { this.filters.push({ "address": { "$in": vals } }); return this; } - withAddressNotIn(...vals: any[]): this { + withAddressNotIn(...vals: string[]): this { this.filters.push({ "address": { "$notIn": vals } }); return this; } - withAddressGreaterThan(val: any): this { + withAddressGreaterThan(val: string): this { this.filters.push({ "address": { "$gt": val } }); return this; } - withAddressGreaterThanOrEqualTo(val: any): this { + withAddressGreaterThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$gte": val } }); return this; } - withAddressLessThan(val: any): this { + withAddressLessThan(val: string): this { this.filters.push({ "address": { "$lt": val } }); return this; } - withAddressLessThanOrEqualTo(val: any): this { + withAddressLessThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$lte": val } }); return this; } - withAddressBetween(lower: any, upper: any): this { + withAddressBetween(lower: string, upper: string): this { this.filters.push({ "address": { "$between": [lower, upper] } }); return this; } @@ -496,47 +503,47 @@ export class SchoolRequest { return this; } - withEstablishedDateIs(val: any): this { + withEstablishedDateIs(val: string): this { this.filters.push({ "establishedDate": { "$eq": val } }); return this; } - withEstablishedDateIsNot(val: any): this { + withEstablishedDateIsNot(val: string): this { this.filters.push({ "establishedDate": { "$ne": val } }); return this; } - withEstablishedDateIn(...vals: any[]): this { + withEstablishedDateIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$in": vals } }); return this; } - withEstablishedDateNotIn(...vals: any[]): this { + withEstablishedDateNotIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$notIn": vals } }); return this; } - withEstablishedDateGreaterThan(val: any): this { + withEstablishedDateGreaterThan(val: string): this { this.filters.push({ "establishedDate": { "$gt": val } }); return this; } - withEstablishedDateGreaterThanOrEqualTo(val: any): this { + withEstablishedDateGreaterThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$gte": val } }); return this; } - withEstablishedDateLessThan(val: any): this { + withEstablishedDateLessThan(val: string): this { this.filters.push({ "establishedDate": { "$lt": val } }); return this; } - withEstablishedDateLessThanOrEqualTo(val: any): this { + withEstablishedDateLessThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$lte": val } }); return this; } - withEstablishedDateBetween(lower: any, upper: any): this { + withEstablishedDateBetween(lower: string, upper: string): this { this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); return this; } @@ -551,47 +558,47 @@ export class SchoolRequest { return this; } - withStudentCapacityIs(val: any): this { + withStudentCapacityIs(val: number): this { this.filters.push({ "studentCapacity": { "$eq": val } }); return this; } - withStudentCapacityIsNot(val: any): this { + withStudentCapacityIsNot(val: number): this { this.filters.push({ "studentCapacity": { "$ne": val } }); return this; } - withStudentCapacityIn(...vals: any[]): this { + withStudentCapacityIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$in": vals } }); return this; } - withStudentCapacityNotIn(...vals: any[]): this { + withStudentCapacityNotIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$notIn": vals } }); return this; } - withStudentCapacityGreaterThan(val: any): this { + withStudentCapacityGreaterThan(val: number): this { this.filters.push({ "studentCapacity": { "$gt": val } }); return this; } - withStudentCapacityGreaterThanOrEqualTo(val: any): this { + withStudentCapacityGreaterThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$gte": val } }); return this; } - withStudentCapacityLessThan(val: any): this { + withStudentCapacityLessThan(val: number): this { this.filters.push({ "studentCapacity": { "$lt": val } }); return this; } - withStudentCapacityLessThanOrEqualTo(val: any): this { + withStudentCapacityLessThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$lte": val } }); return this; } - withStudentCapacityBetween(lower: any, upper: any): this { + withStudentCapacityBetween(lower: number, upper: number): this { this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); return this; } @@ -615,42 +622,42 @@ export class SchoolRequest { this.filters.push({ "active": { "$eq": false } }); return this; } - withActiveIsNot(val: any): this { + withActiveIsNot(val: boolean): this { this.filters.push({ "active": { "$ne": val } }); return this; } - withActiveIn(...vals: any[]): this { + withActiveIn(...vals: boolean[]): this { this.filters.push({ "active": { "$in": vals } }); return this; } - withActiveNotIn(...vals: any[]): this { + withActiveNotIn(...vals: boolean[]): this { this.filters.push({ "active": { "$notIn": vals } }); return this; } - withActiveGreaterThan(val: any): this { + withActiveGreaterThan(val: boolean): this { this.filters.push({ "active": { "$gt": val } }); return this; } - withActiveGreaterThanOrEqualTo(val: any): this { + withActiveGreaterThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$gte": val } }); return this; } - withActiveLessThan(val: any): this { + withActiveLessThan(val: boolean): this { this.filters.push({ "active": { "$lt": val } }); return this; } - withActiveLessThanOrEqualTo(val: any): this { + withActiveLessThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$lte": val } }); return this; } - withActiveBetween(lower: any, upper: any): this { + withActiveBetween(lower: boolean, upper: boolean): this { this.filters.push({ "active": { "$between": [lower, upper] } }); return this; } @@ -665,47 +672,47 @@ export class SchoolRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -720,47 +727,47 @@ export class SchoolRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -775,47 +782,47 @@ export class SchoolRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -1010,7 +1017,7 @@ export class SchoolRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPlatform(): this { @@ -1019,7 +1026,7 @@ export class SchoolRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupBySchoolType(): this { @@ -1028,7 +1035,7 @@ export class SchoolRequest { } groupBySchoolTypeAs(retName: string): this { - this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + this.query.groupBy("schoolType", retName); return this; } groupByName(): this { @@ -1037,7 +1044,7 @@ export class SchoolRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByAddress(): this { @@ -1046,7 +1053,7 @@ export class SchoolRequest { } groupByAddressAs(retName: string): this { - this.query.groupBy("address"); // In TS we don't alias group by yet natively + this.query.groupBy("address", retName); return this; } groupByEstablishedDate(): this { @@ -1055,7 +1062,7 @@ export class SchoolRequest { } groupByEstablishedDateAs(retName: string): this { - this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + this.query.groupBy("establishedDate", retName); return this; } groupByStudentCapacity(): this { @@ -1064,7 +1071,7 @@ export class SchoolRequest { } groupByStudentCapacityAs(retName: string): this { - this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + this.query.groupBy("studentCapacity", retName); return this; } groupByActive(): this { @@ -1073,7 +1080,7 @@ export class SchoolRequest { } groupByActiveAs(retName: string): this { - this.query.groupBy("active"); // In TS we don't alias group by yet natively + this.query.groupBy("active", retName); return this; } groupByCreateTime(): this { @@ -1082,7 +1089,7 @@ export class SchoolRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1091,7 +1098,7 @@ export class SchoolRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1100,14 +1107,14 @@ export class SchoolRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1117,7 +1124,7 @@ export class SchoolRequest { facetBySchoolTypeAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "schoolType", request, includeAllFacets, @@ -1233,9 +1240,10 @@ export class ExecutableSchoolRequest { return this; } - newEntity(context: UserContext): School { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new School(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return School.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts index 8d09b5f34a9b4b2aeee292bcfb05406959efef90..0eb932a414f079e38f575598bd0212c567b84edb 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { SchoolType } from '../models/SchoolType'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolTypeRequest { else this.selectSelfFields(); } + get entityName(): "SchoolType" { + return "SchoolType"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolTypeRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -140,7 +147,7 @@ export class SchoolTypeRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -148,7 +155,7 @@ export class SchoolTypeRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -157,7 +164,7 @@ export class SchoolTypeRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -166,7 +173,7 @@ export class SchoolTypeRequest { return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "schoolType", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -175,17 +182,19 @@ export class SchoolTypeRequest { haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -196,7 +205,7 @@ export class SchoolTypeRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -213,13 +222,13 @@ export class SchoolTypeRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -231,10 +240,10 @@ export class SchoolTypeRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -245,10 +254,10 @@ export class SchoolTypeRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -259,10 +268,10 @@ export class SchoolTypeRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -273,10 +282,10 @@ export class SchoolTypeRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -287,10 +296,10 @@ export class SchoolTypeRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -301,10 +310,10 @@ export class SchoolTypeRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -315,10 +324,10 @@ export class SchoolTypeRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -329,10 +338,10 @@ export class SchoolTypeRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -361,47 +370,47 @@ export class SchoolTypeRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -426,42 +435,42 @@ export class SchoolTypeRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -515,42 +524,42 @@ export class SchoolTypeRequest { return this; } - withCodeIsNot(val: any): this { + withCodeIsNot(val: string): this { this.filters.push({ "code": { "$ne": val } }); return this; } - withCodeIn(...vals: any[]): this { + withCodeIn(...vals: string[]): this { this.filters.push({ "code": { "$in": vals } }); return this; } - withCodeNotIn(...vals: any[]): this { + withCodeNotIn(...vals: string[]): this { this.filters.push({ "code": { "$notIn": vals } }); return this; } - withCodeGreaterThan(val: any): this { + withCodeGreaterThan(val: string): this { this.filters.push({ "code": { "$gt": val } }); return this; } - withCodeGreaterThanOrEqualTo(val: any): this { + withCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$gte": val } }); return this; } - withCodeLessThan(val: any): this { + withCodeLessThan(val: string): this { this.filters.push({ "code": { "$lt": val } }); return this; } - withCodeLessThanOrEqualTo(val: any): this { + withCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$lte": val } }); return this; } - withCodeBetween(lower: any, upper: any): this { + withCodeBetween(lower: string, upper: string): this { this.filters.push({ "code": { "$between": [lower, upper] } }); return this; } @@ -594,47 +603,47 @@ export class SchoolTypeRequest { return this; } - withDisplayOrderIs(val: any): this { + withDisplayOrderIs(val: Decimal): this { this.filters.push({ "displayOrder": { "$eq": val } }); return this; } - withDisplayOrderIsNot(val: any): this { + withDisplayOrderIsNot(val: Decimal): this { this.filters.push({ "displayOrder": { "$ne": val } }); return this; } - withDisplayOrderIn(...vals: any[]): this { + withDisplayOrderIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$in": vals } }); return this; } - withDisplayOrderNotIn(...vals: any[]): this { + withDisplayOrderNotIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$notIn": vals } }); return this; } - withDisplayOrderGreaterThan(val: any): this { + withDisplayOrderGreaterThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$gt": val } }); return this; } - withDisplayOrderGreaterThanOrEqualTo(val: any): this { + withDisplayOrderGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$gte": val } }); return this; } - withDisplayOrderLessThan(val: any): this { + withDisplayOrderLessThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$lt": val } }); return this; } - withDisplayOrderLessThanOrEqualTo(val: any): this { + withDisplayOrderLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$lte": val } }); return this; } - withDisplayOrderBetween(lower: any, upper: any): this { + withDisplayOrderBetween(lower: Decimal, upper: Decimal): this { this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); return this; } @@ -649,47 +658,47 @@ export class SchoolTypeRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -842,7 +851,7 @@ export class SchoolTypeRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupById(): this { @@ -851,7 +860,7 @@ export class SchoolTypeRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -860,7 +869,7 @@ export class SchoolTypeRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCode(): this { @@ -869,7 +878,7 @@ export class SchoolTypeRequest { } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } groupByDisplayOrder(): this { @@ -878,7 +887,7 @@ export class SchoolTypeRequest { } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } groupByVersion(): this { @@ -887,14 +896,14 @@ export class SchoolTypeRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1010,9 +1019,10 @@ export class ExecutableSchoolTypeRequest { return this; } - newEntity(context: UserContext): SchoolType { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new SchoolType(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return SchoolType.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts b/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts index 8f85334eadcd8cf4c401500f53cdb51ca806f9b5..4f546ca95babfcdba5358e5720414f21f8ddf7a6 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/runtime-module.ts @@ -1,3 +1,4 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; import { ObjectLocation, RuntimeModule } from "teaql-ts"; import { ENTITY_SCHEMAS } from "./teaql-schemas"; import { ensureGeneratedBootstrap } from "./generated-bootstrap"; @@ -144,7 +145,7 @@ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { }, { ...{ defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, constants: [ - { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary School", "code": "PRIMARY", "displayOrder": 1 } }, - { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary School", "code": "PRIMARY", "displayOrder": decimal("1") } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": decimal("2") } } ] }, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts index 8c4af67824ab9c6712d12cb9c231db91c4731e3f..47c029fe0666369302f3c4e9a42940c15abc2057 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-schemas.ts @@ -10,13 +10,13 @@ export const ENTITY_SCHEMAS: Record = { "SchoolType": { table: "school_type_data", auditMaskFields: [], - columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} }, "School": { table: "school_data", auditMaskFields: [], - columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} } }; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts b/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts index b54a29ac3c12fb072cf4c292e22bb2e644b56319..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts +++ b/source/teaql-ts/examples/school-management/src/reconciled/teaql-ts.ts @@ -1,14 +1,26 @@ import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, SelectQuery as RuntimeSelectQuery, UserContext, - executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, } from "teaql-ts"; export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; -export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; function soundex(input: unknown): string { const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); @@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; preflightMutation(mutation: any): any; afterGraphCommit(work: () => void): void; afterGraphRollback(work: () => void): void; @@ -52,18 +65,24 @@ export interface TeaQLDataService { close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; private readonly checkers: Record = {}; + private readonly schemas: Record = {}; private userContext = new UserContext(); private graphSaveActive = false; + private activeGraph?: GraphMutationSession; private graphCommitActions: Array<() => void> = []; private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; private graphSaveTail: Promise = Promise.resolve(); private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService { /** Installs passive generated metadata. It never mutates storage. */ install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); return this; } + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + setUserContext(context: UserContext): this { this.userContext = context; return this; @@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService { return [...this.mutationGovernanceEvents]; } + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } const predecessor = this.graphSaveTail; let release!: () => void; this.graphSaveTail = new Promise(resolve => { release = resolve; }); @@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService { const nextIdsSnapshot = { ...this.nextIds }; let fixEvidenceStarted = false; let mutationPolicyGraphStarted = false; + let committed = false; try { + graph.validatePreparedSources(); this.graphSaveActive = true; + this.activeGraph = graph; this.graphCommitActions = []; this.graphRollbackActions = []; - this.userContext.insertResource("fixTime", new Date()); - this.userContext.beginFixEvidence(); - fixEvidenceStarted = true; - this.userContext.beginMutationPolicyGraph(); + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); const result = await work(graph); - this.userContext.ensureMutationPolicyGraphComplete(); - this.persist(); - for (const action of this.graphCommitActions) action(); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); return result; } catch (error) { - this.data = dataSnapshot; - this.nextIds = nextIdsSnapshot; - for (const action of [...this.graphRollbackActions].reverse()) action(); + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } throw error; } finally { this.graphSaveActive = false; + this.activeGraph = undefined; this.graphCommitActions = []; this.graphRollbackActions = []; - if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); - this.userContext.removeResource("fixTime"); - if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); release(); } } @@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService { } preflightMutation(mutation: any): any { - mutation = this.checkAndFixMutation(mutation); - this.userContext.recordMutationPolicyPreflight(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); return mutation; } private checkAndFixMutation(mutation: any): any { - if (mutation instanceof MutationRequest) mutation = mutation.mutation; - if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; - const checker = this.checkers[String(mutation.entity)]; - if (!checker) return mutation; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } const results: any[] = []; const ownsFixTime = this.userContext.getResource("fixTime") === undefined; - if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); try { checker.checkAndFix(this.userContext, mutation, results); - if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); - this.userContext.translateCheckResults(results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); if (results.length) throw new CheckException(results); - return mutation; + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } } async executeMutation(mutation: any): Promise { - mutation = this.checkAndFixMutation(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); const mutationGovernance = this.userContext.enterMutationPolicy(mutation); - this.mutationGovernanceEvents.push(mutationGovernance); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; if (!this.graphSaveActive) this.persist(); - return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; - } - if (mutation.action === "Update") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { - throw new Error( - `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); - } - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Delete") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { throw new Error( `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); } - table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; if (!(query instanceof RuntimeSelectQuery)) { throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); } query.prepareForList(); - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); - if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); @@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService { if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); - if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; - if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; - if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; - if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; - if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; @@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService { }))]; } for (const order of [...query.orderItems].reverse()) { - rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); } const start = query.offsetValue || 0; rows = rows.slice(start, start + query.limitValue); for (const relation of (query.relations || []) as any[]) { - const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); - const relatedRows = (await this.executeQuery(relation.query)).filter( - (row: any) => localValues.has(row[relation.foreignKey || "id"])); for (const row of rows) { - const matches = relatedRows.filter( - (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); row[relation.name] = relation.many === false ? matches[0] : matches; } } @@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService { rows = rows.map((row: any) => Object.fromEntries( Object.entries(row).filter(([field]) => selections.has(field)))); } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); return rows; } async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { @@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService { return value; } async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); const rows = await this.executeQuery(query); for (let offset = 0; offset < rows.length; offset += chunkSize) { diff --git a/source/teaql-ts/examples/school-management/src/runtime-module.ts b/source/teaql-ts/examples/school-management/src/runtime-module.ts index 9e03a4e5cb463203c4cf7323fbb77a4e98d2b952..2ff822eb0deb888082751850f2be8bf6d1941bd3 100644 --- a/source/teaql-ts/examples/school-management/src/runtime-module.ts +++ b/source/teaql-ts/examples/school-management/src/runtime-module.ts @@ -1,3 +1,4 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; import { ObjectLocation, RuntimeModule } from "teaql-ts"; import { ENTITY_SCHEMAS } from "./teaql-schemas"; import { ensureGeneratedBootstrap } from "./generated-bootstrap"; @@ -144,7 +145,7 @@ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { }, { ...{ defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, constants: [ - { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": 1 } }, - { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": decimal("1") } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": decimal("2") } } ] }, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-schemas.ts b/source/teaql-ts/examples/school-management/src/teaql-schemas.ts index 8c4af67824ab9c6712d12cb9c231db91c4731e3f..47c029fe0666369302f3c4e9a42940c15abc2057 100644 --- a/source/teaql-ts/examples/school-management/src/teaql-schemas.ts +++ b/source/teaql-ts/examples/school-management/src/teaql-schemas.ts @@ -10,13 +10,13 @@ export const ENTITY_SCHEMAS: Record = { "SchoolType": { table: "school_type_data", auditMaskFields: [], - columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} }, "School": { table: "school_data", auditMaskFields: [], - columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} } }; \ No newline at end of file diff --git a/source/teaql-ts/examples/school-management/src/teaql-ts.ts b/source/teaql-ts/examples/school-management/src/teaql-ts.ts index b54a29ac3c12fb072cf4c292e22bb2e644b56319..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/school-management/src/teaql-ts.ts +++ b/source/teaql-ts/examples/school-management/src/teaql-ts.ts @@ -1,14 +1,26 @@ import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, SelectQuery as RuntimeSelectQuery, UserContext, - executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, } from "teaql-ts"; export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; -export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; function soundex(input: unknown): string { const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); @@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; preflightMutation(mutation: any): any; afterGraphCommit(work: () => void): void; afterGraphRollback(work: () => void): void; @@ -52,18 +65,24 @@ export interface TeaQLDataService { close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; private readonly checkers: Record = {}; + private readonly schemas: Record = {}; private userContext = new UserContext(); private graphSaveActive = false; + private activeGraph?: GraphMutationSession; private graphCommitActions: Array<() => void> = []; private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; private graphSaveTail: Promise = Promise.resolve(); private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService { /** Installs passive generated metadata. It never mutates storage. */ install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); return this; } + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + setUserContext(context: UserContext): this { this.userContext = context; return this; @@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService { return [...this.mutationGovernanceEvents]; } + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } const predecessor = this.graphSaveTail; let release!: () => void; this.graphSaveTail = new Promise(resolve => { release = resolve; }); @@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService { const nextIdsSnapshot = { ...this.nextIds }; let fixEvidenceStarted = false; let mutationPolicyGraphStarted = false; + let committed = false; try { + graph.validatePreparedSources(); this.graphSaveActive = true; + this.activeGraph = graph; this.graphCommitActions = []; this.graphRollbackActions = []; - this.userContext.insertResource("fixTime", new Date()); - this.userContext.beginFixEvidence(); - fixEvidenceStarted = true; - this.userContext.beginMutationPolicyGraph(); + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); const result = await work(graph); - this.userContext.ensureMutationPolicyGraphComplete(); - this.persist(); - for (const action of this.graphCommitActions) action(); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); return result; } catch (error) { - this.data = dataSnapshot; - this.nextIds = nextIdsSnapshot; - for (const action of [...this.graphRollbackActions].reverse()) action(); + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } throw error; } finally { this.graphSaveActive = false; + this.activeGraph = undefined; this.graphCommitActions = []; this.graphRollbackActions = []; - if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); - this.userContext.removeResource("fixTime"); - if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); release(); } } @@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService { } preflightMutation(mutation: any): any { - mutation = this.checkAndFixMutation(mutation); - this.userContext.recordMutationPolicyPreflight(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); return mutation; } private checkAndFixMutation(mutation: any): any { - if (mutation instanceof MutationRequest) mutation = mutation.mutation; - if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; - const checker = this.checkers[String(mutation.entity)]; - if (!checker) return mutation; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } const results: any[] = []; const ownsFixTime = this.userContext.getResource("fixTime") === undefined; - if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); try { checker.checkAndFix(this.userContext, mutation, results); - if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); - this.userContext.translateCheckResults(results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); if (results.length) throw new CheckException(results); - return mutation; + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } } async executeMutation(mutation: any): Promise { - mutation = this.checkAndFixMutation(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); const mutationGovernance = this.userContext.enterMutationPolicy(mutation); - this.mutationGovernanceEvents.push(mutationGovernance); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; if (!this.graphSaveActive) this.persist(); - return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; - } - if (mutation.action === "Update") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { - throw new Error( - `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); - } - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Delete") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { throw new Error( `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); } - table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; if (!(query instanceof RuntimeSelectQuery)) { throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); } query.prepareForList(); - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); - if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); @@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService { if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); - if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; - if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; - if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; - if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; - if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; @@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService { }))]; } for (const order of [...query.orderItems].reverse()) { - rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); } const start = query.offsetValue || 0; rows = rows.slice(start, start + query.limitValue); for (const relation of (query.relations || []) as any[]) { - const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); - const relatedRows = (await this.executeQuery(relation.query)).filter( - (row: any) => localValues.has(row[relation.foreignKey || "id"])); for (const row of rows) { - const matches = relatedRows.filter( - (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); row[relation.name] = relation.many === false ? matches[0] : matches; } } @@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService { rows = rows.map((row: any) => Object.fromEntries( Object.entries(row).filter(([field]) => selections.has(field)))); } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); return rows; } async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { @@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService { return value; } async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); const rows = await this.executeQuery(query); for (let offset = 0; offset < rows.length; offset += chunkSize) { diff --git a/source/teaql-ts/examples/school-management/verify-file-bootstrap.cjs b/source/teaql-ts/examples/school-management/verify-file-bootstrap.cjs new file mode 100644 index 0000000000000000000000000000000000000000..da391cafe57be974077800e6713002c64df4f9ab --- /dev/null +++ b/source/teaql-ts/examples/school-management/verify-file-bootstrap.cjs @@ -0,0 +1,34 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),assert=require('node:assert/strict'),crypto=require('node:crypto'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const repo=path.resolve(__dirname,'../..'),sha=b=>crypto.createHash('sha256').update(b).digest('hex'); +async function main(){ + const supplied=process.env.TEAQL_FILE_BOOTSTRAP_OUTPUT;assert(supplied&&path.isAbsolute(supplied));assert(!fs.existsSync(supplied));fs.mkdirSync(supplied,{recursive:true}); + const report={schema:'teaql.typescript-file-bootstrap-example/v1',passed:false,rounds:[],sameStores:true,manualSeed:false}; + const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-file-bootstrap-build-'));let runner; + try{ + runner=createOwnedRunner();const config=path.join(scratch,'jest.cjs'),tsconfig=path.join(scratch,'tsconfig.json'); + fs.writeFileSync(tsconfig,JSON.stringify({extends:path.join(repo,'tsconfig.json'),compilerOptions:{baseUrl:repo,types:['node','jest'],typeRoots:[path.join(repo,'node_modules/@types')],paths:{'teaql-ts':[path.join(repo,'src/index.ts')],'teaql-ts/*':[path.join(repo,'src/*')]}}})); + fs.writeFileSync(config,'module.exports = '+JSON.stringify({rootDir:repo,roots:[__dirname],testEnvironment:'node', + testMatch:['**/examples/school-management/file-bootstrap.test.ts'],moduleNameMapper:{'^teaql-ts$':path.join(repo,'src/index.ts'),'^teaql-ts/(.*)$':path.join(repo,'src/$1')}, + transform:{'^.+\\.tsx?$':['ts-jest',{tsconfig}]}})+';\n'); + for(const round of [1,2]){ + const log=path.join(supplied,'round-'+round+'.log'),fd=fs.openSync(log,'wx');let result; + try{result=await runner.run([process.execPath,path.join(repo,'node_modules/jest/bin/jest.js'),'--config',config,'--runInBand','--cacheDirectory',path.join(scratch,'jest')], + {cwd:repo,env:{...process.env,TEAQL_FILE_BOOTSTRAP_EVIDENCE_DIR:supplied,TEAQL_FILE_BOOTSTRAP_ROUND:String(round)},timeout:120000,stdio:['ignore',fd,fd]});} + finally{fs.closeSync(fd);} + const bytes=fs.readFileSync(log),text=bytes.toString();report.rounds.push({round,exitCode:result.status,signal:result.signal,logSha256:sha(bytes)}); + assert.equal(result.status,0,text.slice(-14000)); + const rows=text.split(/\r?\n/).filter(l=>l.startsWith('FILE_BOOTSTRAP=')).map(l=>JSON.parse(l.slice('FILE_BOOTSTRAP='.length))); + assert.deepEqual(rows.map(r=>r.scenario).sort(),['concurrent','conflict','floor','reconcile','rejected','school']);assert(rows.every(r=>r.passed&&r.round===round)); + }report.passed=true; + }catch(error){report.error=error.stack;console.error(error.stack);process.exitCode=1;} + finally{ + report.cleanup={sharedCachesDeleted:false,sourceOrDatabasesDeleted:false}; + if(!runner||runner.safeToClean){report.cleanup.disposedOwnedBytes=ownedBytes(scratch);fs.rmSync(scratch,{recursive:true});report.cleanup.scratchRemoved=true;} + else{report.cleanup.scratchRemoved=false;report.cleanup.unsafeRetention=scratch;report.passed=false;process.exitCode=1;} + runner?.dispose();fs.writeFileSync(path.join(supplied,'receipt.json'),JSON.stringify(report,null,2)+'\n',{flag:'wx'}); + console.log(JSON.stringify({passed:report.passed,directory:supplied,error:report.error})); + } +} +main().catch(error=>{console.error(error.stack);process.exitCode=1;}); diff --git a/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts b/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts index 9842d593458074c4269cfef76e420b898a556062..9aa31f42fbd474942b848140156f6fa75330847b 100644 --- a/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts +++ b/source/teaql-ts/examples/task-board/app-dynamic/src/main.ts @@ -1,40 +1,21 @@ -import fetch from 'node-fetch'; -import { TeaQLClient, QueryParser } from '../../../../src'; +import { QueryParser, SmartList, TeaQLClient, UserContext } from 'teaql-ts'; import { Q } from '../../ts-lib-core/src/generated/Q'; +import { Task } from '../../ts-lib-core/src/generated/models/Task'; -// 1. Initialize TFP Client, pointing to the Rust backend -const client = new TeaQLClient({ - baseUrl: 'http://127.0.0.1:3001', - fetch: fetch as any -}); +export const taskQuery = 'Q.tasksWithMinimalFields().selectName().withNameContaining("bug-")' + + '.orderByIdAscending().limit(20).comment("load dynamic bug task list").purpose("render the task board")'; -// 2. Prepare request context -const ctx = { client }; - -async function runDynamicExamples() { - try { - console.log("=== Dynamic String Query Examples ==="); - - // Example A: Dynamic filtering query - const filterQuery = 'Q.tasks().withNameContaining("bug")'; - console.log(`[Execution]: ${filterQuery}`); - - // Parse the string DSL into AST and execute (pass entry object Q) - const filterRequest = QueryParser.parse(filterQuery, Q); - const filterResult = await filterRequest.executeForList(ctx); - console.log("Result:", filterResult); - - // Example B: Dynamic aggregation and grouping - const userQueryStr = 'Q.tasks().withNameContaining("bug").facetByStatusAs("statusFacet", Q.taskStatuses().count())'; - console.log(`\n[Execution]: ${userQueryStr}`); - - const aggRequest = QueryParser.parse(userQueryStr, Q); - const aggResult = await aggRequest.executeForList(ctx); - console.log("Result:", aggResult); - - } catch (err) { - console.error("Query execution failed:", err); - } +/** The controlled parser builds a request; it never evaluates JavaScript. */ +export async function runDynamicExamples(context: UserContext): Promise> { + return QueryParser.parse(taskQuery, Q).executeForList(context); } -runDynamicExamples(); +if (require.main === module) { + const baseUrl = process.env.TEAQL_TASK_BOARD_BACKEND; + if (!baseUrl) throw new Error('Set TEAQL_TASK_BOARD_BACKEND for the optional HTTP demo; npm run verify uses local SQLite.'); + const client = new TeaQLClient({baseUrl}); + const context = new UserContext().insertResource('dataService', client); + runDynamicExamples(context).then(result => console.log(result)).catch(error => { + console.error(error); process.exitCode = 1; + }); +} diff --git a/source/teaql-ts/examples/task-board/app-native/src/main.ts b/source/teaql-ts/examples/task-board/app-native/src/main.ts index 36a1a74b3684e677efa8ef3f5ef654aa1ae22077..1c5dc42d080f16b10c9ee024d928822307633bdc 100644 --- a/source/teaql-ts/examples/task-board/app-native/src/main.ts +++ b/source/teaql-ts/examples/task-board/app-native/src/main.ts @@ -1,75 +1,29 @@ -import fetch from 'node-fetch'; -import { TeaQLClient } from '../../../../src'; +import { TeaQLClient, UserContext } from 'teaql-ts'; import { Q } from '../../ts-lib-core/src/generated/Q'; -import { Task } from '../../ts-lib-core/src/generated/models/Task'; -// 1. Initialize TFP Client, pointing to the Rust backend -const client = new TeaQLClient({ - baseUrl: 'http://127.0.0.1:3001', - fetch: fetch as any -}); - -// 2. Prepare request context -const ctx = { client }; - -async function runNativeExamples() { - try { - console.log("=== Native TypeScript Query Examples ==="); - - // Example A: Strongly-typed chained calls (Conditional filtering) - console.log("[Execution]: Q.tasks().withNameContaining('bug').purpose('find bugs')"); - const filterResult = await Q.tasks() - .withNameContaining("bug") - .purpose("find bugs") - .executeForList(ctx); - - console.log("Result:", filterResult); - - // Example B: Strongly-typed chained calls (Aggregation and Grouping) - console.log("\n[Execution]: Q.taskStatuses().groupByDisplayOrder().avgProgress().purpose('calc average')"); - const aggResult = await Q.taskStatuses() - .groupByDisplayOrder() - .avgProgress() - .purpose("calc average") - .executeForList(ctx); - - console.log("Result:", aggResult); - - // Example C: Strongly-typed chained calls (Nested Facet panel aggregation) - console.log("\n[Execution]: Q.tasks().facetByStatusAs('statusFacet', Q.taskStatuses().count()).purpose('dashboard render')"); - const facetResult = await Q.tasks() - .facetByStatusAs("statusFacet", Q.taskStatuses().count()) - .purpose("dashboard render") - .executeForList(ctx); - - console.log("Main data (Tasks):", facetResult.data); - console.log("Statistics panel (Facets):", facetResult.facets); - - // Example D: Data Mutations - console.log("\n[Execution]: Create Task"); - const task = new Task({ name: 'New Bug Task', status: 1001 }); - const saveResult = await task.auditAs("Create a new bug").save(ctx); - console.log("Create Result:", JSON.stringify(saveResult, null, 2)); - - const newId = saveResult.data[0].saved_data.id; - const newVersion = saveResult.data[0].saved_data.version; - console.log(`Retrieved newly created Task ID: ${newId}, Version: ${newVersion}`); - - console.log(`\n[Execution]: Update Task (ID: ${newId})`); - const updateTask = new Task({ id: newId, name: 'New Bug Task (Fixed)', status: 1004, version: newVersion }); - const updateResult = await updateTask.auditAs("Fix the bug").save(ctx); - console.log("Update Result:", JSON.stringify(updateResult, null, 2)); - - const updatedVersion = updateResult.data[0].saved_data.version; - - console.log(`\n[Execution]: Delete Task (ID: ${newId})`); - const taskToDelete = new Task({ id: newId, version: updatedVersion }); - const deleteResult = await taskToDelete.markForDeletion().auditAs("Clean up the bug").save(ctx); - console.log("Delete Result:", JSON.stringify(deleteResult, null, 2)); - - } catch (err) { - console.error("Query execution failed:", err); - } +/** The same query can run on local SQLite or an explicitly configured HTTP client. */ +export async function runNativeExamples(context: UserContext) { + const tasks = await Q.tasks().withNameContaining('bug-') + .selectStatusWith(Q.taskStatuses().comment('load task status')) + .selectTaskExecutionLogListWith(Q.taskExecutionLogs().orderByIdAscending().limit(10) + .comment('load bounded execution history')) + .orderByIdAscending().limit(20) + .comment('load bug tasks with status and history') + .purpose('render the task board').executeForList(context); + const facets = await Q.tasksWithMinimalFields().selectName().withNameContaining('bug-') + .facetByStatusAs('statusFacet', Q.taskStatuses().countAs('taskCount').orderByIdAscending().limit(10) + .comment('count tasks by status'), true) + .orderByIdAscending().limit(20) + .comment('load task status facets').purpose('render task board counters').executeForList(context); + return {tasks, facets}; } -runNativeExamples(); +if (require.main === module) { + const baseUrl = process.env.TEAQL_TASK_BOARD_BACKEND; + if (!baseUrl) throw new Error('Set TEAQL_TASK_BOARD_BACKEND for the optional HTTP demo; npm run verify uses local SQLite.'); + const client = new TeaQLClient({baseUrl}); + const context = new UserContext().insertResource('dataService', client); + runNativeExamples(context).then(result => console.log(result)).catch(error => { + console.error(error); process.exitCode = 1; + }); +} diff --git a/source/teaql-ts/examples/task-board/assist/create/task.md b/source/teaql-ts/examples/task-board/assist/create/task.md new file mode 100644 index 0000000000000000000000000000000000000000..2dd7bd339adf21580118afe83dd8698f619dc120 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/create/task.md @@ -0,0 +1,109 @@ + + +# TypeScript Assist — Create `Task` + +Use the exact generated `Q.tasks()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { Decimal, UserContext, decimal } from '../teaql-ts'; +import { Q } from './Q'; +import { Task } from './models/Task'; + +export interface CreateTaskInput { + name: string; + status: string | number; + platform: string | number; + +} + +export async function createTask( + input: CreateTaskInput, + context: UserContext, +): Promise { + const entity = await Q.tasks() + .comment('what: initialize Task') + .purpose('why: create Task') + .newEntity(context); + + entity.updateName(input.name); + entity.updateStatus(input.status); + entity.updatePlatform(input.platform); + + await entity + .auditAs('Create Task for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: +- `updateStatusToPlanned()` +- `updateStatusToReady()` +- `updateStatusToExecuting()` +- `updateStatusToVerified()` + + +For Decimal fields, construct exact values with `decimal('3.50')`. Do not pass a +JavaScript `number`, which can lose digits before the runtime sees it. + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + +## Compose one audited graph + +Create each child using its own generated Q entry point and Create Assist, then +attach it with the exact model-derived collection API: + +| Reverse relation | Child entry point | Attach | +| --- | --- | --- | +| `task_execution_log_list` | `Q.taskExecutionLogs()` | `entity.taskExecutionLogList().push(child)` | + + +Use `child.auditAs('authorize payment')` to add a local reason. Leave it unset +to inherit the root reason; creation-query comment is separate. Keep an existing +child marked with `child.markForDeletion().auditAs('remove unavailable item')` +in the composed graph. Call only `entity.auditAs('submit order').save(context)` +on the root. Generated cascades preserve branch-local reasons and assigned IDs; +the runtime emits committed audit only after the complete graph commits. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/task-board/assist/create/task_execution_log.md b/source/teaql-ts/examples/task-board/assist/create/task_execution_log.md new file mode 100644 index 0000000000000000000000000000000000000000..8e1e5d7b2b3c33d68142abacecd91d64554b7f2c --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/create/task_execution_log.md @@ -0,0 +1,87 @@ + + +# TypeScript Assist — Create `Task Execution Log` + +Use the exact generated `Q.taskExecutionLogs()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { Decimal, UserContext, decimal } from '../teaql-ts'; +import { Q } from './Q'; +import { TaskExecutionLog } from './models/TaskExecutionLog'; + +export interface CreateTaskExecutionLogInput { + task: string | number; + action: string; + detail: string; + +} + +export async function createTaskExecutionLog( + input: CreateTaskExecutionLogInput, + context: UserContext, +): Promise { + const entity = await Q.taskExecutionLogs() + .comment('what: initialize Task Execution Log') + .purpose('why: create Task Execution Log') + .newEntity(context); + + entity.updateTask(input.task); + entity.updateAction(input.action); + entity.updateDetail(input.detail); + + await entity + .auditAs('Create Task Execution Log for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +For Decimal fields, construct exact values with `decimal('3.50')`. Do not pass a +JavaScript `number`, which can lose digits before the runtime sees it. + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/task-board/assist/delete/task.md b/source/teaql-ts/examples/task-board/assist/delete/task.md new file mode 100644 index 0000000000000000000000000000000000000000..56eb52bc5b06c70790f5a5d8b33a46a5ada977ec --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/delete/task.md @@ -0,0 +1,72 @@ + + +# TypeScript Assist — Delete `Task` + +Load the current row and its original optimistic version. Never reconstruct an +entity from client-supplied ID/version. Delete is audited, version-aware soft +deletion; do not invent physical-delete APIs. + +```typescript +import { Q } from './Q'; +import { UserContext } from '../teaql-ts'; + +export async function deleteTask( + id: string, + context: UserContext, +): Promise { + const entity = await Q.tasks() + .withIdIs(id) + + .comment('what: load current Task for deletion') + .purpose('why: preserve original version for optimistic locking') + .executeForOne(context); + if (!entity) return false; + + await entity.markForDeletion() + .auditAs('Delete Task for the requested business operation') + .save(context); + return true; +} +``` + +Compile the source unchanged. Prove retained negative-version persistence, +normal-query hiding, `deletedRowsOnly()` visibility, stale-copy rejection, +not-found false, audit enforcement, and physical-delete compilation failure. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `delete`. + +- Load the policy-scoped current entity, mark it for deletion, then use audited + save with the same UserContext. Do not invent a physical-delete API. +- Require an audit reason and optimistic version. Test missing audit and stale + version as explicit failures. diff --git a/source/teaql-ts/examples/task-board/assist/expression/task.md b/source/teaql-ts/examples/task-board/assist/expression/task.md new file mode 100644 index 0000000000000000000000000000000000000000..387c96b8c22097d44566feef939dfc6fb499bc9d --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/expression/task.md @@ -0,0 +1,121 @@ + + +# TypeScript Assist — Expression `Task` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +Use the error's `toWire()` for structured diagnostics: `location` is the first +missing canonical path; `attemptedLocation` retains the full suffix and real +list indices. `expressionWithBrokenPoint` marks one `` in the complete +native chain. Use `suggestedFix.location` with Q Assist; never parse the message +or guess a preload method. + +```typescript +import { E } from './E'; +import { Task } from './models/Task'; + +export function extractId(entity: Task) { + return E.task(entity).id().eval(); +} + +export function extractIdOrElse( + entity: Task, fallback: NonNullable, +) { + return E.task(entity).id().orElse(fallback); +} + +export function extractName(entity: Task) { + return E.task(entity).name().eval(); +} + +export function extractNameOrElse( + entity: Task, fallback: NonNullable, +) { + return E.task(entity).name().orElse(fallback); +} + +export function extractVersion(entity: Task) { + return E.task(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: Task, fallback: NonNullable, +) { + return E.task(entity).version().orElse(fallback); +} + +export function extractStatusId(entity: Task) { + return E.task(entity).statusId().eval(); +} + +export function traverseStatus(entity: Task) { + return E.task(entity).status().eval(); +} + +export function extractPlatformId(entity: Task) { + return E.task(entity).platformId().eval(); +} + +export function traversePlatform(entity: Task) { + return E.task(entity).platform().eval(); +} + +export function aggregateTaskExecutionLogListSize(entity: Task) { + return E.task(entity).taskExecutionLogList().size().eval(); +} + +export function firstTaskExecutionLogListId(entity: Task) { + return E.task(entity).taskExecutionLogList().first().id().eval(); +} + +export function getTaskExecutionLogListId(entity: Task, index: number) { + return E.task(entity).taskExecutionLogList().get(index).id().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/task-board/assist/expression/task_execution_log.md b/source/teaql-ts/examples/task-board/assist/expression/task_execution_log.md new file mode 100644 index 0000000000000000000000000000000000000000..1aa03913b01c6fe257ddbac9a26180a2978d97fe --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/expression/task_execution_log.md @@ -0,0 +1,111 @@ + + +# TypeScript Assist — Expression `Task Execution Log` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +Use the error's `toWire()` for structured diagnostics: `location` is the first +missing canonical path; `attemptedLocation` retains the full suffix and real +list indices. `expressionWithBrokenPoint` marks one `` in the complete +native chain. Use `suggestedFix.location` with Q Assist; never parse the message +or guess a preload method. + +```typescript +import { E } from './E'; +import { TaskExecutionLog } from './models/TaskExecutionLog'; + +export function extractId(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).id().eval(); +} + +export function extractIdOrElse( + entity: TaskExecutionLog, fallback: NonNullable, +) { + return E.taskExecutionLog(entity).id().orElse(fallback); +} + +export function extractAction(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).action().eval(); +} + +export function extractActionOrElse( + entity: TaskExecutionLog, fallback: NonNullable, +) { + return E.taskExecutionLog(entity).action().orElse(fallback); +} + +export function extractDetail(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).detail().eval(); +} + +export function extractDetailOrElse( + entity: TaskExecutionLog, fallback: NonNullable, +) { + return E.taskExecutionLog(entity).detail().orElse(fallback); +} + +export function extractVersion(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: TaskExecutionLog, fallback: NonNullable, +) { + return E.taskExecutionLog(entity).version().orElse(fallback); +} + +export function extractTaskId(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).taskId().eval(); +} + +export function traverseTask(entity: TaskExecutionLog) { + return E.taskExecutionLog(entity).task().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/task-board/assist/expression/task_status.md b/source/teaql-ts/examples/task-board/assist/expression/task_status.md new file mode 100644 index 0000000000000000000000000000000000000000..9cb0d58820a8f17199ec56d6e70403e29085a5bd --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/expression/task_status.md @@ -0,0 +1,153 @@ + + +# TypeScript Assist — Expression `Task Status` + +The generated E facade preserves Value, loaded null/undefined, and NotLoaded. +`eval()` returns a native value for the first two and throws +`TeaQLNotLoadedError` for the third. `orElse` is nullish-only and never hides +NotLoaded. + +Use the error's `toWire()` for structured diagnostics: `location` is the first +missing canonical path; `attemptedLocation` retains the full suffix and real +list indices. `expressionWithBrokenPoint` marks one `` in the complete +native chain. Use `suggestedFix.location` with Q Assist; never parse the message +or guess a preload method. + +```typescript +import { E } from './E'; +import { TaskStatus } from './models/TaskStatus'; + +export function extractId(entity: TaskStatus) { + return E.taskStatus(entity).id().eval(); +} + +export function extractIdOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).id().orElse(fallback); +} + +export function extractName(entity: TaskStatus) { + return E.taskStatus(entity).name().eval(); +} + +export function extractNameOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).name().orElse(fallback); +} + +export function extractCode(entity: TaskStatus) { + return E.taskStatus(entity).code().eval(); +} + +export function extractCodeOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).code().orElse(fallback); +} + +export function extractColor(entity: TaskStatus) { + return E.taskStatus(entity).color().eval(); +} + +export function extractColorOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).color().orElse(fallback); +} + +export function extractDisplayOrder(entity: TaskStatus) { + return E.taskStatus(entity).displayOrder().eval(); +} + +export function extractDisplayOrderOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).displayOrder().orElse(fallback); +} + +export function extractProgress(entity: TaskStatus) { + return E.taskStatus(entity).progress().eval(); +} + +export function extractProgressOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).progress().orElse(fallback); +} + +export function extractVersion(entity: TaskStatus) { + return E.taskStatus(entity).version().eval(); +} + +export function extractVersionOrElse( + entity: TaskStatus, fallback: NonNullable, +) { + return E.taskStatus(entity).version().orElse(fallback); +} + +export function extractPlatformId(entity: TaskStatus) { + return E.taskStatus(entity).platformId().eval(); +} + +export function traversePlatform(entity: TaskStatus) { + return E.taskStatus(entity).platform().eval(); +} + +export function aggregateTaskListSize(entity: TaskStatus) { + return E.taskStatus(entity).taskList().size().eval(); +} + +export function firstTaskListId(entity: TaskStatus) { + return E.taskStatus(entity).taskList().first().id().eval(); +} + +export function getTaskListId(entity: TaskStatus, index: number) { + return E.taskStatus(entity).taskList().get(index).id().eval(); +} + + +``` + +Select every traversed field and relation. Never catch +`TeaQLNotLoadedError` merely to supply a default, and never replace generated E +accessors with optional chaining. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/source/teaql-ts/examples/task-board/assist/query/platform.md b/source/teaql-ts/examples/task-board/assist/query/platform.md new file mode 100644 index 0000000000000000000000000000000000000000..5397d55fd086cec00c6b6ad6571b6d1ee53dfe74 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/platform.md @@ -0,0 +1,119 @@ + + +# TypeScript Assist — Query `Platform` + +Use the exact generated `Q.platformsWithMinimalFields()` +entry point. Trusted runtime and policy state comes only from `UserContext`. + +```typescript +import { Q } from './Q'; +import { Platform } from './models/Platform'; +import { SmartList, UserContext } from '../teaql-ts'; + +export async function queryPlatformById( + context: UserContext, + entityId: string, +): Promise> { + return Q.platformsWithMinimalFields() + .withIdIs(entityId) + .orderByIdAscending() + .limit(20) + .comment('what: load the requested Platform row') + .purpose('why: serve the authorized Platform view') + .executeForList(context); +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Missing or blank intent, +unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Facet results + +Configure the target request with `countAs(alias)` to expose the outer membership +count under that alias, then pass it to the field-specific `facetBy...As` API. +Facet target requests can themselves declare Facets. Read the returned +`SmartList.facets[name]`; each Facet is another SmartList, with nested Facets in +its own `facets`. Narrow count aliases from unknown to number; missing is not zero. +`includeAllFacets` includes target candidates with zero membership. Membership +counts use the active filter, not the visible page's offset or limit. + +After selecting `taskStatusList`, read `entity.taskStatusList()` to retain +the loaded child SmartList and its Facets. Do not use `map` to obtain its metadata. +After selecting `taskList`, read `entity.taskList()` to retain +the loaded child SmartList and its Facets. Do not use `map` to obtain its metadata. + + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `typescript-assist-query/platform.id` | +| `name` | `string` | `typescript-assist-query/platform.name` | +| `founded` | `createTime` | `typescript-assist-query/platform.founded` | +| `user_email` | `string` | `typescript-assist-query/platform.user_email` | +| `version` | `version` | `typescript-assist-query/platform.version` | + +Generated reverse relations are derived from referencing KSML fields. Use their exact generated location for relation selection and access: + +| Generated reverse relation | Child entity | Field help | +| --- | --- | --- | +| `task_status_list` | `task_status` | `typescript-assist-query/platform.task_status_list` | +| `task_list` | `task` | `typescript-assist-query/platform.task_list` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task.md b/source/teaql-ts/examples/task-board/assist/query/task.md new file mode 100644 index 0000000000000000000000000000000000000000..04c9b32b2c5df6c86bb341a4b8436bb17b1cea91 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task.md @@ -0,0 +1,116 @@ + + +# TypeScript Assist — Query `Task` + +Use the exact generated `Q.tasksWithMinimalFields()` +entry point. Trusted runtime and policy state comes only from `UserContext`. + +```typescript +import { Q } from './Q'; +import { Task } from './models/Task'; +import { SmartList, UserContext } from '../teaql-ts'; + +export async function queryTaskById( + context: UserContext, + entityId: string, +): Promise> { + return Q.tasksWithMinimalFields() + .withIdIs(entityId) + .orderByIdAscending() + .limit(20) + .comment('what: load the requested Task row') + .purpose('why: serve the authorized Task view') + .executeForList(context); +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Missing or blank intent, +unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Facet results + +Configure the target request with `countAs(alias)` to expose the outer membership +count under that alias, then pass it to the field-specific `facetBy...As` API. +Facet target requests can themselves declare Facets. Read the returned +`SmartList.facets[name]`; each Facet is another SmartList, with nested Facets in +its own `facets`. Narrow count aliases from unknown to number; missing is not zero. +`includeAllFacets` includes target candidates with zero membership. Membership +counts use the active filter, not the visible page's offset or limit. + +After selecting `taskExecutionLogList`, read `entity.taskExecutionLogList()` to retain +the loaded child SmartList and its Facets. Do not use `map` to obtain its metadata. + + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `typescript-assist-query/task.id` | +| `name` | `string` | `typescript-assist-query/task.name` | +| `status` | `relation` | `typescript-assist-query/task.status` | +| `platform` | `relation` | `typescript-assist-query/task.platform` | +| `version` | `version` | `typescript-assist-query/task.version` | + +Generated reverse relations are derived from referencing KSML fields. Use their exact generated location for relation selection and access: + +| Generated reverse relation | Child entity | Field help | +| --- | --- | --- | +| `task_execution_log_list` | `task_execution_log` | `typescript-assist-query/task.task_execution_log_list` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task.name.md b/source/teaql-ts/examples/task-board/assist/query/task.name.md new file mode 100644 index 0000000000000000000000000000000000000000..25a15c1cdba423c335749f7b867af7491d04af69 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task.name.md @@ -0,0 +1,73 @@ + + +# TypeScript Query Field Assist — `task.name` + +KSML entity: `Task` +KSML field: `name` +Type: `string` +Named predicate values use `string`, matching the generated entity's native scalar type. +For nullable fields, use known/unknown predicates instead of passing `null`. + +| Capability | Generated API | +| --- | --- | +| Select | `selectName()` | +| Equality/set | `withNameIs(value)`, `withNameIsNot(value)`, `withNameIn(...values)`, `withNameNotIn(...values)` | +| Comparison | `withNameGreaterThan(value)`, `withNameGreaterThanOrEqualTo(value)`, `withNameLessThan(value)`, `withNameLessThanOrEqualTo(value)`, `withNameBetween(lower, upper)` | +| Null state | `withNameIsKnown()`, `withNameIsUnknown()` | +| String | `withNameContaining(value)`, `withNameNotContaining(value)`, `withNameStartingWith(value)`, `withNameNotStartingWith(value)`, `withNameEndingWith(value)`, `withNameNotEndingWith(value)`, `withNameSoundingLike(value)` | +| Order | `orderByNameAscending()`, `orderByNameDescending()` | +| Group | `groupByName()`, `groupByNameAs(alias)` | +Execution requires `comment(...)`, `purpose(...)`, and exactly one `context`. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task.status.md b/source/teaql-ts/examples/task-board/assist/query/task.status.md new file mode 100644 index 0000000000000000000000000000000000000000..15c047e9f1fddb761a1d38dafc8be78e81ebec63 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task.status.md @@ -0,0 +1,72 @@ + + +# TypeScript Query Field Assist — `task.status` + +KSML entity: `Task` +KSML field: `Task Status` +Type: `Task Status` +| Capability | Generated API | +| --- | --- | +| Select | `selectStatusWith(request)` | +| Filter identity | `filterByStatus(id)`, `filterByStatusIn(...ids)` | +| Filter nested request | `withStatusMatching(request)`, `withoutStatusMatching(request)` | +| Constant | `withStatusIsPlanned()` | +| Constant | `withStatusIsReady()` | +| Constant | `withStatusIsExecuting()` | +| Constant | `withStatusIsVerified()` | +| Group | `groupByStatus()`, `groupByStatusAs(alias)` | +| Facet | `facetByStatusAs(name, request, includeAllFacets)` | +Execution requires `comment(...)`, `purpose(...)`, and exactly one `context`. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task.task_execution_log_list.md b/source/teaql-ts/examples/task-board/assist/query/task.task_execution_log_list.md new file mode 100644 index 0000000000000000000000000000000000000000..3f3fe24c9ce17a08ea3995ffd4e225fc3ba7e794 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task.task_execution_log_list.md @@ -0,0 +1,71 @@ + + +# Query Reverse-Relation Assist — `task.task_execution_log_list` + +KSML entity: `task` +Derived reverse relation: `task_execution_log_list` +Child entity: `task_execution_log` + +| Capability | Generated API | +| --- | --- | +| Select | `.selectTaskExecutionLogListWith(Q.taskExecutionLogsWithMinimalFields())` | +| Related count | `.countTaskExecutionLogsAs(alias)` | +| Filtered related count | `.countTaskExecutionLogsWith(alias, childRequest)` | +| Read related count | `(entity as unknown as Record)[alias]`; require a present numeric value | + +Related counts are query projections, not modeled fields or mutation setters. Use a dedicated child request for the aggregate; do not reuse it as a row selection. An alias has no generated E accessor. Use E for modeled fields and loaded relation traversal; then narrow the returned alias from unknown. Missing is not zero. List and stream return entities carrying the alias; executeForRows returns records. Choose aliases that do not collide with model fields, relations or entity methods. + +Reverse relations are model-derived and never perform an implicit database query. Select the relation explicitly before expression access. Apply query methods before the executable purpose stage, then execute with exactly one trusted context. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task_execution_log.md b/source/teaql-ts/examples/task-board/assist/query/task_execution_log.md new file mode 100644 index 0000000000000000000000000000000000000000..c0aa4af3654a0c6e5820cdd54d800de218f43e73 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task_execution_log.md @@ -0,0 +1,107 @@ + + +# TypeScript Assist — Query `Task Execution Log` + +Use the exact generated `Q.taskExecutionLogsWithMinimalFields()` +entry point. Trusted runtime and policy state comes only from `UserContext`. + +```typescript +import { Q } from './Q'; +import { TaskExecutionLog } from './models/TaskExecutionLog'; +import { SmartList, UserContext } from '../teaql-ts'; + +export async function queryTaskExecutionLogById( + context: UserContext, + entityId: string, +): Promise> { + return Q.taskExecutionLogsWithMinimalFields() + .withIdIs(entityId) + .orderByIdAscending() + .limit(20) + .comment('what: load the requested Task Execution Log row') + .purpose('why: serve the authorized Task Execution Log view') + .executeForList(context); +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Missing or blank intent, +unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Facet results + +Configure the target request with `countAs(alias)` to expose the outer membership +count under that alias, then pass it to the field-specific `facetBy...As` API. +Facet target requests can themselves declare Facets. Read the returned +`SmartList.facets[name]`; each Facet is another SmartList, with nested Facets in +its own `facets`. Narrow count aliases from unknown to number; missing is not zero. +`includeAllFacets` includes target candidates with zero membership. Membership +counts use the active filter, not the visible page's offset or limit. + + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `typescript-assist-query/task_execution_log.id` | +| `task` | `relation` | `typescript-assist-query/task_execution_log.task` | +| `action` | `string` | `typescript-assist-query/task_execution_log.action` | +| `detail` | `string` | `typescript-assist-query/task_execution_log.detail` | +| `version` | `version` | `typescript-assist-query/task_execution_log.version` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/query/task_status.md b/source/teaql-ts/examples/task-board/assist/query/task_status.md new file mode 100644 index 0000000000000000000000000000000000000000..f3a76c4533d6ff78d363aaee610d847d3995923f --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/query/task_status.md @@ -0,0 +1,119 @@ + + +# TypeScript Assist — Query `Task Status` + +Use the exact generated `Q.taskStatusesWithMinimalFields()` +entry point. Trusted runtime and policy state comes only from `UserContext`. + +```typescript +import { Q } from './Q'; +import { TaskStatus } from './models/TaskStatus'; +import { SmartList, UserContext } from '../teaql-ts'; + +export async function queryTaskStatusById( + context: UserContext, + entityId: string, +): Promise> { + return Q.taskStatusesWithMinimalFields() + .withIdIs(entityId) + .orderByIdAscending() + .limit(20) + .comment('what: load the requested Task Status row') + .purpose('why: serve the authorized Task Status view') + .executeForList(context); +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Missing or blank intent, +unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Facet results + +Configure the target request with `countAs(alias)` to expose the outer membership +count under that alias, then pass it to the field-specific `facetBy...As` API. +Facet target requests can themselves declare Facets. Read the returned +`SmartList.facets[name]`; each Facet is another SmartList, with nested Facets in +its own `facets`. Narrow count aliases from unknown to number; missing is not zero. +`includeAllFacets` includes target candidates with zero membership. Membership +counts use the active filter, not the visible page's offset or limit. + +After selecting `taskList`, read `entity.taskList()` to retain +the loaded child SmartList and its Facets. Do not use `map` to obtain its metadata. + + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `typescript-assist-query/task_status.id` | +| `name` | `string` | `typescript-assist-query/task_status.name` | +| `code` | `string` | `typescript-assist-query/task_status.code` | +| `color` | `string` | `typescript-assist-query/task_status.color` | +| `display_order` | `number` | `typescript-assist-query/task_status.display_order` | +| `progress` | `number` | `typescript-assist-query/task_status.progress` | +| `platform` | `relation` | `typescript-assist-query/task_status.platform` | +| `version` | `version` | `typescript-assist-query/task_status.version` | + +Generated reverse relations are derived from referencing KSML fields. Use their exact generated location for relation selection and access: + +| Generated reverse relation | Child entity | Field help | +| --- | --- | --- | +| `task_list` | `task` | `typescript-assist-query/task_status.task_list` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/task-board/assist/update/task.md b/source/teaql-ts/examples/task-board/assist/update/task.md new file mode 100644 index 0000000000000000000000000000000000000000..1f787fbed218d0b26f7bf9f97a07ccb53e07b5d4 --- /dev/null +++ b/source/teaql-ts/examples/task-board/assist/update/task.md @@ -0,0 +1,94 @@ + + +# TypeScript Assist — Update `Task` + +Load the current row and its original optimistic version. Never reconstruct an +entity from an ID/version supplied by a client. Trusted runtime and policy state +comes only from `UserContext`. + +An entity update is not a partial DTO patch. Load every scalar field before +modification so checker rules can validate the complete business state. Never +use `WithMinimalFields()` or a reduced projection for an entity that will be saved. + +```typescript +import { Decimal, UserContext, decimal } from '../teaql-ts'; +import { Q } from './Q'; +import { Task } from './models/Task'; + +export interface UpdateTaskInput { + name: string; + +} + +export async function updateTask( + id: string, + input: UpdateTaskInput, + context: UserContext, + throwIfMissing = false, +): Promise { + const entity = await Q.tasks() + .withIdIs(id) + + .comment('what: load current Task for update') + .purpose('why: preserve original version for optimistic locking') + .executeForOne(context); + if (!entity) { + if (throwIfMissing) throw new Error('Task not found: ' + id); + return undefined; + } + + entity.updateName(input.name); + + await entity + .auditAs('Update Task for the requested business operation') + .save(context); + return entity; +} +``` + +Compile the source unchanged. Prove persistence and query-back, a conflict from +an independently loaded stale copy, undefined and throwing not-found behavior, +missing/blank audit rejection, and compilation failure for unknown or trusted +fields. Constant and relation updates require an explicitly selected generated +method; do not invent a generic setter. + +For Decimal fields, construct exact values with `decimal('3.50')`; JavaScript +`number` is not an exact Decimal input. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `update`. + +- Load the tenant-scoped current entity first so its original version participates + in optimistic locking; do not reconstruct versioned state from untrusted JSON. +- Allow-list writable fields, attach the generated audit-reason API, and save with + the same UserContext. Add a stale-version rejection test. diff --git a/source/teaql-ts/examples/task-board/evaluation.md b/source/teaql-ts/examples/task-board/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..4a19300b57c15796cb0b8cbca85ade5395d577a9 --- /dev/null +++ b/source/teaql-ts/examples/task-board/evaluation.md @@ -0,0 +1,181 @@ + +# KSML Evaluation Report +## 📊 Summary +- **Errors**: 0 +- **Warnings**: 6 +- **Suggestions**: 2 +- **Solids**: 21 + +## ⚠️ Warnings + +| Rule ID | Target | Source | Warning Message | +|---------|--------|--------|-----------------| +| `KSML-OBJECT-002` | `platform._module_key` | `model.xml:2` | Module key 'task_board' on object 'platform' should be lowercase kebab-case. | +| `KSML-OBJECT-002` | `task_status._module_key` | `model.xml:5` | Module key 'task_board' on object 'task_status' should be lowercase kebab-case. | +| `KSML-OBJECT-002` | `task._module_key` | `model.xml:14` | Module key 'task_board' on object 'task' should be lowercase kebab-case. | +| `KSML-OBJECT-002` | `task_execution_log._module_key` | `model.xml:16` | Module key 'task_board' on object 'task_execution_log' should be lowercase kebab-case. | +| `KSML-BUSINESS-002` | `task_execution_log.action` | `model.xml:16` | Field 'action' in business object 'task_execution_log' should preferably use a rich concrete typical value instead of generic string(). | +| `KSML-BUSINESS-002` | `task_execution_log.detail` | `model.xml:16` | Field 'detail' in business object 'task_execution_log' should preferably use a rich concrete typical value instead of generic string(). | + + +## 💡 Suggestions + +| Rule ID | Target | Source | Suggestion | +|---------|--------|--------|------------| +| `KSML-LOG-007` | `task_execution_log` | `model.xml:16` | Object 'task_execution_log' has a name ending with '_log' but is not marked as a logging object. Consider adding _log="true" if this object represents append-only log entries. | +| `KSML-PRIVACY-001-SUG` | `platform.user_email` | `model.xml:4` | Contact identifier field. Add `user_email` to `_audit_mask_fields` (e.g., ``). | + + +## Privacy Findings + +These are model-level risk findings and jurisdiction-specific review references, not a compliance certificate. +Field names do not establish legal applicability. Confirm processing purposes, legal bases, retention, +individual rights, cross-border transfers and operational evidence separately. Masking alone is not compliance. +Regional repetitions do not add to the Summary counts. Official references reviewed on 2026-10-13; +check current law and commencement dates before deployment. + +### Mainland China — PIPL (Personal Information Protection Law) + +PIPL (LAW). Confirm the processing falls within PIPL scope, including its territorial rules. +[Official reference](https://www.gov.cn/xinwen/2021-08/20/content_5632486.htm) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | PIPL: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Hong Kong — PDPO (Personal Data (Privacy) Ordinance) + +PDPO (LAW). Review the applicable data-user duties and six data protection principles. +[Official reference](https://www.pcpd.org.hk/english/data_privacy_law/ordinance_at_a_Glance/ordinance.html) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | PDPO: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### European Union / EEA — GDPR (General Data Protection Regulation) + +GDPR (LAW). Confirm GDPR territorial scope and the lawful basis for the actual processing. +[Official reference](https://commission.europa.eu/law/law-topic/data-protection_en) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | GDPR: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### United Kingdom — UK GDPR / Data Protection Act 2018 (UK General Data Protection Regulation and Data Protection Act 2018) + +UK GDPR / Data Protection Act 2018 (LAW). Apply the UK framework separately; check applicable Data (Use and Access) Act 2025 amendments. +[Official reference](https://www.gov.uk/guidance/data-use-and-access-act-2025-data-protection-and-privacy-changes) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | UK GDPR / Data Protection Act 2018: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Switzerland — FADP (Federal Act on Data Protection) + +FADP (LAW). Confirm the revised federal law applies; check any additional sector or cantonal requirements. +[Official reference](https://www.edoeb.admin.ch/en/faq-data-protection) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | FADP: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### United States - California — CCPA, as amended by CPRA (California Consumer Privacy Act, as amended by the California Privacy Rights Act) + +CCPA, as amended by CPRA (LAW). Confirm covered-business criteria and exemptions. CPRA amends CCPA; this is not a nationwide US law. +[Official reference](https://www.cppa.ca.gov/faq.html) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | CCPA, as amended by CPRA: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Canada — PIPEDA (Personal Information Protection and Electronic Documents Act) + +PIPEDA (LAW). Confirm commercial-activity scope and whether a provincial or sector law applies instead or additionally. +[Official reference](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/pipeda_brief/) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | PIPEDA: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Brazil — LGPD (Lei Geral de Protecao de Dados Pessoais (General Personal Data Protection Law)) + +LGPD (LAW). Confirm LGPD applicability and the processing basis; field names do not establish either. +[Official reference](https://www.gov.br/anpd/pt-br/acesso-a-informacao/perguntas-frequentes) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | LGPD: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Australia — Privacy Act 1988 / Australian Privacy Principles (Privacy Act 1988 and Australian Privacy Principles) + +Privacy Act 1988 / Australian Privacy Principles (LAW). Confirm APP-entity coverage and exemptions; not every organisation is covered. +[Official reference](https://www.oaic.gov.au/privacy/privacy-legislation/the-privacy-act) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | Privacy Act 1988 / Australian Privacy Principles: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### India — DPDP Act 2023 / Rules 2025 (Digital Personal Data Protection Act 2023 and Digital Personal Data Protection Rules 2025) + +DPDP Act 2023 / Rules 2025 (LAW). Confirm digital-personal-data scope and the commencement date of each provision; implementation is phased. +[Official reference](https://www.meity.gov.in/documents/act-and-policies/digital-personal-data-protection-rules-2025-gDOxUjMtQWa) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | DPDP Act 2023 / Rules 2025: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Japan — APPI (Act on the Protection of Personal Information) + +APPI (LAW). Confirm APPI coverage and the relevant handling and third-party provision requirements. +[Official reference](https://www.ppc.go.jp/en/legal/) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | APPI: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### South Korea — PIPA (Personal Information Protection Act) + +PIPA (LAW). Confirm PIPA coverage and the current Korean statutory text and applicable amendments. +[Official reference](https://pipc.go.kr/eng/user/lgp/law/lawsRegulations.do) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | PIPA: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + +### Singapore — PDPA (Personal Data Protection Act) + +PDPA (LAW). Confirm organisational coverage, exceptions and which obligations are in force. +[Official reference](https://www.pdpc.gov.sg/overview-of-pdpa/the-legislation/personal-data-protection-act/data-protection-obligations) + +| Severity | Target | Reason | Recommended Action | Regulatory Basis | +|----------|--------|--------|--------------------|------------------| +| Suggestion | `platform.user_email` | Contact identifier field. | Add to `_audit_mask_fields="user_email"`. | PDPA: review personal-data safeguards and unnecessary exposure in audit logs if the law applies | + + + +## ✅ Solids + +| Rule ID | Target | Source | Message | +|---------|--------|--------|---------| +| `KSML-UPLOAD-001` | `` | — | The upload contains 1 files. | +| `KSML-UPLOAD-005` | `` | `model.xml:1` | Resolved entrypoint: model.xml | +| `KSML-XML-002` | `` | `model.xml:1` | The XML document model.xml was parsed successfully. | +| `KSML-ROOT-003` | `` | `model.xml:1` | Root name 'robot-task-board-service' is well-formed. | +| `KSML-ROOT-008` | `` | `model.xml:1` | External JSON business fields use the default camelCase profile. | +| `KSML-OBJECT-001` | `platform` | `model.xml:2` | Object 'platform' defines display name, module, and module key metadata. | +| `KSML-OBJECT-001` | `task_status` | `model.xml:5` | Object 'task_status' defines display name, module, and module key metadata. | +| `KSML-OBJECT-001` | `task` | `model.xml:14` | Object 'task' defines display name, module, and module key metadata. | +| `KSML-OBJECT-001` | `task_execution_log` | `model.xml:16` | Object 'task_execution_log' defines display name, module, and module key metadata. | +| `KSML-CONSTANT-007` | `task_status.id` | `model.xml:5` | Constant object 'task_status' correctly defines id="id()". | +| `KSML-CONSTANT-001` | `task_status` | `model.xml:5` | Constant object 'task_status' has correctly defined constant properties. | +| `KSML-CONSTANT-002` | `task_status.platform` | `model.xml:5` | Constant object 'task_status' is correctly associated with the root object. | +| `KSML-CONSTANT-004` | `task_status` | `model.xml:5` | Constant object 'task_status' has 4 constant value records. | +| `KSML-CONSTANT-008` | `task_status` | `model.xml:5` | Every value in constant object 'task_status' explicitly provides every declared constant field. | +| `KSML-REFERENCE-003` | `task_status.platform` | `model.xml:6` | Reference 'platform' in 'task_status' successfully resolves to target object 'platform'. | +| `KSML-REFERENCE-003` | `task.platform` | `model.xml:14` | Reference 'platform' in 'task' successfully resolves to target object 'platform'. | +| `KSML-REFERENCE-003` | `task.status` | `model.xml:14` | Reference 'status' in 'task' successfully resolves to target object 'task_status'. | +| `KSML-REFERENCE-003` | `task_execution_log.task` | `model.xml:16` | Reference 'task' in 'task_execution_log' successfully resolves to target object 'task'. | +| `KSML-MODULE-004` | `task_status` | `model.xml:5` | Constant object 'task_status' is local to business area 'task' and correctly shares its _module_key 'task_board'. | +| `KSML-DOMAIN-ROOT-003` | `` | `model.xml:1` | Exactly one domain root candidate 'platform' was found. | +| `KSML-STATE-001` | `task.status` | `model.xml:14` | Object 'task' is an Aggregate Root candidate with primary state field 'status'. | + diff --git a/source/teaql-ts/examples/task-board/fixture-manifest.json b/source/teaql-ts/examples/task-board/fixture-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..77eabbf42a94db1eba06d37c604baec95324d744 --- /dev/null +++ b/source/teaql-ts/examples/task-board/fixture-manifest.json @@ -0,0 +1,60 @@ +{ + "schema": "teaql.typescript-task-board-fixture/v1", + "modelSha256": "4a1ec513cb362e4c25a5bc9479fe27a2034558633a9e5760245919af7c601856", + "manifestSha256": "d3df51e67323e4add6eb482dbc7c48fdc5df7cdc6fcab44ab361cd912dca8e2f", + "generationReport": { + "label": "typescript-task-board-generator-v3", + "sha256": "606f4ec6d012bb12930aaab04d4f0aec9bf51701c300a497c61d2ad1cb55d811" + }, + "generatorCommit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "evaluatedScope": "typescript-node-lib-core", + "evaluationErrors": 0, + "files": { + "src/generated/Q.ts": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "src/generated/requests/PlatformRequest.ts": "c20d7cdee9394dba4103a64cd5d8b44a9f9714d8a752d561f6bea13bb39d53a3", + "src/generated/requests/TaskStatusRequest.ts": "6cb4081eecc35f10aa66fa7d56ac66a406d438d60a96e6d84e5d38669faaa3c8", + "src/generated/requests/TaskRequest.ts": "312c7a5b30f86e4d656daee7cf1075d6e6388f010b2f3d46c41fd73427f9003a", + "src/generated/requests/TaskExecutionLogRequest.ts": "1484d5c9e07fe4cd46688e0fa40976091b335d2ecc736a1cd99d1e0457714b5f", + "teaql-i18n.json": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "src/generated/E.ts": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "package.json": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "src/teaql-node-sql.ts": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "src/runtime-module.ts": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "src/generated-bootstrap.ts": "a0444cc739c1a3c8cd3bc89127c2db056ca2aedf3293990c2b7fe5bfdf44afc3", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Platform.ts": "c455434e212c63a95e789131400ceba113800d6ab045778d96f142f54c014da2", + "src/generated/models/TaskStatus.ts": "8610b1aa0156f0b1dba7f6ba691b2b490dbdb2f489fa17b9894cc994e20156a4", + "src/generated/models/Task.ts": "efea9096e07268c6b0eb5fa711c397fc40d104a5e67840c6e067d01c4e83b5a8", + "src/generated/models/TaskExecutionLog.ts": "2a100aea505f12a86fd7c87ee8ead1a3313d8d7515ab5e3b4388eb31c14dd03a" + }, + "assist": { + "query/task.md": "6f99a202ad68381ffc852ed4501eac7be6194a81548850326219866fa856f9fe", + "query/task.status.md": "872774d3e3581fba58c57d5dc44cff58c7622cfb11d4da7233a28a4f41792ef4", + "query/task.name.md": "4fb7e7850b255421d55cf492132a0ca62679f5d42dff064d5fed3cc549628c41", + "query/task.task_execution_log_list.md": "1cc26492cf73ed75c5da580ffbc6b07384040356f179c06fca8dd418efba912b", + "create/task.md": "b620c41b95af918ac72c91dbc47684d3a94221af968cbd9bc60dc56fa0fff3b0", + "update/task.md": "0b5d1112589194f63315c8870f81a95aead57f1a45d730e9ef53cfabdba715bc", + "delete/task.md": "c6224e940d802fd6effa2571dc79677e061bae8cefdf1acbebbe4066423da910", + "expression/task.md": "7f215920d1eb7c00b078ed56a0d5bd2264528a3d66c4078ec1e0adaced727d48", + "expression/task_status.md": "3a2ad50910b2b656ea66156be2c26f66411b48382f4e105607dd7a3dd9b468a0", + "expression/task_execution_log.md": "11ab48e064804bb253f6543c085519ca6dd00b4c5cd59ae90fae909cfb85a4f4", + "create/task_execution_log.md": "278d1e82d28f44a5958746e0d33f2383b7f851f94ab0aa1636d636e5dc1af523", + "query/task_execution_log.md": "7942681172082053820be0f583e3fef63f7682c73aa390361ed83f41061ec4c3", + "query/task_status.md": "f0076bfcfb1e67fa745eb3c02fc1a065ee1bb02974e627d5aeb388d1c85ba0b6", + "query/platform.md": "f27fa3606997cc8312c42ec570ff42f008beeb7d1207420c4d190b30962ca211" + }, + "generatedImplementationHandEdited": false, + "runtimeProductionChanged": false, + "generatorSourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937", + "producerReportSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "evaluationWarnings": 6, + "previousFixtureManifestSha256": "c4e011c976fa58b2cd6295fb53485eac9280dddd5103c8503a82fd417551fea2" +} diff --git a/source/teaql-ts/examples/task-board/model.xml b/source/teaql-ts/examples/task-board/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..614dbf34704d60c719efeb71cc1f1c64fb50cd7a --- /dev/null +++ b/source/teaql-ts/examples/task-board/model.xml @@ -0,0 +1,19 @@ + + + + <_value id="1001" name="Planned" code="PLANNED" color="#94A3B8" display_order="10" progress="0"/> + <_value id="1002" name="Ready" code="READY" color="#3B82F6" display_order="20" progress="25"/> + <_value id="1003" name="Executing" code="EXECUTING" color="#F59E0B" display_order="30" progress="50"/> + <_value id="1004" name="Verified" code="VERIFIED" color="#16A34A" display_order="40" progress="100"/> + + + + diff --git a/source/teaql-ts/examples/task-board/package-lock.json b/source/teaql-ts/examples/task-board/package-lock.json index bf1ee72b08dc772376e37a83552a4ce9c081a204..93b8e1f0845eefb7e2f862ad94e05a2ac98328e6 100644 --- a/source/teaql-ts/examples/task-board/package-lock.json +++ b/source/teaql-ts/examples/task-board/package-lock.json @@ -1,22 +1,24 @@ { - "name": "teaql-task-board-federation-examples", + "name": "teaql-task-board-examples", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "teaql-task-board-federation-examples", + "name": "teaql-task-board-examples", "dependencies": { - "node-fetch": "^2.7.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../.." }, "devDependencies": { - "@types/node-fetch": "^2.6.12", - "typescript": "^5.0.0" + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "ts-node": "10.9.2", + "typescript": "5.4.5" } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -40,7 +42,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -67,7 +69,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", @@ -136,323 +138,226 @@ } } }, - "node_modules/@types/node": { - "version": "26.3.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.3.0.tgz", - "integrity": "sha512-L3fgrnchriRC2ExBflb8j4uZZURHZfQsmQeyVzhjcHW4kkwVyo8/0h1B2MVzMTrYUJYu6G7EWs14hW/L9putqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~8.3.0" - } - }, - "node_modules/@types/node-fetch": { - "version": "2.6.13", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", - "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.4" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", "dev": true, "license": "MIT", "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" + "@jridgewell/trace-mapping": "0.3.9" }, "engines": { - "node": ">= 0.4" + "node": ">=12" } }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "dev": true, "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, "engines": { - "node": ">= 0.8" + "node": ">=6.0.0" } }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } + "license": "MIT" }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", "dev": true, "license": "MIT", "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "node_modules/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } + "license": "MIT" }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } + "license": "MIT" }, - "node_modules/es-object-atoms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", - "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } + "license": "MIT" }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } + "license": "MIT" }, - "node_modules/form-data": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", - "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", "dev": true, "license": "MIT", "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.4", - "mime-types": "^2.1.35" - }, - "engines": { - "node": ">= 6" + "@types/node": "*" } }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", "dev": true, "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" + "dependencies": { + "undici-types": "~6.21.0" } }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" + "bin": { + "acorn": "bin/acorn" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=0.4.0" } }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", "dev": true, "license": "MIT", "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" + "acorn": "^8.11.0" }, "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=0.4.0" } }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } + "license": "MIT" }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, + "node_modules/better-sqlite3": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", + "hasInstallScript": true, "license": "MIT", "dependencies": { - "has-symbols": "^1.0.3" + "node-addon-api": "^8.0.0" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">=22" } }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } + "license": "MIT" }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "node_modules/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", "dev": true, - "license": "MIT", + "license": "BSD-3-Clause", "engines": { - "node": ">= 0.4" + "node": ">=0.3.1" } }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } + "license": "ISC" }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, "engines": { - "node": ">= 0.6" + "node": "^18 || ^20 || >= 21" } }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "node_modules/teaql-ts": { + "resolved": "../..", + "link": true + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, "license": "MIT", "dependencies": { - "whatwg-url": "^5.0.0" + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" }, - "engines": { - "node": "4.x || >=6.0.0" + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" }, "peerDependencies": { - "encoding": "^0.1.0" + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" }, "peerDependenciesMeta": { - "encoding": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { "optional": true } } }, - "node_modules/teaql-ts": { - "resolved": "../..", - "link": true - }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" - }, "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -464,26 +369,27 @@ } }, "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" }, - "node_modules/webidl-conversions": { + "node_modules/v8-compile-cache-lib": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" + "engines": { + "node": ">=6" } } } diff --git a/source/teaql-ts/examples/task-board/package.json b/source/teaql-ts/examples/task-board/package.json index bc3dcfe4a262a6ec0a5b5053d57959630519678f..30355bc95496e8a9186891aca96abc48df2cdc70 100644 --- a/source/teaql-ts/examples/task-board/package.json +++ b/source/teaql-ts/examples/task-board/package.json @@ -1,15 +1,20 @@ { - "name": "teaql-task-board-federation-examples", + "name": "teaql-task-board-examples", "private": true, "scripts": { - "build": "tsc --noEmit" + "build": "tsc --noEmit", + "verify": "node verify-local.cjs", + "demo:native": "ts-node app-native/src/main.ts", + "demo:dynamic": "ts-node app-dynamic/src/main.ts" }, "dependencies": { - "node-fetch": "^2.7.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../.." }, "devDependencies": { - "@types/node-fetch": "^2.6.12", - "typescript": "^5.0.0" + "@types/better-sqlite3": "^7.6.12", + "@types/node": "^22.0.0", + "ts-node": "10.9.2", + "typescript": "5.4.5" } } diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/package.json b/source/teaql-ts/examples/task-board/ts-lib-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..18f94cf1d9431020594d34c5eedb21090d74e205 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/package.json @@ -0,0 +1,18 @@ +{ + "name": "robot-task-board-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-bootstrap.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ad5dca1bfb2e41498961081760fda99ca6a1179 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-bootstrap.ts @@ -0,0 +1,96 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Platform } from './generated/models/Platform'; +import { TaskStatus } from './generated/models/TaskStatus'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Platform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Robot System"); + domainRoot.updateUserEmail("admin@robots.example"); + await domainRoot.auditAs('create generated Domain Root Platform').save(context); + } + context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); + let constantTaskStatus1001 = (await Q.taskStatuses().withIdIs("1001").comment('what: locate generated constant TaskStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantTaskStatus1001) { + constantTaskStatus1001 = TaskStatus.teaqlBootstrapNew(context, "1001"); + constantTaskStatus1001.updateName("Planned"); + constantTaskStatus1001.updateCode("PLANNED"); + constantTaskStatus1001.updateColor("#94A3B8"); + constantTaskStatus1001.updateDisplayOrder(decimal("10")); + constantTaskStatus1001.updateProgress(decimal("0")); + constantTaskStatus1001.updatePlatform(domainRoot); + await constantTaskStatus1001.auditAs('create model constant TaskStatus(1001)').save(context); + } else { + let changed = false; + if (constantTaskStatus1001.name !== "Planned") { constantTaskStatus1001.updateName("Planned"); changed = true; } + if (constantTaskStatus1001.code !== "PLANNED") { constantTaskStatus1001.updateCode("PLANNED"); changed = true; } + if (constantTaskStatus1001.color !== "#94A3B8") { constantTaskStatus1001.updateColor("#94A3B8"); changed = true; } + if (constantTaskStatus1001.displayOrder !== decimal("10")) { constantTaskStatus1001.updateDisplayOrder(decimal("10")); changed = true; } + if (constantTaskStatus1001.progress !== decimal("0")) { constantTaskStatus1001.updateProgress(decimal("0")); changed = true; } + if (String((constantTaskStatus1001.platform as any)?.id ?? constantTaskStatus1001.platform) !== String(domainRoot.id)) { constantTaskStatus1001.updatePlatform(domainRoot); changed = true; } + if (changed) await constantTaskStatus1001.auditAs('reconcile model constant TaskStatus(1001)').save(context); + } + let constantTaskStatus1002 = (await Q.taskStatuses().withIdIs("1002").comment('what: locate generated constant TaskStatus(1002)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantTaskStatus1002) { + constantTaskStatus1002 = TaskStatus.teaqlBootstrapNew(context, "1002"); + constantTaskStatus1002.updateName("Ready"); + constantTaskStatus1002.updateCode("READY"); + constantTaskStatus1002.updateColor("#3B82F6"); + constantTaskStatus1002.updateDisplayOrder(decimal("20")); + constantTaskStatus1002.updateProgress(decimal("25")); + constantTaskStatus1002.updatePlatform(domainRoot); + await constantTaskStatus1002.auditAs('create model constant TaskStatus(1002)').save(context); + } else { + let changed = false; + if (constantTaskStatus1002.name !== "Ready") { constantTaskStatus1002.updateName("Ready"); changed = true; } + if (constantTaskStatus1002.code !== "READY") { constantTaskStatus1002.updateCode("READY"); changed = true; } + if (constantTaskStatus1002.color !== "#3B82F6") { constantTaskStatus1002.updateColor("#3B82F6"); changed = true; } + if (constantTaskStatus1002.displayOrder !== decimal("20")) { constantTaskStatus1002.updateDisplayOrder(decimal("20")); changed = true; } + if (constantTaskStatus1002.progress !== decimal("25")) { constantTaskStatus1002.updateProgress(decimal("25")); changed = true; } + if (String((constantTaskStatus1002.platform as any)?.id ?? constantTaskStatus1002.platform) !== String(domainRoot.id)) { constantTaskStatus1002.updatePlatform(domainRoot); changed = true; } + if (changed) await constantTaskStatus1002.auditAs('reconcile model constant TaskStatus(1002)').save(context); + } + let constantTaskStatus1003 = (await Q.taskStatuses().withIdIs("1003").comment('what: locate generated constant TaskStatus(1003)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantTaskStatus1003) { + constantTaskStatus1003 = TaskStatus.teaqlBootstrapNew(context, "1003"); + constantTaskStatus1003.updateName("Executing"); + constantTaskStatus1003.updateCode("EXECUTING"); + constantTaskStatus1003.updateColor("#F59E0B"); + constantTaskStatus1003.updateDisplayOrder(decimal("30")); + constantTaskStatus1003.updateProgress(decimal("50")); + constantTaskStatus1003.updatePlatform(domainRoot); + await constantTaskStatus1003.auditAs('create model constant TaskStatus(1003)').save(context); + } else { + let changed = false; + if (constantTaskStatus1003.name !== "Executing") { constantTaskStatus1003.updateName("Executing"); changed = true; } + if (constantTaskStatus1003.code !== "EXECUTING") { constantTaskStatus1003.updateCode("EXECUTING"); changed = true; } + if (constantTaskStatus1003.color !== "#F59E0B") { constantTaskStatus1003.updateColor("#F59E0B"); changed = true; } + if (constantTaskStatus1003.displayOrder !== decimal("30")) { constantTaskStatus1003.updateDisplayOrder(decimal("30")); changed = true; } + if (constantTaskStatus1003.progress !== decimal("50")) { constantTaskStatus1003.updateProgress(decimal("50")); changed = true; } + if (String((constantTaskStatus1003.platform as any)?.id ?? constantTaskStatus1003.platform) !== String(domainRoot.id)) { constantTaskStatus1003.updatePlatform(domainRoot); changed = true; } + if (changed) await constantTaskStatus1003.auditAs('reconcile model constant TaskStatus(1003)').save(context); + } + let constantTaskStatus1004 = (await Q.taskStatuses().withIdIs("1004").comment('what: locate generated constant TaskStatus(1004)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!constantTaskStatus1004) { + constantTaskStatus1004 = TaskStatus.teaqlBootstrapNew(context, "1004"); + constantTaskStatus1004.updateName("Verified"); + constantTaskStatus1004.updateCode("VERIFIED"); + constantTaskStatus1004.updateColor("#16A34A"); + constantTaskStatus1004.updateDisplayOrder(decimal("40")); + constantTaskStatus1004.updateProgress(decimal("100")); + constantTaskStatus1004.updatePlatform(domainRoot); + await constantTaskStatus1004.auditAs('create model constant TaskStatus(1004)').save(context); + } else { + let changed = false; + if (constantTaskStatus1004.name !== "Verified") { constantTaskStatus1004.updateName("Verified"); changed = true; } + if (constantTaskStatus1004.code !== "VERIFIED") { constantTaskStatus1004.updateCode("VERIFIED"); changed = true; } + if (constantTaskStatus1004.color !== "#16A34A") { constantTaskStatus1004.updateColor("#16A34A"); changed = true; } + if (constantTaskStatus1004.displayOrder !== decimal("40")) { constantTaskStatus1004.updateDisplayOrder(decimal("40")); changed = true; } + if (constantTaskStatus1004.progress !== decimal("100")) { constantTaskStatus1004.updateProgress(decimal("100")); changed = true; } + if (String((constantTaskStatus1004.platform as any)?.id ?? constantTaskStatus1004.platform) !== String(domainRoot.id)) { constantTaskStatus1004.updatePlatform(domainRoot); changed = true; } + if (changed) await constantTaskStatus1004.auditAs('reconcile model constant TaskStatus(1004)').save(context); + } +} diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-search-models.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..93aac0586ab9b4cffcdc6d295f29d8568684babc --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated-search-models.ts @@ -0,0 +1,95 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Platform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "founded": "timestamp" as const, + "user_email": "string" as const, + "userEmail": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "founded": "founded", + "user_email": "userEmail", + "userEmail": "userEmail", + "version": "version", + }), + relations: Object.freeze({ + "taskStatusList": "TaskStatus", + "taskList": "Task", + }), + }), + "TaskStatus": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "code": "string" as const, + "color": "string" as const, + "display_order": "decimal" as const, + "displayOrder": "decimal" as const, + "progress": "decimal" as const, + "platform": "integer" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "code": "code", + "color": "color", + "display_order": "displayOrder", + "displayOrder": "displayOrder", + "progress": "progress", + "platform": "platform", + "version": "version", + }), + relations: Object.freeze({ + "platform": "Platform", + "taskList": "Task", + }), + }), + "Task": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "status": "integer" as const, + "platform": "integer" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "status": "status", + "platform": "platform", + "version": "version", + }), + relations: Object.freeze({ + "status": "TaskStatus", + "platform": "Platform", + "taskExecutionLogList": "TaskExecutionLog", + }), + }), + "TaskExecutionLog": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "task": "integer" as const, + "action": "string" as const, + "detail": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "task": "task", + "action": "action", + "detail": "detail", + "version": "version", + }), + relations: Object.freeze({ + "task": "Task", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/E.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..4330e0a3b231b4d8efecccc444f3bcff46d19f28 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/E.ts @@ -0,0 +1,732 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { Platform } from './models/Platform'; +import { TaskStatus } from './models/TaskStatus'; +import { Task } from './models/Task'; +import { TaskExecutionLog } from './models/TaskExecutionLog'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class PlatformExpression { + constructor( + private readonly value: Platform | null | undefined, + private readonly root = 'Platform(null)', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Platform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + founded(): ValueExpression { + const path = this.path.member('founded', 'founded'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('founded')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'founded'), + ); + } + return new ValueExpression(this.value.founded); + } + + userEmail(): ValueExpression { + const path = this.path.member('user_email', 'userEmail'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('userEmail')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'user_email'), + ); + } + return new ValueExpression(this.value.userEmail); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + taskStatusList(): TaskStatusListExpression { + const path = this.path.member('task_status_list', 'taskStatusList'); + if (this.notLoaded) { + return new TaskStatusListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return TaskStatusListExpression.missing(this.root, path); + if (!this.value.isLoaded('taskStatusList')) { + return new TaskStatusListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'task_status_list')); + } + return new TaskStatusListExpression( + this.value.taskStatusList(), this.root, path, + ); + } + + taskList(): TaskListExpression { + const path = this.path.member('task_list', 'taskList'); + if (this.notLoaded) { + return new TaskListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return TaskListExpression.missing(this.root, path); + if (!this.value.isLoaded('taskList')) { + return new TaskListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'task_list')); + } + return new TaskListExpression( + this.value.taskList(), this.root, path, + ); + } +} + +export class TaskStatusExpression { + constructor( + private readonly value: TaskStatus | null | undefined, + private readonly root = 'TaskStatus(null)', + private readonly path = ExpressionPath.root('E.taskStatus()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TaskStatus | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + code(): ValueExpression { + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('code')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'code'), + ); + } + return new ValueExpression(this.value.code); + } + + color(): ValueExpression { + const path = this.path.member('color', 'color'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('color')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'color'), + ); + } + return new ValueExpression(this.value.color); + } + + displayOrder(): ValueExpression { + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('displayOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), + ); + } + return new ValueExpression(this.value.displayOrder); + } + + progress(): ValueExpression { + const path = this.path.member('progress', 'progress'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('progress')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'progress'), + ); + } + return new ValueExpression(this.value.progress); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + platformId(): ValueExpression { + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + platform(): PlatformExpression { + const path = this.path.member('platform', 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const relation = this.value.platform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; + return new PlatformExpression(target, this.root, path); + } + + taskList(): TaskListExpression { + const path = this.path.member('task_list', 'taskList'); + if (this.notLoaded) { + return new TaskListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return TaskListExpression.missing(this.root, path); + if (!this.value.isLoaded('taskList')) { + return new TaskListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'task_list')); + } + return new TaskListExpression( + this.value.taskList(), this.root, path, + ); + } +} + +export class TaskExpression { + constructor( + private readonly value: Task | null | undefined, + private readonly root = 'Task(null)', + private readonly path = ExpressionPath.root('E.task()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Task | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + statusId(): ValueExpression { + const path = this.path.member('status', 'statusId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('status')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'status'), + ); + } + const reference = this.value.status; + return new ValueExpression( + reference instanceof TaskStatus + ? reference.id : reference as string | number | undefined, + ); + } + + platformId(): ValueExpression { + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('platform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'platform'), + ); + } + const reference = this.value.platform; + return new ValueExpression( + reference instanceof Platform + ? reference.id : reference as string | number | undefined, + ); + } + + status(): TaskStatusExpression { + const path = this.path.member('status', 'status'); + if (this.notLoaded) { + return new TaskStatusExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TaskStatusExpression(undefined, this.root, path); + if (!this.value.isLoaded('status')) { + return new TaskStatusExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'status')); + } + const relation = this.value.status; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof TaskStatus)) { + return new TaskStatusExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'status')); + } + const target = relation instanceof TaskStatus ? relation : undefined; + return new TaskStatusExpression(target, this.root, path); + } + + platform(): PlatformExpression { + const path = this.path.member('platform', 'platform'); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new PlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('platform')) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const relation = this.value.platform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; + return new PlatformExpression(target, this.root, path); + } + + taskExecutionLogList(): TaskExecutionLogListExpression { + const path = this.path.member('task_execution_log_list', 'taskExecutionLogList'); + if (this.notLoaded) { + return new TaskExecutionLogListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return TaskExecutionLogListExpression.missing(this.root, path); + if (!this.value.isLoaded('taskExecutionLogList')) { + return new TaskExecutionLogListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'task_execution_log_list')); + } + return new TaskExecutionLogListExpression( + this.value.taskExecutionLogList(), this.root, path, + ); + } +} + +export class TaskExecutionLogExpression { + constructor( + private readonly value: TaskExecutionLog | null | undefined, + private readonly root = 'TaskExecutionLog(null)', + private readonly path = ExpressionPath.root('E.taskExecutionLog()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TaskExecutionLog | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + action(): ValueExpression { + const path = this.path.member('action', 'action'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('action')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'action'), + ); + } + return new ValueExpression(this.value.action); + } + + detail(): ValueExpression { + const path = this.path.member('detail', 'detail'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('detail')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'detail'), + ); + } + return new ValueExpression(this.value.detail); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + taskId(): ValueExpression { + const path = this.path.member('task', 'taskId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('task')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'task'), + ); + } + const reference = this.value.task; + return new ValueExpression( + reference instanceof Task + ? reference.id : reference as string | number | undefined, + ); + } + + task(): TaskExpression { + const path = this.path.member('task', 'task'); + if (this.notLoaded) { + return new TaskExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TaskExpression(undefined, this.root, path); + if (!this.value.isLoaded('task')) { + return new TaskExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'task')); + } + const relation = this.value.task; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Task)) { + return new TaskExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'task')); + } + const target = relation instanceof Task ? relation : undefined; + return new TaskExpression(target, this.root, path); + } + +} + +export class PlatformListExpression { + constructor( + private readonly items: readonly Platform[], + private readonly root = 'Platform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { + return new PlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PlatformExpression { + return this.item(0, true); + } + + get(index: number): PlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new PlatformExpression(undefined, this.root, itemPath) + : new PlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class TaskStatusListExpression { + constructor( + private readonly items: readonly TaskStatus[], + private readonly root = 'TaskStatus(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TaskStatusListExpression { + return new TaskStatusListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TaskStatusExpression { + return this.item(0, true); + } + + get(index: number): TaskStatusExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TaskStatusExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TaskStatusExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TaskStatusExpression(undefined, this.root, itemPath) + : new TaskStatusExpression(this.items[index], this.root, itemPath); + } +} + +export class TaskListExpression { + constructor( + private readonly items: readonly Task[], + private readonly root = 'Task(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TaskListExpression { + return new TaskListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TaskExpression { + return this.item(0, true); + } + + get(index: number): TaskExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TaskExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TaskExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TaskExpression(undefined, this.root, itemPath) + : new TaskExpression(this.items[index], this.root, itemPath); + } +} + +export class TaskExecutionLogListExpression { + constructor( + private readonly items: readonly TaskExecutionLog[], + private readonly root = 'TaskExecutionLog(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TaskExecutionLogListExpression { + return new TaskExecutionLogListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TaskExecutionLogExpression { + return this.item(0, true); + } + + get(index: number): TaskExecutionLogExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TaskExecutionLogExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TaskExecutionLogExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TaskExecutionLogExpression(undefined, this.root, itemPath) + : new TaskExecutionLogExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static platform( + value: Platform | null | undefined, + ): PlatformExpression { + return new PlatformExpression( + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), + ); + } + + static taskStatus( + value: TaskStatus | null | undefined, + ): TaskStatusExpression { + return new TaskStatusExpression( + value, 'TaskStatus', ExpressionPath.root('E.taskStatus()', 'camelCase'), + ); + } + + static task( + value: Task | null | undefined, + ): TaskExpression { + return new TaskExpression( + value, 'Task', ExpressionPath.root('E.task()', 'camelCase'), + ); + } + + static taskExecutionLog( + value: TaskExecutionLog | null | undefined, + ): TaskExecutionLogExpression { + return new TaskExecutionLogExpression( + value, 'TaskExecutionLog', ExpressionPath.root('E.taskExecutionLog()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts index ea7decc08f8bfe4dc767a8e217b6a99855c35e3c..8050b2cca4e030b9c27be596471651ec999de645 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/Q.ts @@ -1,4 +1,4 @@ -import { TeaQLClient } from '../../../../../src'; +import { TeaQLClient } from '../teaql-ts'; import { PlatformRequest } from './requests/PlatformRequest'; import { TaskStatusRequest } from './requests/TaskStatusRequest'; import { TaskRequest } from './requests/TaskRequest'; @@ -6,15 +6,31 @@ import { TaskExecutionLogRequest } from './requests/TaskExecutionLogRequest'; export class Q { static platforms(): PlatformRequest { - return new PlatformRequest(); + return new PlatformRequest(false); + } + + static platformsWithMinimalFields(): PlatformRequest { + return new PlatformRequest(true); } static taskStatuses(): TaskStatusRequest { - return new TaskStatusRequest(); + return new TaskStatusRequest(false); + } + + static taskStatusesWithMinimalFields(): TaskStatusRequest { + return new TaskStatusRequest(true); } static tasks(): TaskRequest { - return new TaskRequest(); + return new TaskRequest(false); + } + + static tasksWithMinimalFields(): TaskRequest { + return new TaskRequest(true); } static taskExecutionLogs(): TaskExecutionLogRequest { - return new TaskExecutionLogRequest(); + return new TaskExecutionLogRequest(false); + } + + static taskExecutionLogsWithMinimalFields(): TaskExecutionLogRequest { + return new TaskExecutionLogRequest(true); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts index 7cd84985c1d6959bedefbbe6d0d06952b2bfaee4..4fc8b270e94fa366347d1362371ade446e7bc71c 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Platform.ts @@ -1,34 +1,512 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TaskStatus } from './TaskStatus'; +import { Task } from './Task'; + +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { - id?: any; + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "founded", "user_email", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; name?: string; - founded?: any; + founded?: string; userEmail?: string; - version?: any; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_taskStatusList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_taskList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["taskStatusList"]; + delete fields["taskList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).taskStatusList)) { + const selected = (init as any).taskStatusList; + (this as any)._taskStatusList = new SmartList(selected.map( + (child: unknown) => child instanceof TaskStatus + ? child + : TaskStatus.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("taskStatusList"); + } + if (Array.isArray((init as any).taskList)) { + const selected = (init as any).taskList; + (this as any)._taskList = new SmartList(selected.map( + (child: unknown) => child instanceof Task + ? child + : Task.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("taskList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._taskStatusList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._taskList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Platform { + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("taskStatusList")) result["taskStatusList"] = (this as any)._taskStatusList; + if (this.isLoaded("taskList")) result["taskList"] = (this as any)._taskList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Platform { + return Platform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: any): Promise { + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._taskStatusList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._taskList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._taskStatusList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._taskList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._taskStatusList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._taskList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "task_status_list": graph.sourceMembers((this as any)._taskStatusList), + "task_list": graph.sourceMembers((this as any)._taskList) + })); + for (const child of (this as any)._taskStatusList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._taskList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "founded", canonical: "founded" }, { member: "userEmail", canonical: "user_email" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._taskStatusList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._taskList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "founded", canonical: "founded" }, { member: "userEmail", canonical: "user_email" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Platform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Platform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "Platform", action: (this as any)._action, - payload: this, - id: this.id, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._taskStatusList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_status_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "founded": this.founded, + "user_email": this.userEmail, + "version": this.version }; - return ctx.client.executeMutation(mutation); + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateFounded(value: string): this { + this.founded = value; + this.markLoaded("founded"); + (this as any)._root.set(this.teaqlEntityKey(), "founded", value); + return this; + } + + updateUserEmail(value: string): this { + this.userEmail = value; + this.markLoaded("userEmail"); + (this as any)._root.set(this.teaqlEntityKey(), "user_email", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + taskStatusList(): SmartList { + return (this as any)._taskStatusList; + } + + taskList(): SmartList { + return (this as any)._taskList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts index bd6fb960c914641676ae4ecda2ce485e61fde41c..5f94070169f1c1f93397e68e287a25c0690a95b9 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/Task.ts @@ -1,34 +1,462 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TaskStatus } from './TaskStatus'; +import { Platform } from './Platform'; +import { TaskExecutionLog } from './TaskExecutionLog'; + +const teaqlConstruction = Symbol("managed entity construction"); + export class Task { - id?: any; + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Task", + ["id", "name", "status", "platform", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; name?: string; - status?: any; - platform?: any; - version?: any; + status?: TaskStatus | string; + platform?: Platform | string; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Task.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_taskExecutionLogList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["taskExecutionLogList"]; + Object.assign(this, fields); + if ((init as any).status && typeof (init as any).status === "object") { + this.status = (init as any).status instanceof TaskStatus + ? (init as any).status + : TaskStatus.fromRecord((init as any).status); + this.markLoaded("status"); + } + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if (Array.isArray((init as any).taskExecutionLogList)) { + const selected = (init as any).taskExecutionLogList; + (this as any)._taskExecutionLogList = new SmartList(selected.map( + (child: unknown) => child instanceof TaskExecutionLog + ? child + : TaskExecutionLog.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("taskExecutionLogList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Task", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._taskExecutionLogList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Task { + const entity = EntityCreation.hydrated(new Task(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("taskExecutionLogList")) result["taskExecutionLogList"] = (this as any)._taskExecutionLogList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Task { + return Task.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): Task { + return EntityCreation.bootstrap(context, "Task", id, + reserved => new Task({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Task", + reserved => new Task({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: any): Promise { + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._taskExecutionLogList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._taskExecutionLogList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_execution_log_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Task.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._taskExecutionLogList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Task.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "status": "TaskStatus", + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "task_execution_log_list": graph.sourceMembers((this as any)._taskExecutionLogList) + })); + for (const child of (this as any)._taskExecutionLogList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.task; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("task") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTask(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Task.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "status", canonical: "status" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Task", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._taskExecutionLogList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_execution_log_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(Task.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "status", canonical: "status" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Task", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Task", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskExecutionLogList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.task; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("task") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTask(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_execution_log_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "Task", action: (this as any)._action, - payload: this, - id: this.id, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - return ctx.client.executeMutation(mutation); + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskExecutionLogList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.task; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("task") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTask(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_execution_log_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._taskExecutionLogList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.task; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("task") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTask(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_execution_log_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "status": this.status, + "platform": this.platform, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateStatus(value: any): this { + this.status = value?.id ?? value; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); + return this; + } + public updateStatusToPlanned(): Task { + this.status = "1001"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); + return this; + } + public updateStatusToReady(): Task { + this.status = "1002"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); + return this; + } + public updateStatusToExecuting(): Task { + this.status = "1003"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); + return this; + } + public updateStatusToVerified(): Task { + this.status = "1004"; + this.markLoaded("status"); + (this as any)._root.set(this.teaqlEntityKey(), "status", this.status); + return this; + } + + + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + taskExecutionLogList(): SmartList { + return (this as any)._taskExecutionLogList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts index 09ef85dc9a9169a900af58be3c0a99a6f66ce366..32edd3094fc7ebebb424dfbae41c59d5f00ed70b 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts @@ -1,34 +1,339 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Task } from './Task'; + +const teaqlConstruction = Symbol("managed entity construction"); + export class TaskExecutionLog { - id?: any; - task?: any; + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TaskExecutionLog", + ["id", "task", "action", "detail", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + task?: Task | string; action?: string; detail?: string; - version?: any; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TaskExecutionLog.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).task && typeof (init as any).task === "object") { + this.task = (init as any).task instanceof Task + ? (init as any).task + : Task.fromRecord((init as any).task); + this.markLoaded("task"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TaskExecutionLog", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TaskExecutionLog { + const entity = EntityCreation.hydrated(new TaskExecutionLog(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TaskExecutionLog { + return TaskExecutionLog.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TaskExecutionLog { + return EntityCreation.bootstrap(context, "TaskExecutionLog", id, + reserved => new TaskExecutionLog({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TaskExecutionLog", + reserved => new TaskExecutionLog({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: any): Promise { + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TaskExecutionLog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TaskExecutionLog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "task": "Task" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TaskExecutionLog.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "task", canonical: "task" }, { member: "action", canonical: "action" }, { member: "detail", canonical: "detail" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TaskExecutionLog", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TaskExecutionLog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "task", canonical: "task" }, { member: "action", canonical: "action" }, { member: "detail", canonical: "detail" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TaskExecutionLog", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TaskExecutionLog", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "TaskExecutionLog", action: (this as any)._action, - payload: this, - id: this.id, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - return ctx.client.executeMutation(mutation); + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "task": this.task, + "action": this.action, + "detail": this.detail, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateAction(value: string): this { + this.action = value; + this.markLoaded("action"); + (this as any)._root.set(this.teaqlEntityKey(), "action", value); + return this; + } + + updateDetail(value: string): this { + this.detail = value; + this.markLoaded("detail"); + (this as any)._root.set(this.teaqlEntityKey(), "detail", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateTask(value: any): this { + this.task = value?.id ?? value; + this.markLoaded("task"); + (this as any)._root.set(this.teaqlEntityKey(), "task", this.task); + return this; + } + } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts index 8faed124dc20814aebb72093192a6c0a197b75c2..644d9fb2a37d6edbf5cf1b26eb16e2cabe36aff2 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts @@ -1,37 +1,458 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Platform } from './Platform'; +import { Task } from './Task'; + +const teaqlConstruction = Symbol("managed entity construction"); + export class TaskStatus { - id?: any; + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TaskStatus", + ["id", "name", "code", "color", "display_order", "progress", "platform", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; name?: string; code?: string; color?: string; - displayOrder?: number; - progress?: number; - platform?: any; - version?: any; + displayOrder?: Decimal; + progress?: Decimal; + platform?: Platform | string; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - if (init) Object.assign(this, init); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TaskStatus.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_taskList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["taskList"]; + Object.assign(this, fields); + if ((init as any).platform && typeof (init as any).platform === "object") { + this.platform = (init as any).platform instanceof Platform + ? (init as any).platform + : Platform.fromRecord((init as any).platform); + this.markLoaded("platform"); + } + if (Array.isArray((init as any).taskList)) { + const selected = (init as any).taskList; + (this as any)._taskList = new SmartList(selected.map( + (child: unknown) => child instanceof Task + ? child + : Task.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("taskList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TaskStatus", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._taskList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TaskStatus { + const entity = EntityCreation.hydrated(new TaskStatus(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("taskList")) result["taskList"] = (this as any)._taskList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TaskStatus { + return TaskStatus.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TaskStatus { + return EntityCreation.bootstrap(context, "TaskStatus", id, + reserved => new TaskStatus({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TaskStatus", + reserved => new TaskStatus({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); return this; } auditAs(comment: string): this { - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } - async save(ctx: any): Promise { + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._taskList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._taskList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TaskStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._taskList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TaskStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "task_list": graph.sourceMembers((this as any)._taskList) + })); + for (const child of (this as any)._taskList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TaskStatus.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "progress", canonical: "progress" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TaskStatus", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._taskList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TaskStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "progress", canonical: "progress" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TaskStatus", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TaskStatus", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { entity: "TaskStatus", action: (this as any)._action, - payload: this, - id: this.id, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root }; - return ctx.client.executeMutation(mutation); + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._taskList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("task_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "code": this.code, + "color": this.color, + "display_order": this.displayOrder, + "progress": this.progress, + "platform": this.platform, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateCode(value: string): this { + this.code = value; + this.markLoaded("code"); + (this as any)._root.set(this.teaqlEntityKey(), "code", value); + return this; + } + + updateColor(value: string): this { + this.color = value; + this.markLoaded("color"); + (this as any)._root.set(this.teaqlEntityKey(), "color", value); + return this; + } + + updateDisplayOrder(value: Decimal): this { + if (value != null) value = decimal(value); + this.displayOrder = value; + this.markLoaded("displayOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); + return this; + } + + updateProgress(value: Decimal): this { + if (value != null) value = decimal(value); + this.progress = value; + this.markLoaded("progress"); + (this as any)._root.set(this.teaqlEntityKey(), "progress", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePlatform(value: any): this { + this.platform = value?.id ?? value; + this.markLoaded("platform"); + (this as any)._root.set(this.teaqlEntityKey(), "platform", this.platform); + return this; + } + + taskList(): SmartList { + return (this as any)._taskList; } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts index a09405179972b70ca71f72f7c21d5f142836dde4..fd16c828265d3a6d9d5b765e630d416bae3fd5df 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts @@ -1,68 +1,912 @@ -import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + export class PlatformRequest { private query: SelectQuery; - private filters: any = {}; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("Platform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "Platform" { + return "Platform"; } comment(c: string): this { this.query.comment(c); + this._comment = c; return this; } - purpose(p: string): this { + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutablePlatformRequest { this.query.purpose(p); + this._purpose = p; + return new ExecutablePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "founded", "userEmail", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectFounded(): this { + this.query.select(["founded"]); + return this; + } + + selectUserEmail(): this { + this.query.select(["userEmail"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectTaskStatusListWith(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "taskStatusList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectTaskStatusListWith", relation: "taskStatusList" }); + return this; + } + selectTaskListWith(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "taskList", request.toQuery(), "id", "platform", true, + { kind: "relation-select", method: "selectTaskListWith", relation: "taskList" }); + return this; + } + + haveTaskStatuses(): this { + return this.withTaskStatusListMatching({ + entityName: "TaskStatus", + toQuery: () => new SelectQuery("TaskStatus"), + }); + } + + haveNoTaskStatuses(): this { + return this.withoutTaskStatusListMatching({ + entityName: "TaskStatus", + toQuery: () => new SelectQuery("TaskStatus"), + }); + } + + withTaskStatusListMatching(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutTaskStatusListMatching(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + haveTasks(): this { + return this.withTaskListMatching({ + entityName: "Task", + toQuery: () => new SelectQuery("Task"), + }); + } + + haveNoTasks(): this { + return this.withoutTaskListMatching({ + entityName: "Task", + toQuery: () => new SelectQuery("Task"), + }); + } + + withTaskListMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + withoutTaskListMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "platform", + }, + }, + }); + return this; + } + + countTaskStatuses(): this { + return this.countTaskStatusesAs("countTaskStatuses"); + } + + countTaskStatusesAs(alias: string): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + this.countTaskStatusesWith(alias, { entityName: "TaskStatus", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countTaskStatusesAs", relation: "taskStatusList", alias }; + return this; + } + + countTaskStatusesWith(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "relation-count", method: "countTaskStatusesWith", relation: "taskStatusList", alias }); return this; } - withIdIs(val: any): this { - this.filters["id"] = { "$eq": val }; + minDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.minDisplayOrderOfTaskStatusesAs( + "minOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + minDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "minDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + maxDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.maxDisplayOrderOfTaskStatusesAs( + "maxOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + maxDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "maxDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + sumDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.sumDisplayOrderOfTaskStatusesAs( + "sumOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + sumDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "sumDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + avgDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.avgDisplayOrderOfTaskStatusesAs( + "avgOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + avgDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "avgDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + standardDeviationDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.standardDeviationDisplayOrderOfTaskStatusesAs( + "standardDeviationOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + standardDeviationDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "standardDeviationDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationDisplayOrderOfTaskStatusesAs( + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + sampleVarianceDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceDisplayOrderOfTaskStatusesAs( + "sampleVarianceOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + sampleVarianceDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + samplePopulationVarianceDisplayOrderOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceDisplayOrderOfTaskStatusesAs( + "samplePopulationVarianceOfDisplayOrderOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + samplePopulationVarianceDisplayOrderOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "displayOrder", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceDisplayOrderOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + minProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.minProgressOfTaskStatusesAs( + "minOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + minProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "minProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + maxProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.maxProgressOfTaskStatusesAs( + "maxOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + maxProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "maxProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + sumProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.sumProgressOfTaskStatusesAs( + "sumOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + sumProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "sumProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + avgProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.avgProgressOfTaskStatusesAs( + "avgOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + avgProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "avgProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + standardDeviationProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.standardDeviationProgressOfTaskStatusesAs( + "standardDeviationOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + standardDeviationProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "standardDeviationProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationProgressOfTaskStatusesAs( + "squareRootOfPopulationStandardDeviationOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + sampleVarianceProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceProgressOfTaskStatusesAs( + "sampleVarianceOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + sampleVarianceProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + samplePopulationVarianceProgressOfTaskStatuses(): this { + const query = new SelectQuery("TaskStatus").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceProgressOfTaskStatusesAs( + "samplePopulationVarianceOfProgressOfTaskStatuses", { entityName: "TaskStatus", toQuery: () => query }); + } + + samplePopulationVarianceProgressOfTaskStatusesAs(alias: string, child: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "progress", alias); + this.query.relationAggregate("taskStatusList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceProgressOfTaskStatusesAs", relation: "taskStatusList", alias }); + return this; + } + countTasks(): this { + return this.countTasksAs("countTasks"); + } + + countTasksAs(alias: string): this { + const query = new SelectQuery("Task").filter({ version: { "$gte": 1 } }); + this.countTasksWith(alias, { entityName: "Task", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countTasksAs", relation: "taskList", alias }; + return this; + } + + countTasksWith(alias: string, child: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("taskList", alias, query, true, + { kind: "relation-count", method: "countTasksWith", relation: "taskList", alias }); + return this; + } + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); return this; } withNameContaining(val: string): this { - this.filters["name"] = { "$contains": val }; + this.filters.push({ "name": { "$contains": val } }); return this; } withNameIs(val: string): this { - this.filters["name"] = { "$eq": val }; + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); return this; } - withFoundedIs(val: any): this { - this.filters["founded"] = { "$eq": val }; + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withFoundedIs(val: unknown): this { + this.filters.push({ "founded": { "$eq": val } }); + return this; + } + + withFoundedIsNot(val: unknown): this { + this.filters.push({ "founded": { "$ne": val } }); + return this; + } + + withFoundedIn(...vals: unknown[]): this { + this.filters.push({ "founded": { "$in": vals } }); + return this; + } + + withFoundedNotIn(...vals: unknown[]): this { + this.filters.push({ "founded": { "$notIn": vals } }); + return this; + } + + withFoundedGreaterThan(val: unknown): this { + this.filters.push({ "founded": { "$gt": val } }); + return this; + } + + withFoundedGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "founded": { "$gte": val } }); + return this; + } + + withFoundedLessThan(val: unknown): this { + this.filters.push({ "founded": { "$lt": val } }); + return this; + } + + withFoundedLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "founded": { "$lte": val } }); + return this; + } + + withFoundedBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "founded": { "$between": [lower, upper] } }); + return this; + } + + withFoundedIsKnown(): this { + this.filters.push({ "founded": { "$isNull": false } }); + return this; + } + + withFoundedIsUnknown(): this { + this.filters.push({ "founded": { "$isNull": true } }); return this; } withUserEmailContaining(val: string): this { - this.filters["userEmail"] = { "$contains": val }; + this.filters.push({ "userEmail": { "$contains": val } }); return this; } withUserEmailIs(val: string): this { - this.filters["userEmail"] = { "$eq": val }; + this.filters.push({ "userEmail": { "$eq": val } }); + return this; + } + + withUserEmailIsNot(val: string): this { + this.filters.push({ "userEmail": { "$ne": val } }); + return this; + } + + withUserEmailIn(...vals: string[]): this { + this.filters.push({ "userEmail": { "$in": vals } }); + return this; + } + + withUserEmailNotIn(...vals: string[]): this { + this.filters.push({ "userEmail": { "$notIn": vals } }); + return this; + } + + withUserEmailGreaterThan(val: string): this { + this.filters.push({ "userEmail": { "$gt": val } }); + return this; + } + + withUserEmailGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "userEmail": { "$gte": val } }); + return this; + } + + withUserEmailLessThan(val: string): this { + this.filters.push({ "userEmail": { "$lt": val } }); + return this; + } + + withUserEmailLessThanOrEqualTo(val: string): this { + this.filters.push({ "userEmail": { "$lte": val } }); + return this; + } + + withUserEmailBetween(lower: string, upper: string): this { + this.filters.push({ "userEmail": { "$between": [lower, upper] } }); + return this; + } + + withUserEmailIsKnown(): this { + this.filters.push({ "userEmail": { "$isNull": false } }); + return this; + } + + withUserEmailIsUnknown(): this { + this.filters.push({ "userEmail": { "$isNull": true } }); + return this; + } + withUserEmailNotContaining(val: string): this { + this.filters.push({ "userEmail": { "$notContains": val } }); + return this; + } + + withUserEmailStartingWith(val: string): this { + this.filters.push({ "userEmail": { "$startsWith": val } }); + return this; + } + + withUserEmailNotStartingWith(val: string): this { + this.filters.push({ "userEmail": { "$notStartsWith": val } }); + return this; + } + + withUserEmailEndingWith(val: string): this { + this.filters.push({ "userEmail": { "$endsWith": val } }); + return this; + } + + withUserEmailNotEndingWith(val: string): this { + this.filters.push({ "userEmail": { "$notEndsWith": val } }); + return this; + } + + withUserEmailSoundingLike(val: string): this { + this.filters.push({ "userEmail": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); return this; } - withVersionIs(val: any): this { - this.filters["version"] = { "$eq": val }; + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); return this; } + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByFoundedAscending(): this { + this.query.orderBy("founded", "asc"); + return this; + } + + orderByFoundedDescending(): this { + this.query.orderBy("founded", "desc"); + return this; + } + + orderByUserEmailAscending(): this { + this.query.orderBy("userEmail", "asc"); + return this; + } + + orderByUserEmailDescending(): this { + this.query.orderBy("userEmail", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -74,72 +918,178 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } - groupByName(): this { this.query.groupBy("name"); return this; } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } - groupByFounded(): this { this.query.groupBy("founded"); return this; } groupByFoundedAs(retName: string): this { - this.query.groupBy("founded"); // In TS we don't alias group by yet natively + this.query.groupBy("founded", retName); return this; } - groupByUserEmail(): this { - this.query.groupBy("user_email"); + this.query.groupBy("userEmail"); return this; } groupByUserEmailAs(retName: string): this { - this.query.groupBy("user_email"); // In TS we don't alias group by yet natively + this.query.groupBy("userEmail", retName); return this; } - groupByVersion(): this { this.query.groupBy("version"); return this; } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } - // --- Facets --- - async executeForList(ctx: any): Promise { - if (Object.keys(this.filters).length > 0) { - this.query.filter(this.filters); + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); } - const data = await ctx.client.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (Object.keys(this.filters).length > 0) { - f.query.filter(this.filters); // Inherit outer filters - } - result.facets[f.facetName] = await ctx.client.executeQuery(f.query); - } + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); } return result; } + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Platform + ? row + : Platform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Platform + ? entity + : Platform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutablePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts index 9b7604b1c491dafdaeb160db28729b1e6dccb319..f56b5669280850ec4541a925884f24d109831f83 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts @@ -1,64 +1,539 @@ -import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { TaskExecutionLog } from '../models/TaskExecutionLog'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + export class TaskExecutionLogRequest { private query: SelectQuery; - private filters: any = {}; - - constructor() { + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { this.query = new SelectQuery("TaskExecutionLog"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TaskExecutionLog" { + return "TaskExecutionLog"; } comment(c: string): this { this.query.comment(c); + this._comment = c; return this; } - purpose(p: string): this { + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTaskExecutionLogRequest { this.query.purpose(p); + this._purpose = p; + return new ExecutableTaskExecutionLogRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); return this; } - withIdIs(val: any): this { - this.filters["id"] = { "$eq": val }; + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "task", "action", "detail", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectAction(): this { + this.query.select(["action"]); + return this; + } + + selectDetail(): this { + this.query.select(["detail"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTaskWith(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.query.select(["task"]); + this.query.relationQuery( + "task", request.toQuery(), "task", "id", false, + { kind: "relation-select", method: "selectTaskWith", relation: "task" }); + return this; + } + + withTaskMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "task": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTaskMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "task": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); return this; } + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTask(val: any): this { + this.filters.push({ "task": { "$eq": val } }); + return this; + } + + filterByTaskIn(...vals: any[]): this { + this.filters.push({ "task": { "$in": vals } }); + return this; + } + + withTaskIsKnown(): this { + this.filters.push({ "task": { "$isNull": false } }); + return this; + } + + withTaskIsUnknown(): this { + this.filters.push({ "task": { "$isNull": true } }); + return this; + } withActionContaining(val: string): this { - this.filters["action"] = { "$contains": val }; + this.filters.push({ "action": { "$contains": val } }); return this; } withActionIs(val: string): this { - this.filters["action"] = { "$eq": val }; + this.filters.push({ "action": { "$eq": val } }); + return this; + } + + withActionIsNot(val: string): this { + this.filters.push({ "action": { "$ne": val } }); + return this; + } + + withActionIn(...vals: string[]): this { + this.filters.push({ "action": { "$in": vals } }); + return this; + } + + withActionNotIn(...vals: string[]): this { + this.filters.push({ "action": { "$notIn": vals } }); + return this; + } + + withActionGreaterThan(val: string): this { + this.filters.push({ "action": { "$gt": val } }); + return this; + } + + withActionGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "action": { "$gte": val } }); + return this; + } + + withActionLessThan(val: string): this { + this.filters.push({ "action": { "$lt": val } }); + return this; + } + + withActionLessThanOrEqualTo(val: string): this { + this.filters.push({ "action": { "$lte": val } }); + return this; + } + + withActionBetween(lower: string, upper: string): this { + this.filters.push({ "action": { "$between": [lower, upper] } }); + return this; + } + + withActionIsKnown(): this { + this.filters.push({ "action": { "$isNull": false } }); + return this; + } + + withActionIsUnknown(): this { + this.filters.push({ "action": { "$isNull": true } }); + return this; + } + withActionNotContaining(val: string): this { + this.filters.push({ "action": { "$notContains": val } }); + return this; + } + + withActionStartingWith(val: string): this { + this.filters.push({ "action": { "$startsWith": val } }); + return this; + } + + withActionNotStartingWith(val: string): this { + this.filters.push({ "action": { "$notStartsWith": val } }); + return this; + } + + withActionEndingWith(val: string): this { + this.filters.push({ "action": { "$endsWith": val } }); + return this; + } + + withActionNotEndingWith(val: string): this { + this.filters.push({ "action": { "$notEndsWith": val } }); + return this; + } + + withActionSoundingLike(val: string): this { + this.filters.push({ "action": { "$soundLike": val } }); return this; } withDetailContaining(val: string): this { - this.filters["detail"] = { "$contains": val }; + this.filters.push({ "detail": { "$contains": val } }); return this; } withDetailIs(val: string): this { - this.filters["detail"] = { "$eq": val }; + this.filters.push({ "detail": { "$eq": val } }); + return this; + } + + withDetailIsNot(val: string): this { + this.filters.push({ "detail": { "$ne": val } }); + return this; + } + + withDetailIn(...vals: string[]): this { + this.filters.push({ "detail": { "$in": vals } }); + return this; + } + + withDetailNotIn(...vals: string[]): this { + this.filters.push({ "detail": { "$notIn": vals } }); + return this; + } + + withDetailGreaterThan(val: string): this { + this.filters.push({ "detail": { "$gt": val } }); + return this; + } + + withDetailGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "detail": { "$gte": val } }); + return this; + } + + withDetailLessThan(val: string): this { + this.filters.push({ "detail": { "$lt": val } }); + return this; + } + + withDetailLessThanOrEqualTo(val: string): this { + this.filters.push({ "detail": { "$lte": val } }); + return this; + } + + withDetailBetween(lower: string, upper: string): this { + this.filters.push({ "detail": { "$between": [lower, upper] } }); + return this; + } + + withDetailIsKnown(): this { + this.filters.push({ "detail": { "$isNull": false } }); return this; } - withVersionIs(val: any): this { - this.filters["version"] = { "$eq": val }; + withDetailIsUnknown(): this { + this.filters.push({ "detail": { "$isNull": true } }); + return this; + } + withDetailNotContaining(val: string): this { + this.filters.push({ "detail": { "$notContains": val } }); + return this; + } + + withDetailStartingWith(val: string): this { + this.filters.push({ "detail": { "$startsWith": val } }); return this; } + withDetailNotStartingWith(val: string): this { + this.filters.push({ "detail": { "$notStartsWith": val } }); + return this; + } + + withDetailEndingWith(val: string): this { + this.filters.push({ "detail": { "$endsWith": val } }); + return this; + } + + withDetailNotEndingWith(val: string): this { + this.filters.push({ "detail": { "$notEndsWith": val } }); + return this; + } + + withDetailSoundingLike(val: string): this { + this.filters.push({ "detail": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByActionAscending(): this { + this.query.orderBy("action", "asc"); + return this; + } + + orderByActionDescending(): this { + this.query.orderBy("action", "desc"); + return this; + } + + orderByDetailAscending(): this { + this.query.orderBy("detail", "asc"); + return this; + } + + orderByDetailDescending(): this { + this.query.orderBy("detail", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -70,68 +545,188 @@ export class TaskExecutionLogRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); + return this; + } + groupByTask(): this { + this.query.groupBy("task"); return this; } - + groupByTaskAs(retName: string): this { + this.query.groupBy("task", retName); + return this; + } groupByAction(): this { this.query.groupBy("action"); return this; } groupByActionAs(retName: string): this { - this.query.groupBy("action"); // In TS we don't alias group by yet natively + this.query.groupBy("action", retName); return this; } - groupByDetail(): this { this.query.groupBy("detail"); return this; } groupByDetailAs(retName: string): this { - this.query.groupBy("detail"); // In TS we don't alias group by yet natively + this.query.groupBy("detail", retName); return this; } - groupByVersion(): this { this.query.groupBy("version"); return this; } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } - // --- Facets --- - facetByTaskAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "TASK_PROPERTY", request); + facetByTaskAs( + facetName: string, + request: { readonly entityName: "Task"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "task", request, includeAllFacets, + { kind: "facet", method: "facetByTaskAs", relation: "task", alias: facetName }); return this; } - async executeForList(ctx: any): Promise { - if (Object.keys(this.filters).length > 0) { - this.query.filter(this.filters); + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); } - const data = await ctx.client.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TaskExecutionLog + ? row + : TaskExecutionLog.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TaskExecutionLog + ? row + : TaskExecutionLog.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (Object.keys(this.filters).length > 0) { - f.query.filter(this.filters); // Inherit outer filters + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TaskExecutionLog + ? entity + : TaskExecutionLog.fromRecord(entity as Record, new EntityRoot()); } - result.facets[f.facetName] = await ctx.client.executeQuery(f.query); } - } + })(); + } - return result; + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTaskExecutionLogRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; } + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TaskExecutionLog.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts index 0d9b782ead34ad7aaa1fc8e83433f4b1f1ff6565..4af22757091eed951339d0ed9d1256945649c6f6 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts @@ -1,55 +1,560 @@ -import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Task } from '../models/Task'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + export class TaskRequest { private query: SelectQuery; - private filters: any = {}; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("Task"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "Task" { + return "Task"; } comment(c: string): this { this.query.comment(c); + this._comment = c; return this; } - purpose(p: string): this { + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTaskRequest { this.query.purpose(p); + this._purpose = p; + return new ExecutableTaskRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "status", "platform", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectStatusWith(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.query.select(["status"]); + this.query.relationQuery( + "status", request.toQuery(), "status", "id", false, + { kind: "relation-select", method: "selectStatusWith", relation: "status" }); + return this; + } + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withStatusMatching(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "status": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutStatusMatching(request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }): this { + this.filters.push({ + "status": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectTaskExecutionLogListWith(request: { readonly entityName: "TaskExecutionLog"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "taskExecutionLogList", request.toQuery(), "id", "task", true, + { kind: "relation-select", method: "selectTaskExecutionLogListWith", relation: "taskExecutionLogList" }); return this; } - withIdIs(val: any): this { - this.filters["id"] = { "$eq": val }; + haveTaskExecutionLogs(): this { + return this.withTaskExecutionLogListMatching({ + entityName: "TaskExecutionLog", + toQuery: () => new SelectQuery("TaskExecutionLog"), + }); + } + + haveNoTaskExecutionLogs(): this { + return this.withoutTaskExecutionLogListMatching({ + entityName: "TaskExecutionLog", + toQuery: () => new SelectQuery("TaskExecutionLog"), + }); + } + + withTaskExecutionLogListMatching(request: { readonly entityName: "TaskExecutionLog"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "task", + }, + }, + }); + return this; + } + + withoutTaskExecutionLogListMatching(request: { readonly entityName: "TaskExecutionLog"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "task", + }, + }, + }); + return this; + } + + countTaskExecutionLogs(): this { + return this.countTaskExecutionLogsAs("countTaskExecutionLogs"); + } + + countTaskExecutionLogsAs(alias: string): this { + const query = new SelectQuery("TaskExecutionLog").filter({ version: { "$gte": 1 } }); + this.countTaskExecutionLogsWith(alias, { entityName: "TaskExecutionLog", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countTaskExecutionLogsAs", relation: "taskExecutionLogList", alias }; + return this; + } + + countTaskExecutionLogsWith(alias: string, child: { readonly entityName: "TaskExecutionLog"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("taskExecutionLogList", alias, query, true, + { kind: "relation-count", method: "countTaskExecutionLogsWith", relation: "taskExecutionLogList", alias }); + return this; + } + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); return this; } withNameContaining(val: string): this { - this.filters["name"] = { "$contains": val }; + this.filters.push({ "name": { "$contains": val } }); return this; } withNameIs(val: string): this { - this.filters["name"] = { "$eq": val }; + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); return this; } + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } - withVersionIs(val: any): this { - this.filters["version"] = { "$eq": val }; + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + filterByStatus(val: any): this { + this.filters.push({ "status": { "$eq": val } }); + return this; + } + + filterByStatusIn(...vals: any[]): this { + this.filters.push({ "status": { "$in": vals } }); + return this; + } + + withStatusIsKnown(): this { + this.filters.push({ "status": { "$isNull": false } }); + return this; + } + + withStatusIsUnknown(): this { + this.filters.push({ "status": { "$isNull": true } }); + return this; + } + withStatusIsPlanned(): this { + this.filters.push({ "status": { "$eq": "1001" } }); + return this; + } + withStatusIsReady(): this { + this.filters.push({ "status": { "$eq": "1002" } }); + return this; + } + withStatusIsExecuting(): this { + this.filters.push({ "status": { "$eq": "1003" } }); + return this; + } + withStatusIsVerified(): this { + this.filters.push({ "status": { "$eq": "1004" } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -61,64 +566,198 @@ export class TaskRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } - groupByName(): this { this.query.groupBy("name"); return this; } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); + return this; + } + groupByStatus(): this { + this.query.groupBy("status"); return this; } + groupByStatusAs(retName: string): this { + this.query.groupBy("status", retName); + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); + return this; + } - + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform", retName); + return this; + } groupByVersion(): this { this.query.groupBy("version"); return this; } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } - // --- Facets --- - facetByStatusAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "STATUS_PROPERTY", request); + facetByStatusAs( + facetName: string, + request: { readonly entityName: "TaskStatus"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "status", request, includeAllFacets, + { kind: "facet", method: "facetByStatusAs", relation: "status", alias: facetName }); return this; } - facetByPlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "PLATFORM_PROPERTY", request); + facetByPlatformAs( + facetName: string, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); return this; } - async executeForList(ctx: any): Promise { - if (Object.keys(this.filters).length > 0) { - this.query.filter(this.filters); + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); } - const data = await ctx.client.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Task + ? row + : Task.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (Object.keys(this.filters).length > 0) { - f.query.filter(this.filters); // Inherit outer filters - } - result.facets[f.facetName] = await ctx.client.executeQuery(f.query); - } + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); } return result; } + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof Task + ? row + : Task.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Task + ? entity + : Task.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTaskRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Task.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts index 75e2dd816f9eba544263d0001716c7f02aa4b370..1bded7ee53b1d7c8b2d152e99a5919280642fff6 100644 --- a/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts @@ -1,84 +1,846 @@ -import { SelectQuery, TeaQLClient } from '../../../../../../src'; +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { TaskStatus } from '../models/TaskStatus'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + export class TaskStatusRequest { private query: SelectQuery; - private filters: any = {}; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; - constructor() { + constructor(minimal = false) { this.query = new SelectQuery("TaskStatus"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TaskStatus" { + return "TaskStatus"; } comment(c: string): this { this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); return this; } - purpose(p: string): this { + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTaskStatusRequest { this.query.purpose(p); + this._purpose = p; + return new ExecutableTaskStatusRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "code", "color", "displayOrder", "progress", "platform", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectCode(): this { + this.query.select(["code"]); + return this; + } + + selectColor(): this { + this.query.select(["color"]); + return this; + } + + selectDisplayOrder(): this { + this.query.select(["displayOrder"]); return this; } - withIdIs(val: any): this { - this.filters["id"] = { "$eq": val }; + selectProgress(): this { + this.query.select(["progress"]); + return this; + } + + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.query.select(["platform"]); + this.query.relationQuery( + "platform", request.toQuery(), "platform", "id", false, + { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); + return this; + } + + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "platform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + selectTaskListWith(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "taskList", request.toQuery(), "id", "status", true, + { kind: "relation-select", method: "selectTaskListWith", relation: "taskList" }); + return this; + } + + haveTasks(): this { + return this.withTaskListMatching({ + entityName: "Task", + toQuery: () => new SelectQuery("Task"), + }); + } + + haveNoTasks(): this { + return this.withoutTaskListMatching({ + entityName: "Task", + toQuery: () => new SelectQuery("Task"), + }); + } + + withTaskListMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "status", + }, + }, + }); + return this; + } + + withoutTaskListMatching(request: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "status", + }, + }, + }); + return this; + } + + countTasks(): this { + return this.countTasksAs("countTasks"); + } + + countTasksAs(alias: string): this { + const query = new SelectQuery("Task").filter({ version: { "$gte": 1 } }); + this.countTasksWith(alias, { entityName: "Task", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countTasksAs", relation: "taskList", alias }; + return this; + } + + countTasksWith(alias: string, child: { readonly entityName: "Task"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("taskList", alias, query, true, + { kind: "relation-count", method: "countTasksWith", relation: "taskList", alias }); + return this; + } + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); return this; } withNameContaining(val: string): this { - this.filters["name"] = { "$contains": val }; + this.filters.push({ "name": { "$contains": val } }); return this; } withNameIs(val: string): this { - this.filters["name"] = { "$eq": val }; + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); return this; } withCodeContaining(val: string): this { - this.filters["code"] = { "$contains": val }; + this.filters.push({ "code": { "$contains": val } }); return this; } withCodeIs(val: string): this { - this.filters["code"] = { "$eq": val }; + this.filters.push({ "code": { "$eq": val } }); + return this; + } + + withCodeIsNot(val: string): this { + this.filters.push({ "code": { "$ne": val } }); + return this; + } + + withCodeIn(...vals: string[]): this { + this.filters.push({ "code": { "$in": vals } }); + return this; + } + + withCodeNotIn(...vals: string[]): this { + this.filters.push({ "code": { "$notIn": vals } }); + return this; + } + + withCodeGreaterThan(val: string): this { + this.filters.push({ "code": { "$gt": val } }); + return this; + } + + withCodeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "code": { "$gte": val } }); + return this; + } + + withCodeLessThan(val: string): this { + this.filters.push({ "code": { "$lt": val } }); + return this; + } + + withCodeLessThanOrEqualTo(val: string): this { + this.filters.push({ "code": { "$lte": val } }); + return this; + } + + withCodeBetween(lower: string, upper: string): this { + this.filters.push({ "code": { "$between": [lower, upper] } }); + return this; + } + + withCodeIsKnown(): this { + this.filters.push({ "code": { "$isNull": false } }); + return this; + } + + withCodeIsUnknown(): this { + this.filters.push({ "code": { "$isNull": true } }); + return this; + } + withCodeNotContaining(val: string): this { + this.filters.push({ "code": { "$notContains": val } }); + return this; + } + + withCodeStartingWith(val: string): this { + this.filters.push({ "code": { "$startsWith": val } }); + return this; + } + + withCodeNotStartingWith(val: string): this { + this.filters.push({ "code": { "$notStartsWith": val } }); + return this; + } + + withCodeEndingWith(val: string): this { + this.filters.push({ "code": { "$endsWith": val } }); + return this; + } + + withCodeNotEndingWith(val: string): this { + this.filters.push({ "code": { "$notEndsWith": val } }); + return this; + } + + withCodeSoundingLike(val: string): this { + this.filters.push({ "code": { "$soundLike": val } }); return this; } withColorContaining(val: string): this { - this.filters["color"] = { "$contains": val }; + this.filters.push({ "color": { "$contains": val } }); return this; } withColorIs(val: string): this { - this.filters["color"] = { "$eq": val }; + this.filters.push({ "color": { "$eq": val } }); return this; } - withDisplayOrderIs(val: any): this { - this.filters["displayOrder"] = { "$eq": val }; + withColorIsNot(val: string): this { + this.filters.push({ "color": { "$ne": val } }); return this; } - withProgressIs(val: any): this { - this.filters["progress"] = { "$eq": val }; + withColorIn(...vals: string[]): this { + this.filters.push({ "color": { "$in": vals } }); return this; } + withColorNotIn(...vals: string[]): this { + this.filters.push({ "color": { "$notIn": vals } }); + return this; + } - withVersionIs(val: any): this { - this.filters["version"] = { "$eq": val }; + withColorGreaterThan(val: string): this { + this.filters.push({ "color": { "$gt": val } }); return this; } + withColorGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "color": { "$gte": val } }); + return this; + } + + withColorLessThan(val: string): this { + this.filters.push({ "color": { "$lt": val } }); + return this; + } + + withColorLessThanOrEqualTo(val: string): this { + this.filters.push({ "color": { "$lte": val } }); + return this; + } + + withColorBetween(lower: string, upper: string): this { + this.filters.push({ "color": { "$between": [lower, upper] } }); + return this; + } + + withColorIsKnown(): this { + this.filters.push({ "color": { "$isNull": false } }); + return this; + } + + withColorIsUnknown(): this { + this.filters.push({ "color": { "$isNull": true } }); + return this; + } + withColorNotContaining(val: string): this { + this.filters.push({ "color": { "$notContains": val } }); + return this; + } + + withColorStartingWith(val: string): this { + this.filters.push({ "color": { "$startsWith": val } }); + return this; + } + + withColorNotStartingWith(val: string): this { + this.filters.push({ "color": { "$notStartsWith": val } }); + return this; + } + + withColorEndingWith(val: string): this { + this.filters.push({ "color": { "$endsWith": val } }); + return this; + } + + withColorNotEndingWith(val: string): this { + this.filters.push({ "color": { "$notEndsWith": val } }); + return this; + } + + withColorSoundingLike(val: string): this { + this.filters.push({ "color": { "$soundLike": val } }); + return this; + } + + withDisplayOrderIs(val: Decimal): this { + this.filters.push({ "displayOrder": { "$eq": val } }); + return this; + } + + withDisplayOrderIsNot(val: Decimal): this { + this.filters.push({ "displayOrder": { "$ne": val } }); + return this; + } + + withDisplayOrderIn(...vals: Decimal[]): this { + this.filters.push({ "displayOrder": { "$in": vals } }); + return this; + } + + withDisplayOrderNotIn(...vals: Decimal[]): this { + this.filters.push({ "displayOrder": { "$notIn": vals } }); + return this; + } + + withDisplayOrderGreaterThan(val: Decimal): this { + this.filters.push({ "displayOrder": { "$gt": val } }); + return this; + } + + withDisplayOrderGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "displayOrder": { "$gte": val } }); + return this; + } + + withDisplayOrderLessThan(val: Decimal): this { + this.filters.push({ "displayOrder": { "$lt": val } }); + return this; + } + + withDisplayOrderLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "displayOrder": { "$lte": val } }); + return this; + } + + withDisplayOrderBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); + return this; + } + + withDisplayOrderIsKnown(): this { + this.filters.push({ "displayOrder": { "$isNull": false } }); + return this; + } + + withDisplayOrderIsUnknown(): this { + this.filters.push({ "displayOrder": { "$isNull": true } }); + return this; + } + + withProgressIs(val: Decimal): this { + this.filters.push({ "progress": { "$eq": val } }); + return this; + } + + withProgressIsNot(val: Decimal): this { + this.filters.push({ "progress": { "$ne": val } }); + return this; + } + + withProgressIn(...vals: Decimal[]): this { + this.filters.push({ "progress": { "$in": vals } }); + return this; + } + + withProgressNotIn(...vals: Decimal[]): this { + this.filters.push({ "progress": { "$notIn": vals } }); + return this; + } + + withProgressGreaterThan(val: Decimal): this { + this.filters.push({ "progress": { "$gt": val } }); + return this; + } + + withProgressGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "progress": { "$gte": val } }); + return this; + } + + withProgressLessThan(val: Decimal): this { + this.filters.push({ "progress": { "$lt": val } }); + return this; + } + + withProgressLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "progress": { "$lte": val } }); + return this; + } + + withProgressBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "progress": { "$between": [lower, upper] } }); + return this; + } + + withProgressIsKnown(): this { + this.filters.push({ "progress": { "$isNull": false } }); + return this; + } + + withProgressIsUnknown(): this { + this.filters.push({ "progress": { "$isNull": true } }); + return this; + } + + filterByPlatform(val: any): this { + this.filters.push({ "platform": { "$eq": val } }); + return this; + } + + filterByPlatformIn(...vals: any[]): this { + this.filters.push({ "platform": { "$in": vals } }); + return this; + } + + withPlatformIsKnown(): this { + this.filters.push({ "platform": { "$isNull": false } }); + return this; + } + + withPlatformIsUnknown(): this { + this.filters.push({ "platform": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByCodeAscending(): this { + this.query.orderBy("code", "asc"); + return this; + } + + orderByCodeDescending(): this { + this.query.orderBy("code", "desc"); + return this; + } + + orderByColorAscending(): this { + this.query.orderBy("color", "asc"); + return this; + } + + orderByColorDescending(): this { + this.query.orderBy("color", "desc"); + return this; + } + + orderByDisplayOrderAscending(): this { + this.query.orderBy("displayOrder", "asc"); + return this; + } + + orderByDisplayOrderDescending(): this { + this.query.orderBy("displayOrder", "desc"); + return this; + } + + orderByProgressAscending(): this { + this.query.orderBy("progress", "asc"); + return this; + } + + orderByProgressDescending(): this { + this.query.orderBy("progress", "desc"); + return this; + } + + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + // --- Aggregations --- count(): this { this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; return this; } countAs(retName: string): this { this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; return this; } @@ -87,7 +849,7 @@ export class TaskStatusRequest { } minDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("min", "displayOrder", retName); return this; } maxDisplayOrder(): this { @@ -95,7 +857,7 @@ export class TaskStatusRequest { } maxDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("max", "displayOrder", retName); return this; } sumDisplayOrder(): this { @@ -103,7 +865,7 @@ export class TaskStatusRequest { } sumDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("sum", "displayOrder", retName); return this; } avgDisplayOrder(): this { @@ -111,7 +873,7 @@ export class TaskStatusRequest { } avgDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("avg", "displayOrder", retName); return this; } standardDeviationDisplayOrder(): this { @@ -119,7 +881,7 @@ export class TaskStatusRequest { } standardDeviationDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("stddev", "displayOrder", retName); return this; } squareRootOfPopulationStandardDeviationDisplayOrder(): this { @@ -127,7 +889,7 @@ export class TaskStatusRequest { } squareRootOfPopulationStandardDeviationDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("stddev_pop", "displayOrder", retName); return this; } sampleVarianceDisplayOrder(): this { @@ -135,7 +897,7 @@ export class TaskStatusRequest { } sampleVarianceDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("var_samp", "displayOrder", retName); return this; } samplePopulationVarianceDisplayOrder(): this { @@ -143,7 +905,7 @@ export class TaskStatusRequest { } samplePopulationVarianceDisplayOrderAs(retName: string): this { - this.query.aggregate("", "display_order", retName); + this.query.aggregate("var_pop", "displayOrder", retName); return this; } minProgress(): this { @@ -151,7 +913,7 @@ export class TaskStatusRequest { } minProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("min", "progress", retName); return this; } maxProgress(): this { @@ -159,7 +921,7 @@ export class TaskStatusRequest { } maxProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("max", "progress", retName); return this; } sumProgress(): this { @@ -167,7 +929,7 @@ export class TaskStatusRequest { } sumProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("sum", "progress", retName); return this; } avgProgress(): this { @@ -175,7 +937,7 @@ export class TaskStatusRequest { } avgProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("avg", "progress", retName); return this; } standardDeviationProgress(): this { @@ -183,7 +945,7 @@ export class TaskStatusRequest { } standardDeviationProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("stddev", "progress", retName); return this; } squareRootOfPopulationStandardDeviationProgress(): this { @@ -191,7 +953,7 @@ export class TaskStatusRequest { } squareRootOfPopulationStandardDeviationProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("stddev_pop", "progress", retName); return this; } sampleVarianceProgress(): this { @@ -199,7 +961,7 @@ export class TaskStatusRequest { } sampleVarianceProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("var_samp", "progress", retName); return this; } samplePopulationVarianceProgress(): this { @@ -207,7 +969,7 @@ export class TaskStatusRequest { } samplePopulationVarianceProgressAs(retName: string): this { - this.query.aggregate("", "progress", retName); + this.query.aggregate("var_pop", "progress", retName); return this; } @@ -218,98 +980,215 @@ export class TaskStatusRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } - groupByName(): this { this.query.groupBy("name"); return this; } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } - groupByCode(): this { this.query.groupBy("code"); return this; } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } - groupByColor(): this { this.query.groupBy("color"); return this; } groupByColorAs(retName: string): this { - this.query.groupBy("color"); // In TS we don't alias group by yet natively + this.query.groupBy("color", retName); return this; } - groupByDisplayOrder(): this { - this.query.groupBy("display_order"); + this.query.groupBy("displayOrder"); return this; } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("display_order"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } - groupByProgress(): this { this.query.groupBy("progress"); return this; } groupByProgressAs(retName: string): this { - this.query.groupBy("progress"); // In TS we don't alias group by yet natively + this.query.groupBy("progress", retName); + return this; + } + groupByPlatform(): this { + this.query.groupBy("platform"); return this; } - + groupByPlatformAs(retName: string): this { + this.query.groupBy("platform", retName); + return this; + } groupByVersion(): this { this.query.groupBy("version"); return this; } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } - // --- Facets --- - facetByPlatformAs(facetName: string, request: any): this { - this.query.facetBy(facetName, "PLATFORM_PROPERTY", request); + facetByPlatformAs( + facetName: string, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "platform", request, includeAllFacets, + { kind: "facet", method: "facetByPlatformAs", relation: "platform", alias: facetName }); return this; } - async executeForList(ctx: any): Promise { - if (Object.keys(this.filters).length > 0) { - this.query.filter(this.filters); + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); } - const data = await ctx.client.executeQuery(this.query); - const result: any = { data }; + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TaskStatus + ? row + : TaskStatus.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); - if (this.query.facets && this.query.facets.length > 0) { - result.facets = {}; - for (const f of this.query.facets) { - if (Object.keys(this.filters).length > 0) { - f.query.filter(this.filters); // Inherit outer filters - } - result.facets[f.facetName] = await ctx.client.executeQuery(f.query); - } + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); } return result; } + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TaskStatus + ? row + : TaskStatus.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TaskStatus + ? entity + : TaskStatus.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTaskStatusRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TaskStatus.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/runtime-module.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..3671006e149286bc43a25f86a90a65742de2b39c --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/runtime-module.ts @@ -0,0 +1,140 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Platform": Object.freeze({ + entityType: "Platform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "founded": Object.freeze({ canonicalName: "founded", wireName: "founded", aliases: Object.freeze([] as string[]) }), + "user_email": Object.freeze({ canonicalName: "user_email", wireName: "userEmail", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "TaskStatus": Object.freeze({ + entityType: "TaskStatus", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "code": Object.freeze({ canonicalName: "code", wireName: "code", aliases: Object.freeze([] as string[]) }), + "color": Object.freeze({ canonicalName: "color", wireName: "color", aliases: Object.freeze([] as string[]) }), + "display_order": Object.freeze({ canonicalName: "display_order", wireName: "displayOrder", aliases: Object.freeze([] as string[]) }), + "progress": Object.freeze({ canonicalName: "progress", wireName: "progress", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "Task": Object.freeze({ + entityType: "Task", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "status": Object.freeze({ canonicalName: "status", wireName: "status", aliases: Object.freeze([] as string[]) }), + "platform": Object.freeze({ canonicalName: "platform", wireName: "platform", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "TaskExecutionLog": Object.freeze({ + entityType: "TaskExecutionLog", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "task": Object.freeze({ canonicalName: "task", wireName: "task", aliases: Object.freeze([] as string[]) }), + "action": Object.freeze({ canonicalName: "action", wireName: "action", aliases: Object.freeze([] as string[]) }), + "detail": Object.freeze({ canonicalName: "detail", wireName: "detail", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Platform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["founded"] == null) { + mutation.payload["founded"] = now; + context.recordFixEvidence({ entityType: "Platform", modelPath: "founded", source: "clock", sourceLabel: "graphClock" }); + } + + + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["founded"] === undefined) || mutation.payload["founded"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("founded") }); + + if ((mutation.action === "Create" && mutation.payload["user_email"] === undefined) || mutation.payload["user_email"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("user_email") }); + if (mutation.payload["user_email"] != null && [...String(mutation.payload["user_email"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("user_email"), inputValue: mutation.payload["user_email"], systemValue: 100 }); + + + }, + }, + "TaskStatus": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["code"] === undefined) || mutation.payload["code"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("code") }); + if (mutation.payload["code"] != null && [...String(mutation.payload["code"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("code"), inputValue: mutation.payload["code"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["color"] === undefined) || mutation.payload["color"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("color") }); + if (mutation.payload["color"] != null && [...String(mutation.payload["color"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("color"), inputValue: mutation.payload["color"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["display_order"] === undefined) || mutation.payload["display_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("display_order") }); + + if ((mutation.action === "Create" && mutation.payload["progress"] === undefined) || mutation.payload["progress"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("progress") }); + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + }, + }, + "Task": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && !([...String(mutation.payload["name"])].length >= 1)) results.push({ ruleId: "min_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 1 }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 200) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 200 }); + + if ((mutation.action === "Create" && mutation.payload["status"] === undefined) || mutation.payload["status"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("status") }); + + if ((mutation.action === "Create" && mutation.payload["platform"] === undefined) || mutation.payload["platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("platform") }); + + + }, + }, + "TaskExecutionLog": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["task"] === undefined) || mutation.payload["task"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("task") }); + + if ((mutation.action === "Create" && mutation.payload["action"] === undefined) || mutation.payload["action"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("action") }); + if (mutation.payload["action"] != null && [...String(mutation.payload["action"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("action"), inputValue: mutation.payload["action"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["detail"] === undefined) || mutation.payload["detail"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("detail") }); + if (mutation.payload["detail"] != null && [...String(mutation.payload["detail"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("detail"), inputValue: mutation.payload["detail"], systemValue: 100 }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Robot System", "founded": "createTime()", "userEmail": "admin@robots.example" } }, + constants: [ + { entity: "TaskStatus", id: "1001", values: { "name": "Planned", "code": "PLANNED", "color": "#94A3B8", "displayOrder": decimal("10"), "progress": decimal("0"), "platform": "1" } }, + { entity: "TaskStatus", id: "1002", values: { "name": "Ready", "code": "READY", "color": "#3B82F6", "displayOrder": decimal("20"), "progress": decimal("25"), "platform": "1" } }, + { entity: "TaskStatus", id: "1003", values: { "name": "Executing", "code": "EXECUTING", "color": "#F59E0B", "displayOrder": decimal("30"), "progress": decimal("50"), "platform": "1" } }, + { entity: "TaskStatus", id: "1004", values: { "name": "Verified", "code": "VERIFIED", "color": "#16A34A", "displayOrder": decimal("40"), "progress": decimal("100"), "platform": "1" } } + ] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sql.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb9ff48c1cb2f0fbe0bac20ab4619affd6003d83 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sql.ts @@ -0,0 +1,28 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Platform": { + table: "platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "founded": { columnName: "founded", modelName: "founded", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "userEmail": { columnName: "user_email", modelName: "user_email", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"taskStatusList": { targetEntity: "TaskStatus", localKey: "id", foreignKey: "platform", many: true }, "taskList": { targetEntity: "Task", localKey: "id", foreignKey: "platform", many: true }} +}, +"TaskStatus": { + table: "task_status_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "progress": { columnName: "progress", modelName: "progress", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "taskList": { targetEntity: "Task", localKey: "id", foreignKey: "status", many: true }} +}, +"Task": { + table: "task_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"status": { targetEntity: "TaskStatus", localKey: "status", foreignKey: "id", many: false }, "platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "taskExecutionLogList": { targetEntity: "TaskExecutionLog", localKey: "id", foreignKey: "task", many: true }} +}, +"TaskExecutionLog": { + table: "task_execution_log_data", + auditMaskFields: ["detail"], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "task": { columnName: "task", modelName: "task", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "action": { columnName: "action", modelName: "action", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "detail": { columnName: "detail", modelName: "detail", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"task": { targetEntity: "Task", localKey: "task", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-ts.ts b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/teaql-i18n.json b/source/teaql-ts/examples/task-board/ts-lib-core/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..993843e7f88727de84f6580642ba93e3f93dbd09 --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/teaql-i18n.json @@ -0,0 +1,123 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.platform.name": "Name", + "entity.task": "Task", + "property.taskStatus.progress": "Progress", + "entity.taskStatus": "Task Status", + "property.taskStatus.name": "Name", + "property.task.name": "Name", + "property.taskExecutionLog.action": "Action", + "entity.taskExecutionLog": "Task Execution Log", + "property.platform.founded": "Founded", + "property.taskStatus.color": "Color", + "property.taskExecutionLog.id": "Id", + "property.taskExecutionLog.version": "Version", + "property.taskStatus.id": "Id", + "entity.platform": "Platform", + "property.platform.id": "Id", + "property.taskStatus.code": "Code", + "property.task.id": "Id", + "property.taskStatus.displayOrder": "Display Order", + "property.taskExecutionLog.task": "Task", + "property.taskExecutionLog.detail": "Detail", + "property.platform.userEmail": "User Email", + "property.task.platform": "Platform", + "property.task.status": "Status", + "property.taskStatus.version": "Version", + "property.task.version": "Version", + "property.taskStatus.platform": "Platform", + "property.platform.version": "Version" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/ts-lib-core/tsconfig.json b/source/teaql-ts/examples/task-board/ts-lib-core/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/task-board/ts-lib-core/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/task-board/tsconfig.json b/source/teaql-ts/examples/task-board/tsconfig.json index 19471f1c3e4afdbf43fbefb7c212ccb6be72fe72..ac580890228e436bca5782ef1eb1ce50b923895c 100644 --- a/source/teaql-ts/examples/task-board/tsconfig.json +++ b/source/teaql-ts/examples/task-board/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "target": "ES2020", + "target": "ES2022", "module": "commonjs", "moduleResolution": "node", "resolveJsonModule": true, @@ -8,5 +8,5 @@ "strict": true, "skipLibCheck": true }, - "include": ["app-dynamic/src/**/*.ts", "app-native/src/**/*.ts", "ts-lib-core/src/**/*.ts"] + "include": ["verify.ts", "app-dynamic/src/**/*.ts", "app-native/src/**/*.ts", "ts-lib-core/src/**/*.ts"] } diff --git a/source/teaql-ts/examples/task-board/verify-local.cjs b/source/teaql-ts/examples/task-board/verify-local.cjs new file mode 100644 index 0000000000000000000000000000000000000000..294911dd3b6a9e1b831a2f8930d9945d66c2e7be --- /dev/null +++ b/source/teaql-ts/examples/task-board/verify-local.cjs @@ -0,0 +1,46 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),assert=require('node:assert/strict'),crypto=require('node:crypto'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const sha=b=>crypto.createHash('sha256').update(b).digest('hex'),example=__dirname,repo=path.resolve(example,'../..'); +function fixture(){ + const manifest=JSON.parse(fs.readFileSync(path.join(example,'fixture-manifest.json'))); + assert.equal(manifest.schema,'teaql.typescript-task-board-fixture/v1');assert.equal(manifest.evaluationErrors,0); + assert.equal(sha(fs.readFileSync(path.join(example,'model.xml'))),manifest.modelSha256); + const actual=[];function visit(dir,prefix=''){for(const e of fs.readdirSync(dir,{withFileTypes:true})){assert(!e.isSymbolicLink());const n=path.join(prefix,e.name),f=path.join(dir,e.name);if(e.isDirectory())visit(f,n);else{assert(e.isFile());actual.push(n);}}} + visit(path.join(example,'ts-lib-core'));assert.deepEqual(actual.sort(),Object.keys(manifest.files).sort()); + for(const[n,h]of Object.entries(manifest.files))assert.equal(sha(fs.readFileSync(path.join(example,'ts-lib-core',n))),h); + for(const[n,h]of Object.entries(manifest.assist))assert.equal(sha(fs.readFileSync(path.join(example,'assist',n))),h); + return manifest; +} +async function main(){ + const requested=process.env.TEAQL_TASK_BOARD_EVIDENCE_DIR,output=requested?path.resolve(requested):fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-taskboard-evidence-')); + if(requested){assert(path.isAbsolute(requested)&&!fs.existsSync(output));fs.mkdirSync(output,{recursive:true});} + const r={schema:'teaql.typescript-task-board-example/v1',passed:false,rounds:[],sameDatabase:true,manualSeedSQL:false,generatedImplementationHandEdited:false}; + const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-taskboard-build-'));let runner; + try{ + const model=fixture();r.modelSha256=model.modelSha256;r.generatorCommit=model.generatorCommit;r.generatedFiles=Object.keys(model.files).length; + r.runtimeOrigin=fs.realpathSync(require.resolve('teaql-ts')); + r.expectedRuntime=path.resolve(process.env.TEAQL_TASK_BOARD_EXPECTED_RUNTIME||path.join(repo,'dist/index.js')); + assert.equal(r.runtimeOrigin,r.expectedRuntime,'runtime origin must be explicit and exact'); + runner=createOwnedRunner(); + async function run(name,command,extra={}){const f=path.join(output,name+'.log'),fd=fs.openSync(f,'wx');let q;try{q=await runner.run(command,{cwd:example,env:{...process.env,...extra,TMPDIR:scratch},timeout:120000,stdio:['ignore',fd,fd]});}finally{fs.closeSync(fd);}const text=fs.readFileSync(f,'utf8');assert(!q.error&&!q.signal&&q.status===0&&runner.safeToClean,name+': '+text.slice(-5000));return{text,exitCode:q.status,signal:q.signal,logSha256:sha(Buffer.from(text))};} + const compile=await run('compile',[process.execPath,require.resolve('typescript/bin/tsc'),'--noEmit','--pretty','false','-p','tsconfig.json']);r.compile={...compile,text:undefined}; + const database=path.join(output,'task-board.sqlite'); + for(const round of[1,2]){ + assert.equal(fs.existsSync(database),round===2); + const result=await run('round-'+round,[process.execPath,require.resolve('ts-node/dist/bin.js'),'verify.ts'],{TEAQL_TASK_BOARD_DB:database,TEAQL_TASK_BOARD_ROUND:String(round)}); + const frames=result.text.split(/\r?\n/).filter(n=>n.startsWith('TYPESCRIPT_TASK_BOARD=')).map(n=>JSON.parse(n.slice('TYPESCRIPT_TASK_BOARD='.length)));assert.equal(frames.length,1); + const v=frames[0];assert(v.passed&&v.round===round&&v.typedDynamicMatch&&v.checkerRejected&&v.missingAuditRejected&&v.notLoadedRejected&&v.parserInjectionRejected); + assert.equal(v.seeded,round===1?2:0);assert.equal(v.renamed,round===1?2:0);assert.equal(v.runtimeOrigin,r.runtimeOrigin); + r.rounds.push({round,exitCode:result.exitCode,signal:result.signal,logSha256:result.logSha256,result:v});assert.deepEqual(fixture(),model); + } + assert.deepEqual(r.rounds[0].result.taskIds,r.rounds[1].result.taskIds);assert.deepEqual(r.rounds[0].result.versions,r.rounds[1].result.versions); + r.databaseSha256=sha(fs.readFileSync(database));r.passed=true; + }catch(error){r.error=error.stack;process.exitCode=1;} + finally{ + r.cleanup={scratchRemoved:false,sharedCachesDeleted:false,databasesDeleted:false}; + if(!runner||runner.safeToClean){r.cleanup.disposedOwnedBytes=ownedBytes(scratch);fs.rmSync(scratch,{recursive:true});r.cleanup.scratchRemoved=true;}else{r.cleanup.unsafeRetention=scratch;r.passed=false;process.exitCode=1;} + runner?.dispose();fs.writeFileSync(path.join(output,'report.json'),JSON.stringify(r,null,2)+'\n',{flag:'wx'});console.log(JSON.stringify({output,passed:r.passed,error:r.error})); + } +} +module.exports={fixture};if(require.main===module)main().catch(e=>{console.error(e.stack);process.exitCode=1;}); diff --git a/source/teaql-ts/examples/task-board/verify.ts b/source/teaql-ts/examples/task-board/verify.ts new file mode 100644 index 0000000000000000000000000000000000000000..24233f758bc73717297847cd1248b9db535510d0 --- /dev/null +++ b/source/teaql-ts/examples/task-board/verify.ts @@ -0,0 +1,105 @@ +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { CheckException, QueryParser, RequestIntentError, TeaQLNotLoadedError, UserContext } from 'teaql-ts'; +import { Q } from './ts-lib-core/src/generated/Q'; +import { E } from './ts-lib-core/src/generated/E'; +import { SQLiteTeaQLClient } from './ts-lib-core/src/teaql-node-sqlite'; +import { GENERATED_RUNTIME_MODULE } from './ts-lib-core/src/runtime-module'; +import { runNativeExamples } from './app-native/src/main'; +import { runDynamicExamples } from './app-dynamic/src/main'; + +async function main() { + const database = process.env.TEAQL_TASK_BOARD_DB; + assert(database, 'Run npm run verify or set TEAQL_TASK_BOARD_DB to a retained SQLite path.'); + const round = Number(process.env.TEAQL_TASK_BOARD_ROUND ?? '1'); assert([1, 2].includes(round)); + mkdirSync(dirname(resolve(database)), {recursive: true}); + const client = new SQLiteTeaQLClient(resolve(database)).setDiagnosticSQLLogSink(undefined); + client.install(GENERATED_RUNTIME_MODULE); + const context = new UserContext().insertResource('dataService', client); + try { + await context.ensureSchema(); await context.ensureSchema(); + const roots = await Q.platforms().limit(2).comment('read seeded root') + .purpose('verify repeated bootstrap').executeForList(context); + const statuses = await Q.taskStatuses().orderByIdAscending().limit(10).comment('read seeded task statuses') + .purpose('verify fixed constant identities').executeForList(context); + assert.deepEqual(roots.map(r => r.id), ['1']); + assert.deepEqual(statuses.map(r => [r.id, E.taskStatus(r).code().eval()]), + [['1001', 'PLANNED'], ['1002', 'READY'], ['1003', 'EXECUTING'], ['1004', 'VERIFIED']]); + + const invalid = (await Q.tasks().comment('prepare invalid task').purpose('verify Checker').newEntity(context)) + .updatePlatform('1').updateStatusToPlanned().updateName(''); + const beforeInvalid = client.sqlTrace.length; + await assert.rejects(async () => invalid.auditAs('reject blank task name').save(context), CheckException); + assert.equal(client.sqlTrace.length, beforeInvalid, 'Checker rejection must precede business SQL'); + const missingAudit = (await Q.tasks().comment('prepare unaudited task').purpose('verify audit gate').newEntity(context)) + .updatePlatform('1').updateStatusToPlanned().updateName('rejected audit fixture'); + await assert.rejects(async () => missingAudit.auditAs('').save(context), RequestIntentError); + + let seeded = 0, renamed = 0; + for (const channel of ['native', 'dynamic']) { + const initialName = 'bug-' + channel, finalName = initialName + ' verified'; + const existing = await Q.tasks().withNameIn(initialName, finalName).limit(2) + .comment('find retained task fixture').purpose('avoid duplicate sample data').executeForList(context); + assert(existing.length <= 1); + let entity = existing[0]; + if (!entity) { + entity = (await Q.tasks().comment('initialize task graph').purpose('demonstrate generated creation').newEntity(context)) + .updatePlatform('1').updateStatusToPlanned().updateName(initialName); + assert(entity.id && BigInt(entity.id) > 0n, 'creation must assign identity before saving'); + const log = (await Q.taskExecutionLogs().comment('initialize execution history') + .purpose('demonstrate graph save').newEntity(context)) + .updateTask(entity.id).updateAction('created').updateDetail('PRIVATE-TASK-DETAIL'); + entity.taskExecutionLogList().push(log); + await entity.auditAs('create task and its execution history').save(context); seeded++; + } + // Save a complete model, never a reconstructed DTO or reduced projection. + if (E.task(entity).name().eval() !== finalName) { + entity.updateName(finalName).updateStatusToVerified(); + await entity.auditAs('verify task completion').save(context); renamed++; + } + } + assert.equal(seeded, round === 1 ? 2 : 0); assert.equal(renamed, round === 1 ? 2 : 0); + const {tasks, facets} = await runNativeExamples(context); + const dynamic = await runDynamicExamples(context); + assert.equal(tasks.length, 2); assert.equal(dynamic.length, 2); + assert.deepEqual(tasks.map(r => r.id), dynamic.map(r => r.id)); + for (const task of tasks) { + const name = E.task(task).name().eval(); assert(typeof name === 'string' && name.endsWith(' verified')); + const status = E.task(task).status().eval(); assert(status); + assert.equal(E.taskStatus(status).code().eval(), 'VERIFIED'); + assert.equal(E.task(task).statusId().eval(), '1004'); + assert.equal(E.task(task).taskExecutionLogList().size().eval(), 1); + assert.equal(E.task(task).taskExecutionLogList().first().action().eval(), 'created'); + assert.equal(E.task(task).taskExecutionLogList().first().taskId().eval(), task.id); + } + const counters = facets.facets.statusFacet; + assert(counters, 'the requested Facet is present'); + assert.deepEqual(counters.map(r => [String(r.id), r.taskCount]), [['1001', 0], ['1002', 0], ['1003', 0], ['1004', 2]]); + const sparse = await Q.tasksWithMinimalFields().selectName().limit(1) + .comment('load name-only task projection').purpose('verify E loaded-state safety').executeForList(context); + assert.equal(sparse.length, 1); assert.throws(() => E.task(sparse[0]).status().eval(), TeaQLNotLoadedError); + assert.throws(() => E.task(sparse[0]).status().code().orElse('fallback'), TeaQLNotLoadedError); + assert.throws(() => QueryParser.parse('globalThis.process.exit()', Q)); + await assert.rejects(async () => Q.tasks().limit(1).comment('').purpose('verify query intent').executeForList(context), RequestIntentError); + + const transient = (await Q.tasks().comment('initialize deletion fixture').purpose('demonstrate staged deletion').newEntity(context)) + .updatePlatform('1').updateStatusToReady().updateName('temporary-task-' + round); + await transient.auditAs('create deletion fixture').save(context); + const id = transient.id!; + await transient.markForDeletion().auditAs('remove temporary task').save(context); + const visible = await Q.tasks().withIdIs(id).limit(1).comment('check normal-query hiding') + .purpose('verify staged deletion').executeForList(context); assert.equal(visible.length, 0); + const deleted = await Q.tasks().deletedRowsOnly().withIdIs(id).limit(1).comment('read retained deleted task') + .purpose('verify negative optimistic version').executeForList(context); + assert.equal(deleted.length, 1); assert(BigInt(deleted[0].version!) < 0n); + console.log('TYPESCRIPT_TASK_BOARD=' + JSON.stringify({passed: true, round, seeded, renamed, + rootIds: roots.map(r => r.id), constantIds: statuses.map(r => r.id), taskIds: tasks.map(r => r.id), + versions: tasks.map(r => r.version), typedDynamicMatch: true, checkerRejected: true, + missingAuditRejected: true, notLoadedRejected: true, parserInjectionRejected: true, + deletedId: id, deletedVersion: deleted[0].version, actualSQL: client.sqlTrace.length, + runtimeOrigin: require.resolve('teaql-ts')})); + console.log('PASS TypeScript generated Task Board: bootstrap, typed/dynamic Q, loaded E, Checker, audited graph, update, staged delete'); + } finally { await client.close(); } +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/trace-chain/aggregate-membership.ts b/source/teaql-ts/examples/trace-chain/aggregate-membership.ts index e5a5a6a04e075c094bd29db00312316141e61598..decf7701e21a7dde4af3861422fcee6b5657d79c 100644 --- a/source/teaql-ts/examples/trace-chain/aggregate-membership.ts +++ b/source/teaql-ts/examples/trace-chain/aggregate-membership.ts @@ -64,12 +64,12 @@ async function main() { const group=randomUUID(); try { await context.ensureSchema();await context.ensureSchema(); - const order=Q.customerOrders().comment('initialize membership graph').purpose('verify generated aggregate') - .newEntity(context).updatePlatform('1').updateOrderNumber(group).updateDescription(group); - for(const name of [secret,'ordinary member'])order.orderItemList().push(Q.orderItems() - .comment('initialize membership item').purpose('verify two members').newEntity(context).updateName(name)); - order.paymentList().push(Q.payments().comment('initialize membership payment').purpose('verify nested owner') - .newEntity(context).updateReferenceCode(group)); + const order=(await Q.customerOrders().comment('initialize membership graph').purpose('verify generated aggregate') + .newEntity(context)).updatePlatform('1').updateOrderNumber(group).updateDescription(group); + for(const name of [secret,'ordinary member'])order.orderItemList().push((await Q.orderItems() + .comment('initialize membership item').purpose('verify two members').newEntity(context)).updateName(name)); + order.paymentList().push((await Q.payments().comment('initialize membership payment').purpose('verify nested owner') + .newEntity(context)).updateReferenceCode(group)); await order.auditAs('seed generated aggregate membership').save(context); const id=order.id!; for(const nested of [false,true])for(const mode of ['list','stream-full','stream-tail']) diff --git a/source/teaql-ts/examples/trace-chain/app.ts b/source/teaql-ts/examples/trace-chain/app.ts index c45339d8cb6347496a7b3e28d83385877114ba15..7437cccacabcf165d840f413bd666caf4f64f3df 100644 --- a/source/teaql-ts/examples/trace-chain/app.ts +++ b/source/teaql-ts/examples/trace-chain/app.ts @@ -1,3 +1,4 @@ +import {internalId} from 'teaql-ts'; import assert from 'node:assert/strict'; import { randomUUID, createHash } from 'node:crypto'; import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; @@ -35,7 +36,7 @@ function checkIdentities(want: readonly GraphIdentity[], actual: readonly GraphI assert.equal(new Set(observed).size, 6, `${boundary}: duplicate identity`); assert.deepEqual(observed.sort(), expected.sort(), `${boundary}: missing or unknown typed identity`); } -function graphIdentities(graph: ReturnType): GraphIdentity[] { +function graphIdentities(graph: Awaited>): GraphIdentity[] { const identity = (entity: string, id: unknown): GraphIdentity => { assert(typeof id === 'string', 'saved generated entity must have an assigned ID'); return { entity, id }; @@ -119,18 +120,18 @@ class Client extends AbstractSQLTeaQLClient { } } -function construct(context: UserContext, suffix: string) { - const order = Q.customerOrders().comment('initialize order').purpose('verify generated graph').newEntity(context) +async function construct(context: UserContext, suffix: string) { + const order = (await Q.customerOrders().comment('initialize order').purpose('verify generated graph').newEntity(context)) .updatePlatform('1').updateOrderNumber(`${nonce}-${suffix}`).updateDescription(`fixture-description-${suffix}`); - const item = Q.orderItems().comment('initialize available item').purpose('verify generated graph').newEntity(context) + const item = (await Q.orderItems().comment('initialize available item').purpose('verify generated graph').newEntity(context)) .updateName(`fixture-available-${suffix}`); - const removed = Q.orderItems().comment('initialize second item').purpose('verify generated graph').newEntity(context) + const removed = (await Q.orderItems().comment('initialize second item').purpose('verify generated graph').newEntity(context)) .updateName(`fixture-unavailable-${suffix}`); - const payment = Q.payments().comment('initialize payment').purpose('verify generated graph').newEntity(context) + const payment = (await Q.payments().comment('initialize payment').purpose('verify generated graph').newEntity(context)) .updateReferenceCode(`fixture-payment-${suffix}`).auditAs('authorize payment'); - const attempt = Q.paymentAttempts().comment('initialize payment attempt').purpose('verify generated graph').newEntity(context) + const attempt = (await Q.paymentAttempts().comment('initialize payment attempt').purpose('verify generated graph').newEntity(context)) .updateReferenceCode(`fixture-attempt-${suffix}`); - const shipment = Q.shipments().comment('initialize shipment').purpose('verify generated graph').newEntity(context) + const shipment = (await Q.shipments().comment('initialize shipment').purpose('verify generated graph').newEntity(context)) .updateReferenceCode(`fixture-shipment-${suffix}`).auditAs('dispatch shipment'); order.orderItemList().push(item, removed); order.paymentList().push(payment); @@ -203,7 +204,7 @@ function checkPrivateGraph(client: Client, driver: Driver, entries: readonly SQL safeReason, logging, phase, fail, precommitChecks, commands, sql: entries, audit: audits })); console.log('PASS TypeScript complete private lineage: raw commands, safe SQL/readback and committed audit'); } -function expected(graph: ReturnType, rootReason: string, deleted = false) { +function expected(graph: Awaited>, rootReason: string, deleted = false) { const root = ['auditReason', 'CustomerOrder', graph.order.id, rootReason]; return [[root], [root], deleted ? [root, ['auditReason', 'OrderItem', graph.removed.id, 'remove unavailable item']] : [root], [root, ['auditReason', 'Payment', graph.payment.id, 'authorize payment']], @@ -266,7 +267,7 @@ async function main() { checks.push('generated bootstrap twice'); client.commands.length = 0; audits.length = 0; client.setRuntimeTelemetrySink(sql); - const graph = construct(context, 'normative'); + const graph = (await construct(context, 'normative')); await graph.order.auditAs('submit order').save(context); assert.equal(client.commands.length, 6); assert.deepEqual(client.commands.map(command => plain(command.lineage)), expected(graph, 'submit order')); @@ -301,7 +302,7 @@ async function main() { checks.push('generated normative update and child markForDeletion then root save'); sql.enableAll(); - const attempts = await Q.paymentAttempts().withIdIs(graph.attempt.id) + const attempts = await Q.paymentAttempts().withIdIs(internalId(graph.attempt.id)) .selectPaymentWith(Q.payments().limit(1).selectCustomerOrderWith( Q.customerOrders().limit(1).selectPlatformWith(Q.platforms().limit(1)))) .limit(1).comment('load generated three-level graph').purpose('verify query lineage').executeForList(context); @@ -330,7 +331,7 @@ async function main() { checks.push('generated bounded Q and E across three relation levels'); audits.length = 0; client.commands.length = 0; sql.enableAll(); - const first = construct(context, 'concurrent-first'), second = construct(context, 'concurrent-second'); + const first = (await construct(context, 'concurrent-first')), second = (await construct(context, 'concurrent-second')); await Promise.all([first.order.auditAs('first independent operation').save(context), second.order.auditAs('second independent operation').save(context)]); for (const [graph, reason] of [[first, 'first independent operation'], [second, 'second independent operation']] as const) { @@ -343,7 +344,7 @@ async function main() { checks.push('generated overlapping graph saves on the same Context'); for (const readback of [false, true]) { - const failed = construct(context, `failed-${readback}`); + const failed = (await construct(context, `failed-${readback}`)); client.commands.length = 0; audits.length = 0; sql.enableAll(); driver.failureTable = 'payment_data'; driver.readbackFailure = readback; await assert.rejects(failed.order.auditAs('submit failing order').save(context), /injected trace-chain provider failure/); @@ -364,10 +365,10 @@ async function main() { checks.push('generated provider and readback failures retain trace and produce no committed audit'); for (const logging of [false, true]) { - const privacy = construct(context, `loaded-privacy-${logging}`); + const privacy = (await construct(context, `loaded-privacy-${logging}`)); privacy.item.updateName('PRIVATEOLDITEM'); await privacy.order.auditAs('seed loaded privacy graph').save(context); - const loaded = (await Q.customerOrders().withIdIs(privacy.order.id) + const loaded = (await Q.customerOrders().withIdIs(internalId(privacy.order.id)) .selectOrderItemListWith(Q.orderItems().limit(2)).limit(1) .comment('load privacy graph').purpose('verify authoritative scalar snapshot').executeForList(context))[0]; const item = loaded.orderItemList().find(row => row.id === privacy.item.id)!; @@ -401,7 +402,7 @@ async function main() { [oldValue, newValue], newValue, fail, logging, fail ? 'rollback' : oldValue === 'PRIVATEOLDITEM' ? 'update' : 'retry', precommitChecks); driver.beforeCommit = undefined; driver.failureTable = undefined; - const persisted = (await Q.orderItems().withIdIs(item.id).limit(1) + const persisted = (await Q.orderItems().withIdIs(internalId(item.id)).limit(1) .comment('verify item privacy mutation').purpose('check committed or rolled-back value').executeForList(context))[0]; assert.equal(E.orderItem(persisted).name().eval(), fail ? oldValue : newValue); } @@ -417,7 +418,7 @@ async function main() { checkPrivateGraph(client, driver, sql.snapshot(), audits, loaded.id!, item.id!, reason, ['PRIVATERETRYITEM'], undefined, false, logging, 'delete', precommitChecks); driver.beforeCommit = undefined; - const missing = await Q.orderItems().withIdIs(item.id).limit(1) + const missing = await Q.orderItems().withIdIs(internalId(item.id)).limit(1) .comment('verify loaded private child deletion').purpose('confirm soft-deleted row is hidden').executeForList(context); assert.equal(missing.length, 0); // No unrelated request may inherit the preceding graph's privacy snapshot. @@ -428,8 +429,11 @@ async function main() { checks.push('generated loaded old-value privacy, committed refresh, rollback retry and independent request isolation'); } finally { await client.close(); } assert.equal(manifest('lib'), generatedBefore, 'application execution changed generated source'); - mkdirSync('evidence', { recursive: true }); - writeFileSync('evidence/generated-library-manifest.sha256', generatedBefore); + const evidenceDirectory = process.env.TEAQL_EXAMPLES_EVIDENCE_DIR + ? resolve(process.env.TEAQL_EXAMPLES_EVIDENCE_DIR, 'trace-chain') + : resolve('.local/evidence'); + mkdirSync(evidenceDirectory, { recursive: true }); + writeFileSync(join(evidenceDirectory, 'generated-library-manifest.sha256'), generatedBefore); console.log(JSON.stringify({ database, nonce, checks, generatedSourceUnchanged: true })); console.log(`PASS TypeScript generated trace-chain example: ${checks.length} checks`); } diff --git a/source/teaql-ts/examples/trace-chain/checker-overlap.ts b/source/teaql-ts/examples/trace-chain/checker-overlap.ts index eb4909fa93e88ee2d654805346a84c4c18b46c30..8209ffd339c855803c0940f162da2225bbd02249 100644 --- a/source/teaql-ts/examples/trace-chain/checker-overlap.ts +++ b/source/teaql-ts/examples/trace-chain/checker-overlap.ts @@ -62,14 +62,15 @@ class Client extends AbstractSQLTeaQLClient { } return rows; } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, + prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { this.activeSaves++; this.maxSaves = Math.max(this.maxSaves, this.activeSaves); try { return await super.executeGraphSave(intent, async graph => { this.activeCallbacks++; this.maxCallbacks = Math.max(this.maxCallbacks, this.activeCallbacks); assert(this.observedDriver.current); this.observedDriver.current.reason = intent.comment; try { return await work(graph); } finally { this.activeCallbacks--; } - }); + }, prepare, admit); } finally { this.activeSaves--; } } preflightMutation(input: any): any { @@ -110,10 +111,10 @@ async function main() { client.maxSaves = 0; client.maxCallbacks = 0; sql.enableAll(); }; const create = async (suffix: string) => { - const root = Q.customerOrders().comment('initialize Checker overlap fixture').purpose('verify generated validation') - .newEntity(context).updatePlatform('1').updateOrderNumber(`${nonce}-${suffix}`).updateDescription(`before-${suffix}`); - root.orderItemList().push(Q.orderItems().comment('initialize Checker item').purpose('verify generated validation') - .newEntity(context).updateName(`${nonce}-${suffix}-item`)); + const root = (await Q.customerOrders().comment('initialize Checker overlap fixture').purpose('verify generated validation') + .newEntity(context)).updatePlatform('1').updateOrderNumber(`${nonce}-${suffix}`).updateDescription(`before-${suffix}`); + root.orderItemList().push((await Q.orderItems().comment('initialize Checker item').purpose('verify generated validation') + .newEntity(context)).updateName(`${nonce}-${suffix}-item`)); await root.auditAs('seed Checker overlap fixture').save(context); return root; }; @@ -142,8 +143,8 @@ async function main() { valid.updateDescription(`accepted-${nonce}-${suffix}`); valid.orderItemList()[0].updateName(`accepted-child-${nonce}-${suffix}`).auditAs('accepted child responsibility'); invalid.updateDescription(`must-remain-pending-${nonce}-${suffix}`); - const missingName = Q.orderItems().comment('initialize invalid child').purpose('verify real required-field Checker') - .newEntity(context).auditAs('rejected child responsibility'); + const missingName = (await Q.orderItems().comment('initialize invalid child').purpose('verify real required-field Checker') + .newEntity(context)).auditAs('rejected child responsibility'); invalid.orderItemList().push(missingName); reset(); const jobs = invalidFirst @@ -170,9 +171,9 @@ async function main() { assert.deepEqual(client.commands.map(c => plain(c.lineage)), expected); assert.deepEqual(audit.map(event => plain(event.mutationLineage)), expected); assert.deepEqual(client.physical.map(entry => plain(entry.mutationLineage)), expected.flatMap(chain => [chain, chain])); - assert.equal(driver.transactions.length, 2); - const failed = driver.transactions.find(t => t.reason === invalidReason)!; - assert.equal(failed.outcome, 'rollback'); assert.deepEqual(failed.sql, [], 'no ID allocation or business SQL before Checker rejection'); + assert.equal(driver.transactions.length, 1, 'Checker rejection happens before a provider transaction'); + assert.equal(driver.transactions.find(t => t.reason === invalidReason), undefined, + 'no transaction, ID allocation or business SQL before Checker rejection'); assert.equal(driver.transactions.find(t => t.reason === validReason)!.outcome, 'commit'); assert.equal(ledger(platformA).snapshot().length, 0); assert.equal(ledger(platformB).snapshot().length, 0); assert.equal(E.platform(platformA).version().eval(), platformVersion); diff --git a/source/teaql-ts/examples/trace-chain/lib/current-generator-fixture.json b/source/teaql-ts/examples/trace-chain/lib/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..3b76e20e402e594a484943202f0294dafcd1e5fd --- /dev/null +++ b/source/teaql-ts/examples/trace-chain/lib/current-generator-fixture.json @@ -0,0 +1,38 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "95502038a66686580e7399dc4252df51f95cc0dc10a54657f5779dc2a5dd1e76", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "src/generated/Q.ts": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "src/generated/requests/PlatformRequest.ts": "bf715386dbfab4a40c2d88395b3064b7d251aae937b84392ea2f560a76d1554f", + "src/generated/requests/CustomerOrderRequest.ts": "e64907788e78c69e08ad6b6b6ae26fb7b915485d515ed4aa7feb101ef9907a9a", + "src/generated/requests/OrderItemRequest.ts": "93fb78c68c36862b7d80c0a18be71c8583d90db11d5fc2b736ce56a319a678da", + "src/generated/requests/PaymentRequest.ts": "cc7f103a76a67ea8807f32b581ba99e8bc0eb6d239309c3babcdacf9a409261c", + "src/generated/requests/PaymentAttemptRequest.ts": "273917f4319a4e9aec6f1f73be9acef7f78f9f9a19cac3da58cfff45df7ea2f0", + "src/generated/requests/ShipmentRequest.ts": "db8469db7de78791ca038f9de5b611c1b85b2abcfafdfb32303353b54b3133b3", + "src/generated/E.ts": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "src/teaql-schemas.ts": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "src/runtime-module.ts": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "src/generated-bootstrap.ts": "f84c9d8c86c682447690a2b241585b31955b4d3148dbc6cb8bf9e377f1d32ac0", + "src/generated/models/Platform.ts": "b04b4b8b8ea31d6ccac778a4ae9a20cc9e0708184ffcb8fee4f4c86b7e2b0d92", + "src/generated/models/CustomerOrder.ts": "81d7d74139cae387dced64323c62eeb13fbe14dd180a5b5d5ca62559a734c22b", + "src/generated/models/OrderItem.ts": "070bfbe18ef19145e123d79b3c2164783b087175d1e05a4c2186f22d7405b86c", + "src/generated/models/Payment.ts": "e46099d4829efc8e5fcadbe657f325d445bc3c68e06c31d5ba5b3f4ff1581084", + "src/generated/models/PaymentAttempt.ts": "65ad7d3f61b28b304c019868c346b12b7f83bec9d130a8395a00ca9d53eb3e9c", + "src/generated/models/Shipment.ts": "060aaf762614b09d596b61f9d78e3813fcd0b4c9e59935d6f4b3966ada8df474" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "fadd17d8cc33e517522a9a68218b8ad0ea948331285f22dc5ca6beb7eae1e0ca", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/E.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/E.ts index aa0cb8c865ed5c266c3cd868299a5fa32867e5a8..1afe18b16812917e7c78f3f7b1460e9b0f8920e4 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/E.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/E.ts @@ -1,44 +1,19 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; import { Platform } from './models/Platform'; import { CustomerOrder } from './models/CustomerOrder'; import { OrderItem } from './models/OrderItem'; import { Payment } from './models/Payment'; import { PaymentAttempt } from './models/PaymentAttempt'; import { Shipment } from './models/Shipment'; - -export class TeaQLNotLoadedError extends Error { - readonly details: Record; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -49,18 +24,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -69,62 +52,62 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerOrderList(): CustomerOrderListExpression { - const path = expressionPath(this.path, 'customerOrderList'); + const path = this.path.member('customer_order_list', 'customerOrderList'); if (this.notLoaded) { - return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded); + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return CustomerOrderListExpression.missing(this.root, path); if (!this.value.isLoaded('customerOrderList')) { return new CustomerOrderListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'customerOrderList')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); } return new CustomerOrderListExpression( this.value.customerOrderList(), this.root, path, @@ -136,70 +119,70 @@ export class CustomerOrderExpression { constructor( private readonly value: CustomerOrder | null | undefined, private readonly root = 'CustomerOrder(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.customerOrder()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): CustomerOrder | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } orderNumber(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('order_number', 'orderNumber'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'orderNumber'); if (!this.value.isLoaded('orderNumber')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'orderNumber'), + new TeaQLNotLoadedError(path.markMissing(), 'order_number'), ); } return new ValueExpression(this.value.orderNumber); } description(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('description', 'description'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'description'); if (!this.value.isLoaded('description')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'description'), + new TeaQLNotLoadedError(path.markMissing(), 'description'), ); } return new ValueExpression(this.value.description); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -210,33 +193,35 @@ export class CustomerOrderExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } orderItemList(): OrderItemListExpression { - const path = expressionPath(this.path, 'orderItemList'); + const path = this.path.member('order_item_list', 'orderItemList'); if (this.notLoaded) { - return new OrderItemListExpression([], this.root, path, false, this.notLoaded); + return new OrderItemListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return OrderItemListExpression.missing(this.root, path); if (!this.value.isLoaded('orderItemList')) { return new OrderItemListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'orderItemList')); + new TeaQLNotLoadedError(path.markMissing(), 'order_item_list')); } return new OrderItemListExpression( this.value.orderItemList(), this.root, path, @@ -244,14 +229,14 @@ export class CustomerOrderExpression { } paymentList(): PaymentListExpression { - const path = expressionPath(this.path, 'paymentList'); + const path = this.path.member('payment_list', 'paymentList'); if (this.notLoaded) { - return new PaymentListExpression([], this.root, path, false, this.notLoaded); + return new PaymentListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return PaymentListExpression.missing(this.root, path); if (!this.value.isLoaded('paymentList')) { return new PaymentListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'paymentList')); + new TeaQLNotLoadedError(path.markMissing(), 'payment_list')); } return new PaymentListExpression( this.value.paymentList(), this.root, path, @@ -259,14 +244,14 @@ export class CustomerOrderExpression { } shipmentList(): ShipmentListExpression { - const path = expressionPath(this.path, 'shipmentList'); + const path = this.path.member('shipment_list', 'shipmentList'); if (this.notLoaded) { - return new ShipmentListExpression([], this.root, path, false, this.notLoaded); + return new ShipmentListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return ShipmentListExpression.missing(this.root, path); if (!this.value.isLoaded('shipmentList')) { return new ShipmentListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'shipmentList')); + new TeaQLNotLoadedError(path.markMissing(), 'shipment_list')); } return new ShipmentListExpression( this.value.shipmentList(), this.root, path, @@ -278,58 +263,58 @@ export class OrderItemExpression { constructor( private readonly value: OrderItem | null | undefined, private readonly root = 'OrderItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.orderItem()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): OrderItem | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerOrderId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('customer_order', 'customerOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'customerOrder'); if (!this.value.isLoaded('customerOrder')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'customerOrder'), + new TeaQLNotLoadedError(path.markMissing(), 'customer_order'), ); } const reference = this.value.customerOrder; @@ -340,21 +325,23 @@ export class OrderItemExpression { } customerOrder(): CustomerOrderExpression { - const path = expressionPath(this.path, 'customerOrder'); + const path = this.path.member('customer_order', 'customerOrder'); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new CustomerOrderExpression(undefined, this.root, path); if (!this.value.isLoaded('customerOrder')) { return new CustomerOrderExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'customerOrder')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); } const relation = this.value.customerOrder; - const target = relation == null - ? undefined - : relation instanceof CustomerOrder - ? relation - : CustomerOrder.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CustomerOrder)) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const target = relation instanceof CustomerOrder ? relation : undefined; return new CustomerOrderExpression(target, this.root, path); } @@ -364,58 +351,58 @@ export class PaymentExpression { constructor( private readonly value: Payment | null | undefined, private readonly root = 'Payment(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.payment()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Payment | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } referenceCode(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('reference_code', 'referenceCode'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'referenceCode'); if (!this.value.isLoaded('referenceCode')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'referenceCode'), + new TeaQLNotLoadedError(path.markMissing(), 'reference_code'), ); } return new ValueExpression(this.value.referenceCode); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerOrderId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('customer_order', 'customerOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'customerOrder'); if (!this.value.isLoaded('customerOrder')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'customerOrder'), + new TeaQLNotLoadedError(path.markMissing(), 'customer_order'), ); } const reference = this.value.customerOrder; @@ -426,33 +413,35 @@ export class PaymentExpression { } customerOrder(): CustomerOrderExpression { - const path = expressionPath(this.path, 'customerOrder'); + const path = this.path.member('customer_order', 'customerOrder'); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new CustomerOrderExpression(undefined, this.root, path); if (!this.value.isLoaded('customerOrder')) { return new CustomerOrderExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'customerOrder')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); } const relation = this.value.customerOrder; - const target = relation == null - ? undefined - : relation instanceof CustomerOrder - ? relation - : CustomerOrder.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CustomerOrder)) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const target = relation instanceof CustomerOrder ? relation : undefined; return new CustomerOrderExpression(target, this.root, path); } paymentAttemptList(): PaymentAttemptListExpression { - const path = expressionPath(this.path, 'paymentAttemptList'); + const path = this.path.member('payment_attempt_list', 'paymentAttemptList'); if (this.notLoaded) { - return new PaymentAttemptListExpression([], this.root, path, false, this.notLoaded); + return new PaymentAttemptListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return PaymentAttemptListExpression.missing(this.root, path); if (!this.value.isLoaded('paymentAttemptList')) { return new PaymentAttemptListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'paymentAttemptList')); + new TeaQLNotLoadedError(path.markMissing(), 'payment_attempt_list')); } return new PaymentAttemptListExpression( this.value.paymentAttemptList(), this.root, path, @@ -464,58 +453,58 @@ export class PaymentAttemptExpression { constructor( private readonly value: PaymentAttempt | null | undefined, private readonly root = 'PaymentAttempt(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.paymentAttempt()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): PaymentAttempt | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } referenceCode(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('reference_code', 'referenceCode'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'referenceCode'); if (!this.value.isLoaded('referenceCode')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'referenceCode'), + new TeaQLNotLoadedError(path.markMissing(), 'reference_code'), ); } return new ValueExpression(this.value.referenceCode); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } paymentId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('payment', 'paymentId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'payment'); if (!this.value.isLoaded('payment')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'payment'), + new TeaQLNotLoadedError(path.markMissing(), 'payment'), ); } const reference = this.value.payment; @@ -526,21 +515,23 @@ export class PaymentAttemptExpression { } payment(): PaymentExpression { - const path = expressionPath(this.path, 'payment'); + const path = this.path.member('payment', 'payment'); if (this.notLoaded) { - return new PaymentExpression(undefined, this.root, path, this.notLoaded); + return new PaymentExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PaymentExpression(undefined, this.root, path); if (!this.value.isLoaded('payment')) { return new PaymentExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'payment')); + new TeaQLNotLoadedError(path.markMissing(), 'payment')); } const relation = this.value.payment; - const target = relation == null - ? undefined - : relation instanceof Payment - ? relation - : Payment.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Payment)) { + return new PaymentExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'payment')); + } + const target = relation instanceof Payment ? relation : undefined; return new PaymentExpression(target, this.root, path); } @@ -550,58 +541,58 @@ export class ShipmentExpression { constructor( private readonly value: Shipment | null | undefined, private readonly root = 'Shipment(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.shipment()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Shipment | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } referenceCode(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('reference_code', 'referenceCode'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'referenceCode'); if (!this.value.isLoaded('referenceCode')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'referenceCode'), + new TeaQLNotLoadedError(path.markMissing(), 'reference_code'), ); } return new ValueExpression(this.value.referenceCode); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerOrderId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('customer_order', 'customerOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'customerOrder'); if (!this.value.isLoaded('customerOrder')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'customerOrder'), + new TeaQLNotLoadedError(path.markMissing(), 'customer_order'), ); } const reference = this.value.customerOrder; @@ -612,21 +603,23 @@ export class ShipmentExpression { } customerOrder(): CustomerOrderExpression { - const path = expressionPath(this.path, 'customerOrder'); + const path = this.path.member('customer_order', 'customerOrder'); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new CustomerOrderExpression(undefined, this.root, path); if (!this.value.isLoaded('customerOrder')) { return new CustomerOrderExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'customerOrder')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); } const relation = this.value.customerOrder; - const target = relation == null - ? undefined - : relation instanceof CustomerOrder - ? relation - : CustomerOrder.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CustomerOrder)) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const target = relation instanceof CustomerOrder ? relation : undefined; return new CustomerOrderExpression(target, this.root, path); } @@ -636,30 +629,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -671,30 +668,34 @@ export class CustomerOrderListExpression { constructor( private readonly items: readonly CustomerOrder[], private readonly root = 'CustomerOrder(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): CustomerOrderListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CustomerOrderListExpression { return new CustomerOrderListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): CustomerOrderExpression { - return this.get(0); + return this.item(0, true); } get(index: number): CustomerOrderExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): CustomerOrderExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new CustomerOrderExpression(undefined, this.root, itemPath) @@ -706,30 +707,34 @@ export class OrderItemListExpression { constructor( private readonly items: readonly OrderItem[], private readonly root = 'OrderItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): OrderItemListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderItemListExpression { return new OrderItemListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): OrderItemExpression { - return this.get(0); + return this.item(0, true); } get(index: number): OrderItemExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderItemExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded); + return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new OrderItemExpression(undefined, this.root, itemPath) @@ -741,30 +746,34 @@ export class PaymentListExpression { constructor( private readonly items: readonly Payment[], private readonly root = 'Payment(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PaymentListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PaymentListExpression { return new PaymentListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PaymentExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PaymentExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PaymentExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PaymentExpression(undefined, this.root, itemPath, this.notLoaded); + return new PaymentExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PaymentExpression(undefined, this.root, itemPath) @@ -776,30 +785,34 @@ export class PaymentAttemptListExpression { constructor( private readonly items: readonly PaymentAttempt[], private readonly root = 'PaymentAttempt(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PaymentAttemptListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PaymentAttemptListExpression { return new PaymentAttemptListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PaymentAttemptExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PaymentAttemptExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PaymentAttemptExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PaymentAttemptExpression(undefined, this.root, itemPath, this.notLoaded); + return new PaymentAttemptExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PaymentAttemptExpression(undefined, this.root, itemPath) @@ -811,30 +824,34 @@ export class ShipmentListExpression { constructor( private readonly items: readonly Shipment[], private readonly root = 'Shipment(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): ShipmentListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): ShipmentListExpression { return new ShipmentListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): ShipmentExpression { - return this.get(0); + return this.item(0, true); } get(index: number): ShipmentExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): ShipmentExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new ShipmentExpression(undefined, this.root, itemPath, this.notLoaded); + return new ShipmentExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new ShipmentExpression(undefined, this.root, itemPath) @@ -847,7 +864,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -855,7 +872,7 @@ export class E { value: CustomerOrder | null | undefined, ): CustomerOrderExpression { return new CustomerOrderExpression( - value, `CustomerOrder(id=${value?.id ?? 'null'})`, + value, 'CustomerOrder', ExpressionPath.root('E.customerOrder()', 'camelCase'), ); } @@ -863,7 +880,7 @@ export class E { value: OrderItem | null | undefined, ): OrderItemExpression { return new OrderItemExpression( - value, `OrderItem(id=${value?.id ?? 'null'})`, + value, 'OrderItem', ExpressionPath.root('E.orderItem()', 'camelCase'), ); } @@ -871,7 +888,7 @@ export class E { value: Payment | null | undefined, ): PaymentExpression { return new PaymentExpression( - value, `Payment(id=${value?.id ?? 'null'})`, + value, 'Payment', ExpressionPath.root('E.payment()', 'camelCase'), ); } @@ -879,7 +896,7 @@ export class E { value: PaymentAttempt | null | undefined, ): PaymentAttemptExpression { return new PaymentAttemptExpression( - value, `PaymentAttempt(id=${value?.id ?? 'null'})`, + value, 'PaymentAttempt', ExpressionPath.root('E.paymentAttempt()', 'camelCase'), ); } @@ -887,7 +904,7 @@ export class E { value: Shipment | null | undefined, ): ShipmentExpression { return new ShipmentExpression( - value, `Shipment(id=${value?.id ?? 'null'})`, + value, 'Shipment', ExpressionPath.root('E.shipment()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/CustomerOrder.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/CustomerOrder.ts index ab40b8d9609c4d1838571b601bc9782d52bcbd42..f71eed16025f68c6f6ab19ed21e70dc04ad11897 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/CustomerOrder.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/CustomerOrder.ts @@ -1,29 +1,35 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { OrderItem } from './OrderItem'; import { Payment } from './Payment'; import { Shipment } from './Shipment'; +const teaqlConstruction = Symbol("managed entity construction"); + export class CustomerOrder { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("CustomerOrder", + ["id", "platform", "order_number", "description", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; platform?: Platform | string; orderNumber?: string; description?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_orderItemList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_paymentList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_shipmentList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_paymentList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_shipmentList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["orderItemList"]; delete fields["paymentList"]; delete fields["shipmentList"]; @@ -66,26 +72,36 @@ export class CustomerOrder { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root); - for (const child of (this as any)._paymentList) child.teaqlAttachRoot(root); - for (const child of (this as any)._shipmentList) child.teaqlAttachRoot(root); + for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._paymentList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._shipmentList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): CustomerOrder { - const entity = new CustomerOrder(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new CustomerOrder(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderItemList")) result["orderItemList"] = (this as any)._orderItemList; + if (this.isLoaded("paymentList")) result["paymentList"] = (this as any)._paymentList; + if (this.isLoaded("shipmentList")) result["shipmentList"] = (this as any)._shipmentList; + return result; } isLoaded(field: string): boolean { @@ -104,12 +120,19 @@ export class CustomerOrder { } static refer(id: string | number): CustomerOrder { - return new CustomerOrder({ id: String(id) } as Partial); + return CustomerOrder.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): CustomerOrder { - return new CustomerOrder().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): CustomerOrder { + return EntityCreation.bootstrap(context, "CustomerOrder", id, + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "CustomerOrder", + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -119,23 +142,181 @@ export class CustomerOrder { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._paymentList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._shipmentList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._paymentList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("payment_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._shipmentList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("shipment_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderItemList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._paymentList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._shipmentList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_item_list": graph.sourceMembers((this as any)._orderItemList), + "payment_list": graph.sourceMembers((this as any)._paymentList), + "shipment_list": graph.sourceMembers((this as any)._shipmentList) + })); + for (const child of (this as any)._orderItemList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._paymentList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._shipmentList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + CustomerOrder.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "orderNumber", canonical: "order_number" }, { member: "description", canonical: "description" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._paymentList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("payment_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._shipmentList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("shipment_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "orderNumber", canonical: "order_number" }, { member: "description", canonical: "description" }, { member: "version", canonical: "version" }] @@ -143,6 +324,7 @@ export class CustomerOrder { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -153,7 +335,8 @@ export class CustomerOrder { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -162,50 +345,55 @@ export class CustomerOrder { for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._paymentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._shipmentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("shipment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -213,7 +401,7 @@ export class CustomerOrder { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -225,56 +413,57 @@ export class CustomerOrder { for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._paymentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._shipmentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("shipment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -283,12 +472,16 @@ export class CustomerOrder { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -299,52 +492,59 @@ export class CustomerOrder { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._paymentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._shipmentList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("shipment_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -359,6 +559,10 @@ export class CustomerOrder { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -380,7 +584,7 @@ export class CustomerOrder { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/OrderItem.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/OrderItem.ts index 4a8d1bb31d27005773cbe1ff5aa1a43d70eb2c36..67df1167e476eddb010dd72feced2c7a8d4dba2a 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/OrderItem.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/OrderItem.ts @@ -1,22 +1,28 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class OrderItem { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderItem", + ["id", "customer_order", "name", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; customerOrder?: CustomerOrder | string; name?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") { this.customerOrder = (init as any).customerOrder instanceof CustomerOrder @@ -26,13 +32,15 @@ export class OrderItem { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -41,8 +49,13 @@ export class OrderItem { } static fromRecord(record: Record, root?: EntityRoot): OrderItem { - const entity = new OrderItem(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new OrderItem(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -61,12 +74,19 @@ export class OrderItem { } static refer(id: string | number): OrderItem { - return new OrderItem({ id: String(id) } as Partial); + return OrderItem.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): OrderItem { - return new OrderItem().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderItem { + return EntityCreation.bootstrap(context, "OrderItem", id, + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderItem", + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -76,23 +96,100 @@ export class OrderItem { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer_order": "CustomerOrder" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderItem.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] @@ -100,6 +197,7 @@ export class OrderItem { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -110,7 +208,8 @@ export class OrderItem { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -119,8 +218,10 @@ export class OrderItem { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -128,7 +229,7 @@ export class OrderItem { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -140,14 +241,12 @@ export class OrderItem { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -156,12 +255,16 @@ export class OrderItem { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -172,10 +275,14 @@ export class OrderItem { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -189,6 +296,10 @@ export class OrderItem { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -203,7 +314,7 @@ export class OrderItem { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Payment.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Payment.ts index 61f3787c113ed773a842feb9505ce2834f8a56c7..a14d587637f3e17c5118296b35b2a40d9eb84bc3 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Payment.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Payment.ts @@ -1,24 +1,30 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { CustomerOrder } from './CustomerOrder'; import { PaymentAttempt } from './PaymentAttempt'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Payment { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Payment", + ["id", "customer_order", "reference_code", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; customerOrder?: CustomerOrder | string; referenceCode?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Payment.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_paymentAttemptList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_paymentAttemptList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["paymentAttemptList"]; Object.assign(this, fields); if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") { @@ -39,24 +45,32 @@ export class Payment { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Payment", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._paymentAttemptList) child.teaqlAttachRoot(root); + for (const child of (this as any)._paymentAttemptList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Payment { - const entity = new Payment(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Payment(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("paymentAttemptList")) result["paymentAttemptList"] = (this as any)._paymentAttemptList; + return result; } isLoaded(field: string): boolean { @@ -75,12 +89,19 @@ export class Payment { } static refer(id: string | number): Payment { - return new Payment({ id: String(id) } as Partial); + return Payment.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Payment { - return new Payment().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Payment { + return EntityCreation.bootstrap(context, "Payment", id, + reserved => new Payment({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Payment", + reserved => new Payment({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -90,23 +111,127 @@ export class Payment { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._paymentAttemptList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._paymentAttemptList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("payment_attempt_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Payment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._paymentAttemptList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Payment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer_order": "CustomerOrder" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "payment_attempt_list": graph.sourceMembers((this as any)._paymentAttemptList) + })); + for (const child of (this as any)._paymentAttemptList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.payment; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePayment(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Payment.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Payment", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._paymentAttemptList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("payment_attempt_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Payment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }] @@ -114,6 +239,7 @@ export class Payment { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Payment", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -124,7 +250,8 @@ export class Payment { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -133,22 +260,25 @@ export class Payment { for (const [index, child] of (this as any)._paymentAttemptList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.payment; - if (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePayment(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePayment(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_attempt_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -156,7 +286,7 @@ export class Payment { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -168,28 +298,27 @@ export class Payment { for (const [index, child] of (this as any)._paymentAttemptList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.payment; - if (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePayment(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePayment(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_attempt_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -198,12 +327,16 @@ export class Payment { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -214,24 +347,29 @@ export class Payment { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._paymentAttemptList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.payment; - if (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePayment(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("payment") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePayment(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("payment_attempt_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -245,6 +383,10 @@ export class Payment { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -259,7 +401,7 @@ export class Payment { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts index 141650904f4f728ea4529ff9c2128baa08b9b8e1..a1f7e6c8a27f8085001e2ab62298ab90bde9bf2c 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts @@ -1,22 +1,28 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Payment } from './Payment'; +const teaqlConstruction = Symbol("managed entity construction"); + export class PaymentAttempt { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("PaymentAttempt", + ["id", "payment", "reference_code", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; payment?: Payment | string; referenceCode?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --PaymentAttempt.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).payment && typeof (init as any).payment === "object") { this.payment = (init as any).payment instanceof Payment @@ -26,13 +32,15 @@ export class PaymentAttempt { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "PaymentAttempt", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -41,8 +49,13 @@ export class PaymentAttempt { } static fromRecord(record: Record, root?: EntityRoot): PaymentAttempt { - const entity = new PaymentAttempt(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new PaymentAttempt(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -61,12 +74,19 @@ export class PaymentAttempt { } static refer(id: string | number): PaymentAttempt { - return new PaymentAttempt({ id: String(id) } as Partial); + return PaymentAttempt.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): PaymentAttempt { - return new PaymentAttempt().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): PaymentAttempt { + return EntityCreation.bootstrap(context, "PaymentAttempt", id, + reserved => new PaymentAttempt({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "PaymentAttempt", + reserved => new PaymentAttempt({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -76,23 +96,100 @@ export class PaymentAttempt { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(PaymentAttempt.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(PaymentAttempt.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "payment": "Payment" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + PaymentAttempt.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "payment", canonical: "payment" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "PaymentAttempt", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(PaymentAttempt.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "payment", canonical: "payment" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }] @@ -100,6 +197,7 @@ export class PaymentAttempt { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "PaymentAttempt", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -110,7 +208,8 @@ export class PaymentAttempt { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -119,8 +218,10 @@ export class PaymentAttempt { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -128,7 +229,7 @@ export class PaymentAttempt { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -140,14 +241,12 @@ export class PaymentAttempt { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -156,12 +255,16 @@ export class PaymentAttempt { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -172,10 +275,14 @@ export class PaymentAttempt { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -189,6 +296,10 @@ export class PaymentAttempt { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -203,7 +314,7 @@ export class PaymentAttempt { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Platform.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Platform.ts index 0561320937e12ecec16df9008b6ac5f1c29f6b51..f1aca1c7a6a5e7fcbab9789f5a62f40176204e65 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Platform.ts @@ -1,22 +1,28 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["customerOrderList"]; Object.assign(this, fields); if (Array.isArray((init as any).customerOrderList)) { @@ -31,24 +37,32 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root); + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + return result; } isLoaded(field: string): boolean { @@ -67,12 +81,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -82,23 +103,126 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList) + })); + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] @@ -106,6 +230,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -116,7 +241,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -125,22 +251,25 @@ export class Platform { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -148,7 +277,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -160,28 +289,27 @@ export class Platform { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -190,12 +318,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -206,24 +338,29 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -236,6 +373,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -250,7 +391,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Shipment.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Shipment.ts index a5f6d18f4b12c44151ee4ec630c4a91702043d6e..5b02968a67152ca8f9da31db9e7b3f055c74806f 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Shipment.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/models/Shipment.ts @@ -1,22 +1,28 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Shipment { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Shipment", + ["id", "customer_order", "reference_code", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; customerOrder?: CustomerOrder | string; referenceCode?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Shipment.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") { this.customerOrder = (init as any).customerOrder instanceof CustomerOrder @@ -26,13 +32,15 @@ export class Shipment { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Shipment", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -41,8 +49,13 @@ export class Shipment { } static fromRecord(record: Record, root?: EntityRoot): Shipment { - const entity = new Shipment(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Shipment(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -61,12 +74,19 @@ export class Shipment { } static refer(id: string | number): Shipment { - return new Shipment({ id: String(id) } as Partial); + return Shipment.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Shipment { - return new Shipment().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Shipment { + return EntityCreation.bootstrap(context, "Shipment", id, + reserved => new Shipment({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Shipment", + reserved => new Shipment({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -76,23 +96,100 @@ export class Shipment { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Shipment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Shipment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer_order": "CustomerOrder" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Shipment.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Shipment", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Shipment.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "referenceCode", canonical: "reference_code" }, { member: "version", canonical: "version" }] @@ -100,6 +197,7 @@ export class Shipment { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Shipment", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -110,7 +208,8 @@ export class Shipment { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -119,8 +218,10 @@ export class Shipment { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -128,7 +229,7 @@ export class Shipment { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -140,14 +241,12 @@ export class Shipment { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -156,12 +255,16 @@ export class Shipment { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -172,10 +275,14 @@ export class Shipment { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -189,6 +296,10 @@ export class Shipment { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -203,7 +314,7 @@ export class Shipment { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts index 60dc6c51d41c84e7b7e5380c9e55dbe472f9cb7d..bc6ee30e1ea3994d67a7e1b539e944b493c69e46 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { CustomerOrder } from '../models/CustomerOrder'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class CustomerOrderRequest { else this.selectSelfFields(); } + get entityName(): "CustomerOrder" { + return "CustomerOrder"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class CustomerOrderRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -136,7 +143,7 @@ export class CustomerOrderRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -144,7 +151,7 @@ export class CustomerOrderRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -153,7 +160,7 @@ export class CustomerOrderRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -162,19 +169,19 @@ export class CustomerOrderRequest { return this; } - selectOrderItemListWith(request: { toQuery(): SelectQuery }): this { + selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.query.relationQuery( "orderItemList", request.toQuery(), "id", "customerOrder", true, { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" }); return this; } - selectPaymentListWith(request: { toQuery(): SelectQuery }): this { + selectPaymentListWith(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.query.relationQuery( "paymentList", request.toQuery(), "id", "customerOrder", true, { kind: "relation-select", method: "selectPaymentListWith", relation: "paymentList" }); return this; } - selectShipmentListWith(request: { toQuery(): SelectQuery }): this { + selectShipmentListWith(request: { readonly entityName: "Shipment"; toQuery(): SelectQuery }): this { this.query.relationQuery( "shipmentList", request.toQuery(), "id", "customerOrder", true, { kind: "relation-select", method: "selectShipmentListWith", relation: "shipmentList" }); @@ -183,17 +190,19 @@ export class CustomerOrderRequest { haveOrderItems(): this { return this.withOrderItemListMatching({ + entityName: "OrderItem", toQuery: () => new SelectQuery("OrderItem"), }); } haveNoOrderItems(): this { return this.withoutOrderItemListMatching({ + entityName: "OrderItem", toQuery: () => new SelectQuery("OrderItem"), }); } - withOrderItemListMatching(request: { toQuery(): SelectQuery }): this { + withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -204,7 +213,7 @@ export class CustomerOrderRequest { return this; } - withoutOrderItemListMatching(request: { toQuery(): SelectQuery }): this { + withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -216,17 +225,19 @@ export class CustomerOrderRequest { } havePayments(): this { return this.withPaymentListMatching({ + entityName: "Payment", toQuery: () => new SelectQuery("Payment"), }); } haveNoPayments(): this { return this.withoutPaymentListMatching({ + entityName: "Payment", toQuery: () => new SelectQuery("Payment"), }); } - withPaymentListMatching(request: { toQuery(): SelectQuery }): this { + withPaymentListMatching(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -237,7 +248,7 @@ export class CustomerOrderRequest { return this; } - withoutPaymentListMatching(request: { toQuery(): SelectQuery }): this { + withoutPaymentListMatching(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -249,17 +260,19 @@ export class CustomerOrderRequest { } haveShipments(): this { return this.withShipmentListMatching({ + entityName: "Shipment", toQuery: () => new SelectQuery("Shipment"), }); } haveNoShipments(): this { return this.withoutShipmentListMatching({ + entityName: "Shipment", toQuery: () => new SelectQuery("Shipment"), }); } - withShipmentListMatching(request: { toQuery(): SelectQuery }): this { + withShipmentListMatching(request: { readonly entityName: "Shipment"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -270,7 +283,7 @@ export class CustomerOrderRequest { return this; } - withoutShipmentListMatching(request: { toQuery(): SelectQuery }): this { + withoutShipmentListMatching(request: { readonly entityName: "Shipment"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -287,13 +300,13 @@ export class CustomerOrderRequest { countOrderItemsAs(alias: string): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); - this.countOrderItemsWith(alias, { toQuery: () => query }); + this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias }; return this; } - countOrderItemsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -309,13 +322,13 @@ export class CustomerOrderRequest { countPaymentsAs(alias: string): this { const query = new SelectQuery("Payment").filter({ version: { "$gte": 1 } }); - this.countPaymentsWith(alias, { toQuery: () => query }); + this.countPaymentsWith(alias, { entityName: "Payment", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countPaymentsAs", relation: "paymentList", alias }; return this; } - countPaymentsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countPaymentsWith(alias: string, child: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -331,13 +344,13 @@ export class CustomerOrderRequest { countShipmentsAs(alias: string): this { const query = new SelectQuery("Shipment").filter({ version: { "$gte": 1 } }); - this.countShipmentsWith(alias, { toQuery: () => query }); + this.countShipmentsWith(alias, { entityName: "Shipment", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countShipmentsAs", relation: "shipmentList", alias }; return this; } - countShipmentsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countShipmentsWith(alias: string, child: { readonly entityName: "Shipment"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -348,47 +361,47 @@ export class CustomerOrderRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -433,42 +446,42 @@ export class CustomerOrderRequest { return this; } - withOrderNumberIsNot(val: any): this { + withOrderNumberIsNot(val: string): this { this.filters.push({ "orderNumber": { "$ne": val } }); return this; } - withOrderNumberIn(...vals: any[]): this { + withOrderNumberIn(...vals: string[]): this { this.filters.push({ "orderNumber": { "$in": vals } }); return this; } - withOrderNumberNotIn(...vals: any[]): this { + withOrderNumberNotIn(...vals: string[]): this { this.filters.push({ "orderNumber": { "$notIn": vals } }); return this; } - withOrderNumberGreaterThan(val: any): this { + withOrderNumberGreaterThan(val: string): this { this.filters.push({ "orderNumber": { "$gt": val } }); return this; } - withOrderNumberGreaterThanOrEqualTo(val: any): this { + withOrderNumberGreaterThanOrEqualTo(val: string): this { this.filters.push({ "orderNumber": { "$gte": val } }); return this; } - withOrderNumberLessThan(val: any): this { + withOrderNumberLessThan(val: string): this { this.filters.push({ "orderNumber": { "$lt": val } }); return this; } - withOrderNumberLessThanOrEqualTo(val: any): this { + withOrderNumberLessThanOrEqualTo(val: string): this { this.filters.push({ "orderNumber": { "$lte": val } }); return this; } - withOrderNumberBetween(lower: any, upper: any): this { + withOrderNumberBetween(lower: string, upper: string): this { this.filters.push({ "orderNumber": { "$between": [lower, upper] } }); return this; } @@ -522,42 +535,42 @@ export class CustomerOrderRequest { return this; } - withDescriptionIsNot(val: any): this { + withDescriptionIsNot(val: string): this { this.filters.push({ "description": { "$ne": val } }); return this; } - withDescriptionIn(...vals: any[]): this { + withDescriptionIn(...vals: string[]): this { this.filters.push({ "description": { "$in": vals } }); return this; } - withDescriptionNotIn(...vals: any[]): this { + withDescriptionNotIn(...vals: string[]): this { this.filters.push({ "description": { "$notIn": vals } }); return this; } - withDescriptionGreaterThan(val: any): this { + withDescriptionGreaterThan(val: string): this { this.filters.push({ "description": { "$gt": val } }); return this; } - withDescriptionGreaterThanOrEqualTo(val: any): this { + withDescriptionGreaterThanOrEqualTo(val: string): this { this.filters.push({ "description": { "$gte": val } }); return this; } - withDescriptionLessThan(val: any): this { + withDescriptionLessThan(val: string): this { this.filters.push({ "description": { "$lt": val } }); return this; } - withDescriptionLessThanOrEqualTo(val: any): this { + withDescriptionLessThanOrEqualTo(val: string): this { this.filters.push({ "description": { "$lte": val } }); return this; } - withDescriptionBetween(lower: any, upper: any): this { + withDescriptionBetween(lower: string, upper: string): this { this.filters.push({ "description": { "$between": [lower, upper] } }); return this; } @@ -601,47 +614,47 @@ export class CustomerOrderRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -721,7 +734,7 @@ export class CustomerOrderRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPlatform(): this { @@ -730,7 +743,7 @@ export class CustomerOrderRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupByOrderNumber(): this { @@ -739,7 +752,7 @@ export class CustomerOrderRequest { } groupByOrderNumberAs(retName: string): this { - this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively + this.query.groupBy("orderNumber", retName); return this; } groupByDescription(): this { @@ -748,7 +761,7 @@ export class CustomerOrderRequest { } groupByDescriptionAs(retName: string): this { - this.query.groupBy("description"); // In TS we don't alias group by yet natively + this.query.groupBy("description", retName); return this; } groupByVersion(): this { @@ -757,14 +770,14 @@ export class CustomerOrderRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -880,9 +893,10 @@ export class ExecutableCustomerOrderRequest { return this; } - newEntity(context: UserContext): CustomerOrder { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new CustomerOrder(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return CustomerOrder.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts index 71354b80c79899c464c186c8532d4a0e47fc2594..45d59c6cce8403619a95810efcfd760d2cbed4ef 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderItem } from '../models/OrderItem'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class OrderItemRequest { else this.selectSelfFields(); } + get entityName(): "OrderItem" { + return "OrderItem"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class OrderItemRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -131,7 +138,7 @@ export class OrderItemRequest { } - selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.select(["customerOrder"]); this.query.relationQuery( "customerOrder", request.toQuery(), "customerOrder", "id", false, @@ -139,7 +146,7 @@ export class OrderItemRequest { return this; } - withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -148,7 +155,7 @@ export class OrderItemRequest { return this; } - withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -160,47 +167,47 @@ export class OrderItemRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -245,42 +252,42 @@ export class OrderItemRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -324,47 +331,47 @@ export class OrderItemRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -434,7 +441,7 @@ export class OrderItemRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomerOrder(): this { @@ -443,7 +450,7 @@ export class OrderItemRequest { } groupByCustomerOrderAs(retName: string): this { - this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("customerOrder", retName); return this; } groupByName(): this { @@ -452,7 +459,7 @@ export class OrderItemRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByVersion(): this { @@ -461,14 +468,14 @@ export class OrderItemRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByCustomerOrderAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "customerOrder", request, includeAllFacets, @@ -584,9 +591,10 @@ export class ExecutableOrderItemRequest { return this; } - newEntity(context: UserContext): OrderItem { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new OrderItem(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderItem.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts index 4e732e407d2db3759f7de8fe4c91828b36f27a6e..b0addcac02e429ebef96f223d9abb35d82b52b82 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { PaymentAttempt } from '../models/PaymentAttempt'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PaymentAttemptRequest { else this.selectSelfFields(); } + get entityName(): "PaymentAttempt" { + return "PaymentAttempt"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PaymentAttemptRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -131,7 +138,7 @@ export class PaymentAttemptRequest { } - selectPaymentWith(request: { toQuery(): SelectQuery }): this { + selectPaymentWith(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.query.select(["payment"]); this.query.relationQuery( "payment", request.toQuery(), "payment", "id", false, @@ -139,7 +146,7 @@ export class PaymentAttemptRequest { return this; } - withPaymentMatching(request: { toQuery(): SelectQuery }): this { + withPaymentMatching(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.filters.push({ "payment": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -148,7 +155,7 @@ export class PaymentAttemptRequest { return this; } - withoutPaymentMatching(request: { toQuery(): SelectQuery }): this { + withoutPaymentMatching(request: { readonly entityName: "Payment"; toQuery(): SelectQuery }): this { this.filters.push({ "payment": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -160,47 +167,47 @@ export class PaymentAttemptRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -245,42 +252,42 @@ export class PaymentAttemptRequest { return this; } - withReferenceCodeIsNot(val: any): this { + withReferenceCodeIsNot(val: string): this { this.filters.push({ "referenceCode": { "$ne": val } }); return this; } - withReferenceCodeIn(...vals: any[]): this { + withReferenceCodeIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$in": vals } }); return this; } - withReferenceCodeNotIn(...vals: any[]): this { + withReferenceCodeNotIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$notIn": vals } }); return this; } - withReferenceCodeGreaterThan(val: any): this { + withReferenceCodeGreaterThan(val: string): this { this.filters.push({ "referenceCode": { "$gt": val } }); return this; } - withReferenceCodeGreaterThanOrEqualTo(val: any): this { + withReferenceCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$gte": val } }); return this; } - withReferenceCodeLessThan(val: any): this { + withReferenceCodeLessThan(val: string): this { this.filters.push({ "referenceCode": { "$lt": val } }); return this; } - withReferenceCodeLessThanOrEqualTo(val: any): this { + withReferenceCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$lte": val } }); return this; } - withReferenceCodeBetween(lower: any, upper: any): this { + withReferenceCodeBetween(lower: string, upper: string): this { this.filters.push({ "referenceCode": { "$between": [lower, upper] } }); return this; } @@ -324,47 +331,47 @@ export class PaymentAttemptRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -434,7 +441,7 @@ export class PaymentAttemptRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPayment(): this { @@ -443,7 +450,7 @@ export class PaymentAttemptRequest { } groupByPaymentAs(retName: string): this { - this.query.groupBy("payment"); // In TS we don't alias group by yet natively + this.query.groupBy("payment", retName); return this; } groupByReferenceCode(): this { @@ -452,7 +459,7 @@ export class PaymentAttemptRequest { } groupByReferenceCodeAs(retName: string): this { - this.query.groupBy("referenceCode"); // In TS we don't alias group by yet natively + this.query.groupBy("referenceCode", retName); return this; } groupByVersion(): this { @@ -461,14 +468,14 @@ export class PaymentAttemptRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPaymentAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Payment"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "payment", request, includeAllFacets, @@ -584,9 +591,10 @@ export class ExecutablePaymentAttemptRequest { return this; } - newEntity(context: UserContext): PaymentAttempt { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new PaymentAttempt(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return PaymentAttempt.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts index c7026402470891bb8738f59c0d7a99be8682dfdd..81cdc637063ec561305b4af8f2c77c06304fe565 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Payment } from '../models/Payment'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PaymentRequest { else this.selectSelfFields(); } + get entityName(): "Payment" { + return "Payment"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PaymentRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -131,7 +138,7 @@ export class PaymentRequest { } - selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.select(["customerOrder"]); this.query.relationQuery( "customerOrder", request.toQuery(), "customerOrder", "id", false, @@ -139,7 +146,7 @@ export class PaymentRequest { return this; } - withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -148,7 +155,7 @@ export class PaymentRequest { return this; } - withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -157,7 +164,7 @@ export class PaymentRequest { return this; } - selectPaymentAttemptListWith(request: { toQuery(): SelectQuery }): this { + selectPaymentAttemptListWith(request: { readonly entityName: "PaymentAttempt"; toQuery(): SelectQuery }): this { this.query.relationQuery( "paymentAttemptList", request.toQuery(), "id", "payment", true, { kind: "relation-select", method: "selectPaymentAttemptListWith", relation: "paymentAttemptList" }); @@ -166,17 +173,19 @@ export class PaymentRequest { havePaymentAttempts(): this { return this.withPaymentAttemptListMatching({ + entityName: "PaymentAttempt", toQuery: () => new SelectQuery("PaymentAttempt"), }); } haveNoPaymentAttempts(): this { return this.withoutPaymentAttemptListMatching({ + entityName: "PaymentAttempt", toQuery: () => new SelectQuery("PaymentAttempt"), }); } - withPaymentAttemptListMatching(request: { toQuery(): SelectQuery }): this { + withPaymentAttemptListMatching(request: { readonly entityName: "PaymentAttempt"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -187,7 +196,7 @@ export class PaymentRequest { return this; } - withoutPaymentAttemptListMatching(request: { toQuery(): SelectQuery }): this { + withoutPaymentAttemptListMatching(request: { readonly entityName: "PaymentAttempt"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -204,13 +213,13 @@ export class PaymentRequest { countPaymentAttemptsAs(alias: string): this { const query = new SelectQuery("PaymentAttempt").filter({ version: { "$gte": 1 } }); - this.countPaymentAttemptsWith(alias, { toQuery: () => query }); + this.countPaymentAttemptsWith(alias, { entityName: "PaymentAttempt", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countPaymentAttemptsAs", relation: "paymentAttemptList", alias }; return this; } - countPaymentAttemptsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countPaymentAttemptsWith(alias: string, child: { readonly entityName: "PaymentAttempt"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -221,47 +230,47 @@ export class PaymentRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -306,42 +315,42 @@ export class PaymentRequest { return this; } - withReferenceCodeIsNot(val: any): this { + withReferenceCodeIsNot(val: string): this { this.filters.push({ "referenceCode": { "$ne": val } }); return this; } - withReferenceCodeIn(...vals: any[]): this { + withReferenceCodeIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$in": vals } }); return this; } - withReferenceCodeNotIn(...vals: any[]): this { + withReferenceCodeNotIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$notIn": vals } }); return this; } - withReferenceCodeGreaterThan(val: any): this { + withReferenceCodeGreaterThan(val: string): this { this.filters.push({ "referenceCode": { "$gt": val } }); return this; } - withReferenceCodeGreaterThanOrEqualTo(val: any): this { + withReferenceCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$gte": val } }); return this; } - withReferenceCodeLessThan(val: any): this { + withReferenceCodeLessThan(val: string): this { this.filters.push({ "referenceCode": { "$lt": val } }); return this; } - withReferenceCodeLessThanOrEqualTo(val: any): this { + withReferenceCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$lte": val } }); return this; } - withReferenceCodeBetween(lower: any, upper: any): this { + withReferenceCodeBetween(lower: string, upper: string): this { this.filters.push({ "referenceCode": { "$between": [lower, upper] } }); return this; } @@ -385,47 +394,47 @@ export class PaymentRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -495,7 +504,7 @@ export class PaymentRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomerOrder(): this { @@ -504,7 +513,7 @@ export class PaymentRequest { } groupByCustomerOrderAs(retName: string): this { - this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("customerOrder", retName); return this; } groupByReferenceCode(): this { @@ -513,7 +522,7 @@ export class PaymentRequest { } groupByReferenceCodeAs(retName: string): this { - this.query.groupBy("referenceCode"); // In TS we don't alias group by yet natively + this.query.groupBy("referenceCode", retName); return this; } groupByVersion(): this { @@ -522,14 +531,14 @@ export class PaymentRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByCustomerOrderAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "customerOrder", request, includeAllFacets, @@ -645,9 +654,10 @@ export class ExecutablePaymentRequest { return this; } - newEntity(context: UserContext): Payment { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Payment(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Payment.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts index c88ef6a0bf86cd308da8f3bfaf18d4e65f936462..2476c548aff16f22cd4aef253f38ea1aa6d67956 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -132,7 +139,7 @@ export class PlatformRequest { - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.relationQuery( "customerOrderList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); @@ -141,17 +148,19 @@ export class PlatformRequest { haveCustomerOrders(): this { return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } haveNoCustomerOrders(): this { return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } - withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -162,7 +171,7 @@ export class PlatformRequest { return this; } - withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -179,13 +188,13 @@ export class PlatformRequest { countCustomerOrdersAs(alias: string): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); - this.countCustomerOrdersWith(alias, { toQuery: () => query }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; return this; } - countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this { + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -196,47 +205,47 @@ export class PlatformRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -261,42 +270,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -340,47 +349,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -449,7 +458,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -458,7 +467,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByVersion(): this { @@ -467,7 +476,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -580,9 +589,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts index f9e044613521879a2f627df51735bc8fabd3348c..fa194b2a52c6bf3e56d6e2b63ed9c50c958b5a8f 100644 --- a/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts +++ b/source/teaql-ts/examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Shipment } from '../models/Shipment'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class ShipmentRequest { else this.selectSelfFields(); } + get entityName(): "Shipment" { + return "Shipment"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class ShipmentRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -131,7 +138,7 @@ export class ShipmentRequest { } - selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.select(["customerOrder"]); this.query.relationQuery( "customerOrder", request.toQuery(), "customerOrder", "id", false, @@ -139,7 +146,7 @@ export class ShipmentRequest { return this; } - withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -148,7 +155,7 @@ export class ShipmentRequest { return this; } - withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -160,47 +167,47 @@ export class ShipmentRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -245,42 +252,42 @@ export class ShipmentRequest { return this; } - withReferenceCodeIsNot(val: any): this { + withReferenceCodeIsNot(val: string): this { this.filters.push({ "referenceCode": { "$ne": val } }); return this; } - withReferenceCodeIn(...vals: any[]): this { + withReferenceCodeIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$in": vals } }); return this; } - withReferenceCodeNotIn(...vals: any[]): this { + withReferenceCodeNotIn(...vals: string[]): this { this.filters.push({ "referenceCode": { "$notIn": vals } }); return this; } - withReferenceCodeGreaterThan(val: any): this { + withReferenceCodeGreaterThan(val: string): this { this.filters.push({ "referenceCode": { "$gt": val } }); return this; } - withReferenceCodeGreaterThanOrEqualTo(val: any): this { + withReferenceCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$gte": val } }); return this; } - withReferenceCodeLessThan(val: any): this { + withReferenceCodeLessThan(val: string): this { this.filters.push({ "referenceCode": { "$lt": val } }); return this; } - withReferenceCodeLessThanOrEqualTo(val: any): this { + withReferenceCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "referenceCode": { "$lte": val } }); return this; } - withReferenceCodeBetween(lower: any, upper: any): this { + withReferenceCodeBetween(lower: string, upper: string): this { this.filters.push({ "referenceCode": { "$between": [lower, upper] } }); return this; } @@ -324,47 +331,47 @@ export class ShipmentRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -434,7 +441,7 @@ export class ShipmentRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomerOrder(): this { @@ -443,7 +450,7 @@ export class ShipmentRequest { } groupByCustomerOrderAs(retName: string): this { - this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("customerOrder", retName); return this; } groupByReferenceCode(): this { @@ -452,7 +459,7 @@ export class ShipmentRequest { } groupByReferenceCodeAs(retName: string): this { - this.query.groupBy("referenceCode"); // In TS we don't alias group by yet natively + this.query.groupBy("referenceCode", retName); return this; } groupByVersion(): this { @@ -461,14 +468,14 @@ export class ShipmentRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByCustomerOrderAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "customerOrder", request, includeAllFacets, @@ -584,9 +591,10 @@ export class ExecutableShipmentRequest { return this; } - newEntity(context: UserContext): Shipment { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Shipment(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Shipment.teaqlCreate(context); } executeForList(context: UserContext): Promise> {