philipgreat commited on
Commit
b62a79f
·
verified ·
1 Parent(s): f3f2565

docs: explain model-driven development process (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. source/teaql-ts/examples/fix-e-alignment/generated/src/generated-bootstrap.ts +14 -0
  2. source/teaql-ts/examples/fix-e-alignment/generated/src/generated-search-models.ts +90 -0
  3. source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts +985 -0
  4. source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts +1064 -0
  5. source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts +791 -0
  6. source/teaql-ts/examples/fix-e-alignment/generated/src/runtime-module.ts +170 -0
  7. source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sql.ts +22 -0
  8. source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts +14 -0
  9. source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-ts.ts +518 -0
  10. source/teaql-ts/examples/fix-e-alignment/generated/teaql-i18n.json +117 -0
  11. source/teaql-ts/examples/fix-e-alignment/generated/tsconfig.json +12 -0
  12. source/teaql-ts/examples/fix-e-alignment/graph-fix-idempotence.test.ts +112 -0
  13. source/teaql-ts/examples/fix-e-alignment/loading-probe.ts +55 -0
  14. source/teaql-ts/examples/fix-e-alignment/model.xml +17 -0
  15. source/teaql-ts/examples/fix-e-alignment/owned-command.cjs +79 -0
  16. source/teaql-ts/examples/fix-e-alignment/ownership-probe.ts +41 -0
  17. source/teaql-ts/examples/fix-e-alignment/paged-ownership.ts +50 -0
  18. source/teaql-ts/examples/fix-e-alignment/partial-ancestors-probe.ts +142 -0
  19. source/teaql-ts/examples/fix-e-alignment/partial-root-probe.ts +140 -0
  20. source/teaql-ts/examples/fix-e-alignment/unchanged-views-probe.ts +167 -0
  21. source/teaql-ts/examples/fix-e-alignment/verify-local.cjs +138 -0
  22. source/teaql-ts/examples/fix-e-alignment/verify.test.ts +286 -0
  23. source/teaql-ts/examples/managed-creation-fixtures.json +0 -0
  24. source/teaql-ts/examples/natural-messages/AGENTS.md +19 -0
  25. source/teaql-ts/examples/natural-messages/README.md +45 -0
  26. source/teaql-ts/examples/natural-messages/fixture/evaluation.json +108 -0
  27. source/teaql-ts/examples/natural-messages/fixture/generated-files.json +19 -0
  28. source/teaql-ts/examples/natural-messages/fixture/generation.json +11 -0
  29. source/teaql-ts/examples/natural-messages/fixture/model.xml +5 -0
  30. source/teaql-ts/examples/natural-messages/fixture/package.json +18 -0
  31. source/teaql-ts/examples/natural-messages/fixture/src/generated-bootstrap.ts +14 -0
  32. source/teaql-ts/examples/natural-messages/fixture/src/generated-search-models.ts +45 -0
  33. source/teaql-ts/examples/natural-messages/fixture/src/generated/E.ts +320 -0
  34. source/teaql-ts/examples/natural-messages/fixture/src/generated/Q.ts +20 -0
  35. source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Catalog.ts +403 -0
  36. source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Entry.ts +345 -0
  37. source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/CatalogRequest.ts +616 -0
  38. source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/EntryRequest.ts +778 -0
  39. source/teaql-ts/examples/natural-messages/fixture/src/runtime-module.ts +74 -0
  40. source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sql.ts +16 -0
  41. source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sqlite.ts +14 -0
  42. source/teaql-ts/examples/natural-messages/fixture/src/teaql-ts.ts +530 -0
  43. source/teaql-ts/examples/natural-messages/fixture/teaql-i18n.json +112 -0
  44. source/teaql-ts/examples/natural-messages/fixture/teaql/checker-model.json +1 -0
  45. source/teaql-ts/examples/natural-messages/fixture/teaql/model-provenance.json +1 -0
  46. source/teaql-ts/examples/natural-messages/fixture/tsconfig.json +12 -0
  47. source/teaql-ts/examples/natural-messages/verify.test.ts +91 -0
  48. source/teaql-ts/examples/order-management/model.xml +13 -0
  49. source/teaql-ts/examples/order-management/package-lock.json +23 -444
  50. source/teaql-ts/examples/order-management/package.json +4 -0
source/teaql-ts/examples/fix-e-alignment/generated/src/generated-bootstrap.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserContext, decimal, long, localTime } from './teaql-ts';
2
+ import { Q } from './generated/Q';
3
+ import { Tenant } from './generated/models/Tenant';
4
+
5
+ /** @internal Generated typed Mutation bootstrap; never call from application code. */
6
+ export async function ensureGeneratedBootstrap(context: UserContext): Promise<void> {
7
+ let domainRoot = (await Q.tenants().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
8
+ if (!domainRoot) {
9
+ domainRoot = Tenant.teaqlBootstrapNew(context, '1');
10
+ domainRoot.updateName("Tenant Name");
11
+ await domainRoot.auditAs('create generated Domain Root Tenant').save(context);
12
+ }
13
+ context.withActiveRoot({ entity: 'Tenant', id: domainRoot.id! });
14
+ }
source/teaql-ts/examples/fix-e-alignment/generated/src/generated-search-models.ts ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GeneratedSearchModel } from "teaql-ts";
2
+
3
+ /** Generated trusted naming/type metadata. No query execution or authorization lives here. */
4
+ export const GENERATED_SEARCH_MODELS: Readonly<Record<string, GeneratedSearchModel>> = Object.freeze({
5
+ "Tenant": Object.freeze({
6
+ fields: Object.freeze({
7
+ "id": "integer" as const,
8
+ "name": "string" as const,
9
+ "version": "integer" as const,
10
+ }),
11
+ queryFields: Object.freeze({
12
+ "id": "id",
13
+ "name": "name",
14
+ "version": "version",
15
+ }),
16
+ relations: Object.freeze({
17
+ "purchaseOrderList": "PurchaseOrder",
18
+ "orderItemList": "OrderItem",
19
+ }),
20
+ }),
21
+ "PurchaseOrder": Object.freeze({
22
+ fields: Object.freeze({
23
+ "id": "integer" as const,
24
+ "tenant": "integer" as const,
25
+ "contact_phone": "string" as const,
26
+ "contactPhone": "string" as const,
27
+ "internal_note": "string" as const,
28
+ "internalNote": "string" as const,
29
+ "create_time": "timestamp" as const,
30
+ "createTime": "timestamp" as const,
31
+ "update_time": "timestamp" as const,
32
+ "updateTime": "timestamp" as const,
33
+ "version": "integer" as const,
34
+ }),
35
+ queryFields: Object.freeze({
36
+ "id": "id",
37
+ "tenant": "tenant",
38
+ "contact_phone": "contactPhone",
39
+ "contactPhone": "contactPhone",
40
+ "internal_note": "internalNote",
41
+ "internalNote": "internalNote",
42
+ "create_time": "createTime",
43
+ "createTime": "createTime",
44
+ "update_time": "updateTime",
45
+ "updateTime": "updateTime",
46
+ "version": "version",
47
+ }),
48
+ relations: Object.freeze({
49
+ "tenant": "Tenant",
50
+ "orderItemList": "OrderItem",
51
+ }),
52
+ }),
53
+ "OrderItem": Object.freeze({
54
+ fields: Object.freeze({
55
+ "id": "integer" as const,
56
+ "purchase_order": "integer" as const,
57
+ "purchaseOrder": "integer" as const,
58
+ "tenant": "integer" as const,
59
+ "product_name": "string" as const,
60
+ "productName": "string" as const,
61
+ "unit_price": "decimal" as const,
62
+ "unitPrice": "decimal" as const,
63
+ "create_time": "timestamp" as const,
64
+ "createTime": "timestamp" as const,
65
+ "update_time": "timestamp" as const,
66
+ "updateTime": "timestamp" as const,
67
+ "version": "integer" as const,
68
+ }),
69
+ queryFields: Object.freeze({
70
+ "id": "id",
71
+ "purchase_order": "purchaseOrder",
72
+ "purchaseOrder": "purchaseOrder",
73
+ "tenant": "tenant",
74
+ "product_name": "productName",
75
+ "productName": "productName",
76
+ "unit_price": "unitPrice",
77
+ "unitPrice": "unitPrice",
78
+ "create_time": "createTime",
79
+ "createTime": "createTime",
80
+ "update_time": "updateTime",
81
+ "updateTime": "updateTime",
82
+ "version": "version",
83
+ }),
84
+ relations: Object.freeze({
85
+ "purchase_order": "PurchaseOrder",
86
+ "purchaseOrder": "PurchaseOrder",
87
+ "tenant": "Tenant",
88
+ }),
89
+ }),
90
+ });
source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { OrderItem } from '../models/OrderItem';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
+
7
+
8
+
9
+ export class OrderItemRequest {
10
+ private query: SelectQuery;
11
+ private filters: any[] = [];
12
+ private _purpose: string | undefined;
13
+ private _comment: string | undefined;
14
+ private _pageCountAlias: string | undefined;
15
+ private _pageCountMethod: "count" | "countAs" | undefined;
16
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
17
+
18
+ constructor(minimal = false) {
19
+ this.query = new SelectQuery("OrderItem");
20
+ this.filters.push({ version: { "$gte": 1 } });
21
+ if (minimal) {
22
+ this.selectId();
23
+ this.selectVersion();
24
+ }
25
+ else this.selectSelfFields();
26
+ }
27
+
28
+ get entityName(): "OrderItem" {
29
+ return "OrderItem";
30
+ }
31
+
32
+ comment(c: string): this {
33
+ this.query.comment(c);
34
+ this._comment = c;
35
+ return this;
36
+ }
37
+
38
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
39
+ const base = this.query.clone();
40
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
41
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
42
+ this.query = merged.query as SelectQuery;
43
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
44
+ this._dynamicSearchWarnings.push(...merged.warnings);
45
+ return this;
46
+ }
47
+
48
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
49
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
50
+ }
51
+
52
+ purpose(p: string): ExecutableOrderItemRequest {
53
+ this.query.purpose(p);
54
+ this._purpose = p;
55
+ return new ExecutableOrderItemRequest(
56
+ (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)),
57
+ (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)),
58
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
59
+ () => this.limit(1),
60
+ (c) => this.comment(c),
61
+ () => this.ensureIntent());
62
+ }
63
+
64
+ optimizeForContinuousPageFetch(): this {
65
+ this.query.optimizeForContinuousPageFetch();
66
+ return this;
67
+ }
68
+
69
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
70
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
71
+ return this;
72
+ }
73
+
74
+ optimizePaginationWithIdSet(): this {
75
+ this.query.optimizePaginationWithIdSet();
76
+ return this;
77
+ }
78
+
79
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
80
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
81
+ return this;
82
+ }
83
+
84
+ topNProbeParentThreshold(threshold: number): this {
85
+ this.query.topNProbeParentThreshold(threshold);
86
+ return this;
87
+ }
88
+
89
+ limit(n: number): this {
90
+ this.query.limit(n);
91
+ return this;
92
+ }
93
+
94
+ offset(n: number): this {
95
+ this.query.offset(n);
96
+ return this;
97
+ }
98
+
99
+ toQuery(): SelectQuery {
100
+ if (this.filters.length > 0) {
101
+ this.query.filter({ "$and": this.filters });
102
+ }
103
+ return this.query;
104
+ }
105
+
106
+ withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
+ this.filters = this.filters.filter(filter => !("version" in filter));
109
+ return this;
110
+ }
111
+
112
+ deletedRowsOnly(): this {
113
+ this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
+ this.filters.push({ version: { "$lte": -1 } });
116
+ return this;
117
+ }
118
+
119
+ selectSelfFields(): this {
120
+ this.query.select(["id", "purchaseOrder", "tenant", "productName", "unitPrice", "createTime", "updateTime", "version"]);
121
+ return this;
122
+ }
123
+
124
+ selectId(): this {
125
+ this.query.select(["id"]);
126
+ return this;
127
+ }
128
+
129
+
130
+
131
+ selectProductName(): this {
132
+ this.query.select(["productName"]);
133
+ return this;
134
+ }
135
+
136
+ selectUnitPrice(): this {
137
+ this.query.select(["unitPrice"]);
138
+ return this;
139
+ }
140
+
141
+ selectCreateTime(): this {
142
+ this.query.select(["createTime"]);
143
+ return this;
144
+ }
145
+
146
+ selectUpdateTime(): this {
147
+ this.query.select(["updateTime"]);
148
+ return this;
149
+ }
150
+
151
+ selectVersion(): this {
152
+ this.query.select(["version"]);
153
+ return this;
154
+ }
155
+
156
+
157
+ selectPurchaseOrderWith(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
158
+ this.query.select(["purchaseOrder"]);
159
+ this.query.relationQuery(
160
+ "purchaseOrder", request.toQuery(), "purchaseOrder", "id", false,
161
+ { kind: "relation-select", method: "selectPurchaseOrderWith", relation: "purchaseOrder" });
162
+ return this;
163
+ }
164
+ selectTenantWith(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
165
+ this.query.select(["tenant"]);
166
+ this.query.relationQuery(
167
+ "tenant", request.toQuery(), "tenant", "id", false,
168
+ { kind: "relation-select", method: "selectTenantWith", relation: "tenant" });
169
+ return this;
170
+ }
171
+
172
+ withPurchaseOrderMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
173
+ this.filters.push({
174
+ "purchaseOrder": {
175
+ "$inSubquery": { query: request.toQuery(), field: "id" },
176
+ },
177
+ });
178
+ return this;
179
+ }
180
+
181
+ withoutPurchaseOrderMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
182
+ this.filters.push({
183
+ "purchaseOrder": {
184
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
185
+ },
186
+ });
187
+ return this;
188
+ }
189
+ withTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
190
+ this.filters.push({
191
+ "tenant": {
192
+ "$inSubquery": { query: request.toQuery(), field: "id" },
193
+ },
194
+ });
195
+ return this;
196
+ }
197
+
198
+ withoutTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
199
+ this.filters.push({
200
+ "tenant": {
201
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
202
+ },
203
+ });
204
+ return this;
205
+ }
206
+
207
+
208
+
209
+
210
+ withIdIs(val: string): this {
211
+ this.filters.push({ "id": { "$eq": val } });
212
+ return this;
213
+ }
214
+
215
+ withIdIsNot(val: string): this {
216
+ this.filters.push({ "id": { "$ne": val } });
217
+ return this;
218
+ }
219
+
220
+ withIdIn(...vals: string[]): this {
221
+ this.filters.push({ "id": { "$in": vals } });
222
+ return this;
223
+ }
224
+
225
+ withIdNotIn(...vals: string[]): this {
226
+ this.filters.push({ "id": { "$notIn": vals } });
227
+ return this;
228
+ }
229
+
230
+ withIdGreaterThan(val: string): this {
231
+ this.filters.push({ "id": { "$gt": val } });
232
+ return this;
233
+ }
234
+
235
+ withIdGreaterThanOrEqualTo(val: string): this {
236
+ this.filters.push({ "id": { "$gte": val } });
237
+ return this;
238
+ }
239
+
240
+ withIdLessThan(val: string): this {
241
+ this.filters.push({ "id": { "$lt": val } });
242
+ return this;
243
+ }
244
+
245
+ withIdLessThanOrEqualTo(val: string): this {
246
+ this.filters.push({ "id": { "$lte": val } });
247
+ return this;
248
+ }
249
+
250
+ withIdBetween(lower: string, upper: string): this {
251
+ this.filters.push({ "id": { "$between": [lower, upper] } });
252
+ return this;
253
+ }
254
+
255
+ withIdIsKnown(): this {
256
+ this.filters.push({ "id": { "$isNull": false } });
257
+ return this;
258
+ }
259
+
260
+ withIdIsUnknown(): this {
261
+ this.filters.push({ "id": { "$isNull": true } });
262
+ return this;
263
+ }
264
+
265
+ filterByPurchaseOrder(val: any): this {
266
+ this.filters.push({ "purchaseOrder": { "$eq": val } });
267
+ return this;
268
+ }
269
+
270
+ filterByPurchaseOrderIn(...vals: any[]): this {
271
+ this.filters.push({ "purchaseOrder": { "$in": vals } });
272
+ return this;
273
+ }
274
+
275
+ withPurchaseOrderIsKnown(): this {
276
+ this.filters.push({ "purchaseOrder": { "$isNull": false } });
277
+ return this;
278
+ }
279
+
280
+ withPurchaseOrderIsUnknown(): this {
281
+ this.filters.push({ "purchaseOrder": { "$isNull": true } });
282
+ return this;
283
+ }
284
+
285
+ filterByTenant(val: any): this {
286
+ this.filters.push({ "tenant": { "$eq": val } });
287
+ return this;
288
+ }
289
+
290
+ filterByTenantIn(...vals: any[]): this {
291
+ this.filters.push({ "tenant": { "$in": vals } });
292
+ return this;
293
+ }
294
+
295
+ withTenantIsKnown(): this {
296
+ this.filters.push({ "tenant": { "$isNull": false } });
297
+ return this;
298
+ }
299
+
300
+ withTenantIsUnknown(): this {
301
+ this.filters.push({ "tenant": { "$isNull": true } });
302
+ return this;
303
+ }
304
+
305
+ withProductNameContaining(val: string): this {
306
+ this.filters.push({ "productName": { "$contains": val } });
307
+ return this;
308
+ }
309
+
310
+ withProductNameIs(val: string): this {
311
+ this.filters.push({ "productName": { "$eq": val } });
312
+ return this;
313
+ }
314
+
315
+ withProductNameIsNot(val: string): this {
316
+ this.filters.push({ "productName": { "$ne": val } });
317
+ return this;
318
+ }
319
+
320
+ withProductNameIn(...vals: string[]): this {
321
+ this.filters.push({ "productName": { "$in": vals } });
322
+ return this;
323
+ }
324
+
325
+ withProductNameNotIn(...vals: string[]): this {
326
+ this.filters.push({ "productName": { "$notIn": vals } });
327
+ return this;
328
+ }
329
+
330
+ withProductNameGreaterThan(val: string): this {
331
+ this.filters.push({ "productName": { "$gt": val } });
332
+ return this;
333
+ }
334
+
335
+ withProductNameGreaterThanOrEqualTo(val: string): this {
336
+ this.filters.push({ "productName": { "$gte": val } });
337
+ return this;
338
+ }
339
+
340
+ withProductNameLessThan(val: string): this {
341
+ this.filters.push({ "productName": { "$lt": val } });
342
+ return this;
343
+ }
344
+
345
+ withProductNameLessThanOrEqualTo(val: string): this {
346
+ this.filters.push({ "productName": { "$lte": val } });
347
+ return this;
348
+ }
349
+
350
+ withProductNameBetween(lower: string, upper: string): this {
351
+ this.filters.push({ "productName": { "$between": [lower, upper] } });
352
+ return this;
353
+ }
354
+
355
+ withProductNameIsKnown(): this {
356
+ this.filters.push({ "productName": { "$isNull": false } });
357
+ return this;
358
+ }
359
+
360
+ withProductNameIsUnknown(): this {
361
+ this.filters.push({ "productName": { "$isNull": true } });
362
+ return this;
363
+ }
364
+ withProductNameNotContaining(val: string): this {
365
+ this.filters.push({ "productName": { "$notContains": val } });
366
+ return this;
367
+ }
368
+
369
+ withProductNameStartingWith(val: string): this {
370
+ this.filters.push({ "productName": { "$startsWith": val } });
371
+ return this;
372
+ }
373
+
374
+ withProductNameNotStartingWith(val: string): this {
375
+ this.filters.push({ "productName": { "$notStartsWith": val } });
376
+ return this;
377
+ }
378
+
379
+ withProductNameEndingWith(val: string): this {
380
+ this.filters.push({ "productName": { "$endsWith": val } });
381
+ return this;
382
+ }
383
+
384
+ withProductNameNotEndingWith(val: string): this {
385
+ this.filters.push({ "productName": { "$notEndsWith": val } });
386
+ return this;
387
+ }
388
+
389
+ withProductNameSoundingLike(val: string): this {
390
+ this.filters.push({ "productName": { "$soundLike": val } });
391
+ return this;
392
+ }
393
+
394
+ withUnitPriceIs(val: Decimal): this {
395
+ this.filters.push({ "unitPrice": { "$eq": val } });
396
+ return this;
397
+ }
398
+
399
+ withUnitPriceIsNot(val: Decimal): this {
400
+ this.filters.push({ "unitPrice": { "$ne": val } });
401
+ return this;
402
+ }
403
+
404
+ withUnitPriceIn(...vals: Decimal[]): this {
405
+ this.filters.push({ "unitPrice": { "$in": vals } });
406
+ return this;
407
+ }
408
+
409
+ withUnitPriceNotIn(...vals: Decimal[]): this {
410
+ this.filters.push({ "unitPrice": { "$notIn": vals } });
411
+ return this;
412
+ }
413
+
414
+ withUnitPriceGreaterThan(val: Decimal): this {
415
+ this.filters.push({ "unitPrice": { "$gt": val } });
416
+ return this;
417
+ }
418
+
419
+ withUnitPriceGreaterThanOrEqualTo(val: Decimal): this {
420
+ this.filters.push({ "unitPrice": { "$gte": val } });
421
+ return this;
422
+ }
423
+
424
+ withUnitPriceLessThan(val: Decimal): this {
425
+ this.filters.push({ "unitPrice": { "$lt": val } });
426
+ return this;
427
+ }
428
+
429
+ withUnitPriceLessThanOrEqualTo(val: Decimal): this {
430
+ this.filters.push({ "unitPrice": { "$lte": val } });
431
+ return this;
432
+ }
433
+
434
+ withUnitPriceBetween(lower: Decimal, upper: Decimal): this {
435
+ this.filters.push({ "unitPrice": { "$between": [lower, upper] } });
436
+ return this;
437
+ }
438
+
439
+ withUnitPriceIsKnown(): this {
440
+ this.filters.push({ "unitPrice": { "$isNull": false } });
441
+ return this;
442
+ }
443
+
444
+ withUnitPriceIsUnknown(): this {
445
+ this.filters.push({ "unitPrice": { "$isNull": true } });
446
+ return this;
447
+ }
448
+
449
+ withCreateTimeIs(val: unknown): this {
450
+ this.filters.push({ "createTime": { "$eq": val } });
451
+ return this;
452
+ }
453
+
454
+ withCreateTimeIsNot(val: unknown): this {
455
+ this.filters.push({ "createTime": { "$ne": val } });
456
+ return this;
457
+ }
458
+
459
+ withCreateTimeIn(...vals: unknown[]): this {
460
+ this.filters.push({ "createTime": { "$in": vals } });
461
+ return this;
462
+ }
463
+
464
+ withCreateTimeNotIn(...vals: unknown[]): this {
465
+ this.filters.push({ "createTime": { "$notIn": vals } });
466
+ return this;
467
+ }
468
+
469
+ withCreateTimeGreaterThan(val: unknown): this {
470
+ this.filters.push({ "createTime": { "$gt": val } });
471
+ return this;
472
+ }
473
+
474
+ withCreateTimeGreaterThanOrEqualTo(val: unknown): this {
475
+ this.filters.push({ "createTime": { "$gte": val } });
476
+ return this;
477
+ }
478
+
479
+ withCreateTimeLessThan(val: unknown): this {
480
+ this.filters.push({ "createTime": { "$lt": val } });
481
+ return this;
482
+ }
483
+
484
+ withCreateTimeLessThanOrEqualTo(val: unknown): this {
485
+ this.filters.push({ "createTime": { "$lte": val } });
486
+ return this;
487
+ }
488
+
489
+ withCreateTimeBetween(lower: unknown, upper: unknown): this {
490
+ this.filters.push({ "createTime": { "$between": [lower, upper] } });
491
+ return this;
492
+ }
493
+
494
+ withCreateTimeIsKnown(): this {
495
+ this.filters.push({ "createTime": { "$isNull": false } });
496
+ return this;
497
+ }
498
+
499
+ withCreateTimeIsUnknown(): this {
500
+ this.filters.push({ "createTime": { "$isNull": true } });
501
+ return this;
502
+ }
503
+
504
+ withUpdateTimeIs(val: unknown): this {
505
+ this.filters.push({ "updateTime": { "$eq": val } });
506
+ return this;
507
+ }
508
+
509
+ withUpdateTimeIsNot(val: unknown): this {
510
+ this.filters.push({ "updateTime": { "$ne": val } });
511
+ return this;
512
+ }
513
+
514
+ withUpdateTimeIn(...vals: unknown[]): this {
515
+ this.filters.push({ "updateTime": { "$in": vals } });
516
+ return this;
517
+ }
518
+
519
+ withUpdateTimeNotIn(...vals: unknown[]): this {
520
+ this.filters.push({ "updateTime": { "$notIn": vals } });
521
+ return this;
522
+ }
523
+
524
+ withUpdateTimeGreaterThan(val: unknown): this {
525
+ this.filters.push({ "updateTime": { "$gt": val } });
526
+ return this;
527
+ }
528
+
529
+ withUpdateTimeGreaterThanOrEqualTo(val: unknown): this {
530
+ this.filters.push({ "updateTime": { "$gte": val } });
531
+ return this;
532
+ }
533
+
534
+ withUpdateTimeLessThan(val: unknown): this {
535
+ this.filters.push({ "updateTime": { "$lt": val } });
536
+ return this;
537
+ }
538
+
539
+ withUpdateTimeLessThanOrEqualTo(val: unknown): this {
540
+ this.filters.push({ "updateTime": { "$lte": val } });
541
+ return this;
542
+ }
543
+
544
+ withUpdateTimeBetween(lower: unknown, upper: unknown): this {
545
+ this.filters.push({ "updateTime": { "$between": [lower, upper] } });
546
+ return this;
547
+ }
548
+
549
+ withUpdateTimeIsKnown(): this {
550
+ this.filters.push({ "updateTime": { "$isNull": false } });
551
+ return this;
552
+ }
553
+
554
+ withUpdateTimeIsUnknown(): this {
555
+ this.filters.push({ "updateTime": { "$isNull": true } });
556
+ return this;
557
+ }
558
+
559
+ withVersionIs(val: unknown): this {
560
+ this.filters.push({ "version": { "$eq": val } });
561
+ return this;
562
+ }
563
+
564
+ withVersionIsNot(val: unknown): this {
565
+ this.filters.push({ "version": { "$ne": val } });
566
+ return this;
567
+ }
568
+
569
+ withVersionIn(...vals: unknown[]): this {
570
+ this.filters.push({ "version": { "$in": vals } });
571
+ return this;
572
+ }
573
+
574
+ withVersionNotIn(...vals: unknown[]): this {
575
+ this.filters.push({ "version": { "$notIn": vals } });
576
+ return this;
577
+ }
578
+
579
+ withVersionGreaterThan(val: unknown): this {
580
+ this.filters.push({ "version": { "$gt": val } });
581
+ return this;
582
+ }
583
+
584
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
585
+ this.filters.push({ "version": { "$gte": val } });
586
+ return this;
587
+ }
588
+
589
+ withVersionLessThan(val: unknown): this {
590
+ this.filters.push({ "version": { "$lt": val } });
591
+ return this;
592
+ }
593
+
594
+ withVersionLessThanOrEqualTo(val: unknown): this {
595
+ this.filters.push({ "version": { "$lte": val } });
596
+ return this;
597
+ }
598
+
599
+ withVersionBetween(lower: unknown, upper: unknown): this {
600
+ this.filters.push({ "version": { "$between": [lower, upper] } });
601
+ return this;
602
+ }
603
+
604
+ withVersionIsKnown(): this {
605
+ this.filters.push({ "version": { "$isNull": false } });
606
+ return this;
607
+ }
608
+
609
+ withVersionIsUnknown(): this {
610
+ this.filters.push({ "version": { "$isNull": true } });
611
+ return this;
612
+ }
613
+
614
+ orderByIdAscending(): this {
615
+ this.query.orderBy("id", "asc");
616
+ return this;
617
+ }
618
+
619
+ orderByIdDescending(): this {
620
+ this.query.orderBy("id", "desc");
621
+ return this;
622
+ }
623
+
624
+
625
+
626
+ orderByProductNameAscending(): this {
627
+ this.query.orderBy("productName", "asc");
628
+ return this;
629
+ }
630
+
631
+ orderByProductNameDescending(): this {
632
+ this.query.orderBy("productName", "desc");
633
+ return this;
634
+ }
635
+
636
+ orderByUnitPriceAscending(): this {
637
+ this.query.orderBy("unitPrice", "asc");
638
+ return this;
639
+ }
640
+
641
+ orderByUnitPriceDescending(): this {
642
+ this.query.orderBy("unitPrice", "desc");
643
+ return this;
644
+ }
645
+
646
+ orderByCreateTimeAscending(): this {
647
+ this.query.orderBy("createTime", "asc");
648
+ return this;
649
+ }
650
+
651
+ orderByCreateTimeDescending(): this {
652
+ this.query.orderBy("createTime", "desc");
653
+ return this;
654
+ }
655
+
656
+ orderByUpdateTimeAscending(): this {
657
+ this.query.orderBy("updateTime", "asc");
658
+ return this;
659
+ }
660
+
661
+ orderByUpdateTimeDescending(): this {
662
+ this.query.orderBy("updateTime", "desc");
663
+ return this;
664
+ }
665
+
666
+ orderByVersionAscending(): this {
667
+ this.query.orderBy("version", "asc");
668
+ return this;
669
+ }
670
+
671
+ orderByVersionDescending(): this {
672
+ this.query.orderBy("version", "desc");
673
+ return this;
674
+ }
675
+
676
+
677
+ // --- Aggregations ---
678
+ count(): this {
679
+ this.query.aggregate("Count", "id", "count");
680
+ this._pageCountAlias = "count";
681
+ this._pageCountMethod = "count";
682
+ return this;
683
+ }
684
+
685
+ countAs(retName: string): this {
686
+ this.query.aggregate("Count", "id", retName);
687
+ this._pageCountAlias = retName;
688
+ this._pageCountMethod = "countAs";
689
+ return this;
690
+ }
691
+
692
+ minUnitPrice(): this {
693
+ return this.minUnitPriceAs("minOfUnitPrice");
694
+ }
695
+
696
+ minUnitPriceAs(retName: string): this {
697
+ this.query.aggregate("min", "unitPrice", retName);
698
+ return this;
699
+ }
700
+ maxUnitPrice(): this {
701
+ return this.maxUnitPriceAs("maxOfUnitPrice");
702
+ }
703
+
704
+ maxUnitPriceAs(retName: string): this {
705
+ this.query.aggregate("max", "unitPrice", retName);
706
+ return this;
707
+ }
708
+ sumUnitPrice(): this {
709
+ return this.sumUnitPriceAs("sumOfUnitPrice");
710
+ }
711
+
712
+ sumUnitPriceAs(retName: string): this {
713
+ this.query.aggregate("sum", "unitPrice", retName);
714
+ return this;
715
+ }
716
+ avgUnitPrice(): this {
717
+ return this.avgUnitPriceAs("avgOfUnitPrice");
718
+ }
719
+
720
+ avgUnitPriceAs(retName: string): this {
721
+ this.query.aggregate("avg", "unitPrice", retName);
722
+ return this;
723
+ }
724
+ standardDeviationUnitPrice(): this {
725
+ return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice");
726
+ }
727
+
728
+ standardDeviationUnitPriceAs(retName: string): this {
729
+ this.query.aggregate("stddev", "unitPrice", retName);
730
+ return this;
731
+ }
732
+ squareRootOfPopulationStandardDeviationUnitPrice(): this {
733
+ return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice");
734
+ }
735
+
736
+ squareRootOfPopulationStandardDeviationUnitPriceAs(retName: string): this {
737
+ this.query.aggregate("stddev_pop", "unitPrice", retName);
738
+ return this;
739
+ }
740
+ sampleVarianceUnitPrice(): this {
741
+ return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice");
742
+ }
743
+
744
+ sampleVarianceUnitPriceAs(retName: string): this {
745
+ this.query.aggregate("var_samp", "unitPrice", retName);
746
+ return this;
747
+ }
748
+ samplePopulationVarianceUnitPrice(): this {
749
+ return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice");
750
+ }
751
+
752
+ samplePopulationVarianceUnitPriceAs(retName: string): this {
753
+ this.query.aggregate("var_pop", "unitPrice", retName);
754
+ return this;
755
+ }
756
+
757
+ // --- Group By ---
758
+ groupById(): this {
759
+ this.query.groupBy("id");
760
+ return this;
761
+ }
762
+
763
+ groupByIdAs(retName: string): this {
764
+ this.query.groupBy("id", retName);
765
+ return this;
766
+ }
767
+ groupByPurchaseOrder(): this {
768
+ this.query.groupBy("purchaseOrder");
769
+ return this;
770
+ }
771
+
772
+ groupByPurchaseOrderAs(retName: string): this {
773
+ this.query.groupBy("purchaseOrder", retName);
774
+ return this;
775
+ }
776
+ groupByTenant(): this {
777
+ this.query.groupBy("tenant");
778
+ return this;
779
+ }
780
+
781
+ groupByTenantAs(retName: string): this {
782
+ this.query.groupBy("tenant", retName);
783
+ return this;
784
+ }
785
+ groupByProductName(): this {
786
+ this.query.groupBy("productName");
787
+ return this;
788
+ }
789
+
790
+ groupByProductNameAs(retName: string): this {
791
+ this.query.groupBy("productName", retName);
792
+ return this;
793
+ }
794
+ groupByUnitPrice(): this {
795
+ this.query.groupBy("unitPrice");
796
+ return this;
797
+ }
798
+
799
+ groupByUnitPriceAs(retName: string): this {
800
+ this.query.groupBy("unitPrice", retName);
801
+ return this;
802
+ }
803
+ groupByCreateTime(): this {
804
+ this.query.groupBy("createTime");
805
+ return this;
806
+ }
807
+
808
+ groupByCreateTimeAs(retName: string): this {
809
+ this.query.groupBy("createTime", retName);
810
+ return this;
811
+ }
812
+ groupByUpdateTime(): this {
813
+ this.query.groupBy("updateTime");
814
+ return this;
815
+ }
816
+
817
+ groupByUpdateTimeAs(retName: string): this {
818
+ this.query.groupBy("updateTime", retName);
819
+ return this;
820
+ }
821
+ groupByVersion(): this {
822
+ this.query.groupBy("version");
823
+ return this;
824
+ }
825
+
826
+ groupByVersionAs(retName: string): this {
827
+ this.query.groupBy("version", retName);
828
+ return this;
829
+ }
830
+
831
+ // --- Facets ---
832
+ facetByPurchaseOrderAs(
833
+ facetName: string,
834
+ request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery },
835
+ includeAllFacets = true,
836
+ ): this {
837
+ this.query.facetBy(facetName, "purchaseOrder", request, includeAllFacets,
838
+ { kind: "facet", method: "facetByPurchaseOrderAs", relation: "purchaseOrder", alias: facetName });
839
+ return this;
840
+ }
841
+
842
+ facetByTenantAs(
843
+ facetName: string,
844
+ request: { readonly entityName: "Tenant"; toQuery(): SelectQuery },
845
+ includeAllFacets = true,
846
+ ): this {
847
+ this.query.facetBy(facetName, "tenant", request, includeAllFacets,
848
+ { kind: "facet", method: "facetByTenantAs", relation: "tenant", alias: facetName });
849
+ return this;
850
+ }
851
+
852
+
853
+ private async executeForListInternal(context: UserContext): Promise<SmartList<OrderItem>> {
854
+ this.ensureIntent();
855
+ if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context);
856
+ if (this.filters.length > 0) {
857
+ this.query.filter({ "$and": this.filters });
858
+ }
859
+
860
+ const service = context.requireResource<TeaQLDataService>("dataService");
861
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
862
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
863
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
864
+ row instanceof OrderItem
865
+ ? row
866
+ : OrderItem.fromRecord(row as Record<string, unknown>, new EntityRoot()));
867
+ const result = new SmartList<OrderItem>(data);
868
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
869
+
870
+ if (this.query.facets.length > 0) {
871
+ result.facets = await executeRelationFacets(
872
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
873
+ }
874
+
875
+ return result;
876
+ }
877
+
878
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
879
+ this.ensureIntent();
880
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
881
+ const service = context.requireResource<TeaQLDataService>("dataService");
882
+ return new SmartList<Record<string, unknown>>(
883
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
884
+ }
885
+
886
+ private async executeCountedListInternal(
887
+ context: UserContext,
888
+ ): Promise<SmartList<OrderItem>> {
889
+ this.ensureIntent();
890
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
891
+ const service = context.requireResource<TeaQLDataService>("dataService");
892
+ const preparedQuery = context.prepareQuery(this.query);
893
+ const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined;
894
+ const countOperation = { kind: "named-count" as const,
895
+ method: this._pageCountMethod ?? "count",
896
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
897
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
898
+ preparedQuery, this._pageCountAlias, countOperation);
899
+ const pageQuery = preparedQuery.clone();
900
+ // A page count describes the full filtered set, not an aggregate-only page row.
901
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
902
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
903
+ const rows = await service.executeQuery(pageQuery);
904
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
905
+ ? context.idSetPaginationCount!
906
+ : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation));
907
+ const data = new SmartList(rows.map((row: unknown) =>
908
+ row instanceof OrderItem
909
+ ? row
910
+ : OrderItem.fromRecord(row as Record<string, unknown>, new EntityRoot())));
911
+ data.totalCount = totalCount;
912
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
913
+ if (this.query.facets.length > 0) {
914
+ data.facets = await executeRelationFacets(
915
+ service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets);
916
+ }
917
+ return data;
918
+ }
919
+
920
+ private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<OrderItem> {
921
+ this.ensureIntent();
922
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
923
+ const service = context.requireResource<TeaQLDataService>("dataService");
924
+ const preparedQuery = context.prepareQuery(this.query);
925
+ // Prepare Context and capture the runtime request before returning a lazy iterator.
926
+ const chunks = service.executeForStream(preparedQuery, chunkSize);
927
+ return (async function* () {
928
+ for await (const chunk of chunks) {
929
+ for (const entity of chunk) {
930
+ yield entity instanceof OrderItem
931
+ ? entity
932
+ : OrderItem.fromRecord(entity as Record<string, unknown>, new EntityRoot());
933
+ }
934
+ }
935
+ })();
936
+ }
937
+
938
+ private ensureIntent(): void {
939
+ // Runtime owns validation, Unicode whitespace rules and typed diagnostics.
940
+ new QueryIntent(this._comment, this._purpose);
941
+ }
942
+
943
+ }
944
+
945
+ export class ExecutableOrderItemRequest {
946
+ constructor(
947
+ private readonly execute: (context: UserContext) => Promise<SmartList<OrderItem>>,
948
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
949
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<OrderItem>,
950
+ private readonly limitOne: () => void,
951
+ private readonly addComment: (comment: string) => void,
952
+ private readonly ensureIntent: () => void,
953
+ ) {}
954
+
955
+ comment(c: string): this {
956
+ this.addComment(c);
957
+ return this;
958
+ }
959
+
960
+ async newEntity(context: UserContext): Promise<OrderItem> {
961
+ this.ensureIntent();
962
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
963
+ return OrderItem.teaqlCreate(context);
964
+ }
965
+
966
+ executeForList(context: UserContext): Promise<SmartList<OrderItem>> {
967
+ this.ensureIntent();
968
+ return this.execute(context);
969
+ }
970
+
971
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
972
+ this.ensureIntent();
973
+ return this.executeRows(context);
974
+ }
975
+
976
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<OrderItem> {
977
+ this.ensureIntent();
978
+ return this.stream(context, chunkSize);
979
+ }
980
+
981
+ async executeForOne(context: UserContext): Promise<OrderItem | undefined> {
982
+ this.limitOne();
983
+ return (await this.executeForList(context))[0];
984
+ }
985
+ }
source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { PurchaseOrder } from '../models/PurchaseOrder';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
+
7
+
8
+
9
+ export class PurchaseOrderRequest {
10
+ private query: SelectQuery;
11
+ private filters: any[] = [];
12
+ private _purpose: string | undefined;
13
+ private _comment: string | undefined;
14
+ private _pageCountAlias: string | undefined;
15
+ private _pageCountMethod: "count" | "countAs" | undefined;
16
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
17
+
18
+ constructor(minimal = false) {
19
+ this.query = new SelectQuery("PurchaseOrder");
20
+ this.filters.push({ version: { "$gte": 1 } });
21
+ if (minimal) {
22
+ this.selectId();
23
+ this.selectVersion();
24
+ }
25
+ else this.selectSelfFields();
26
+ }
27
+
28
+ get entityName(): "PurchaseOrder" {
29
+ return "PurchaseOrder";
30
+ }
31
+
32
+ comment(c: string): this {
33
+ this.query.comment(c);
34
+ this._comment = c;
35
+ return this;
36
+ }
37
+
38
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
39
+ const base = this.query.clone();
40
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
41
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
42
+ this.query = merged.query as SelectQuery;
43
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
44
+ this._dynamicSearchWarnings.push(...merged.warnings);
45
+ return this;
46
+ }
47
+
48
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
49
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
50
+ }
51
+
52
+ purpose(p: string): ExecutablePurchaseOrderRequest {
53
+ this.query.purpose(p);
54
+ this._purpose = p;
55
+ return new ExecutablePurchaseOrderRequest(
56
+ (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)),
57
+ (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)),
58
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
59
+ () => this.limit(1),
60
+ (c) => this.comment(c),
61
+ () => this.ensureIntent());
62
+ }
63
+
64
+ optimizeForContinuousPageFetch(): this {
65
+ this.query.optimizeForContinuousPageFetch();
66
+ return this;
67
+ }
68
+
69
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
70
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
71
+ return this;
72
+ }
73
+
74
+ optimizePaginationWithIdSet(): this {
75
+ this.query.optimizePaginationWithIdSet();
76
+ return this;
77
+ }
78
+
79
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
80
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
81
+ return this;
82
+ }
83
+
84
+ topNProbeParentThreshold(threshold: number): this {
85
+ this.query.topNProbeParentThreshold(threshold);
86
+ return this;
87
+ }
88
+
89
+ limit(n: number): this {
90
+ this.query.limit(n);
91
+ return this;
92
+ }
93
+
94
+ offset(n: number): this {
95
+ this.query.offset(n);
96
+ return this;
97
+ }
98
+
99
+ toQuery(): SelectQuery {
100
+ if (this.filters.length > 0) {
101
+ this.query.filter({ "$and": this.filters });
102
+ }
103
+ return this.query;
104
+ }
105
+
106
+ withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
+ this.filters = this.filters.filter(filter => !("version" in filter));
109
+ return this;
110
+ }
111
+
112
+ deletedRowsOnly(): this {
113
+ this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
+ this.filters.push({ version: { "$lte": -1 } });
116
+ return this;
117
+ }
118
+
119
+ selectSelfFields(): this {
120
+ this.query.select(["id", "tenant", "contactPhone", "internalNote", "createTime", "updateTime", "version"]);
121
+ return this;
122
+ }
123
+
124
+ selectId(): this {
125
+ this.query.select(["id"]);
126
+ return this;
127
+ }
128
+
129
+
130
+ selectContactPhone(): this {
131
+ this.query.select(["contactPhone"]);
132
+ return this;
133
+ }
134
+
135
+ selectInternalNote(): this {
136
+ this.query.select(["internalNote"]);
137
+ return this;
138
+ }
139
+
140
+ selectCreateTime(): this {
141
+ this.query.select(["createTime"]);
142
+ return this;
143
+ }
144
+
145
+ selectUpdateTime(): this {
146
+ this.query.select(["updateTime"]);
147
+ return this;
148
+ }
149
+
150
+ selectVersion(): this {
151
+ this.query.select(["version"]);
152
+ return this;
153
+ }
154
+
155
+
156
+ selectTenantWith(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
157
+ this.query.select(["tenant"]);
158
+ this.query.relationQuery(
159
+ "tenant", request.toQuery(), "tenant", "id", false,
160
+ { kind: "relation-select", method: "selectTenantWith", relation: "tenant" });
161
+ return this;
162
+ }
163
+
164
+ withTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
165
+ this.filters.push({
166
+ "tenant": {
167
+ "$inSubquery": { query: request.toQuery(), field: "id" },
168
+ },
169
+ });
170
+ return this;
171
+ }
172
+
173
+ withoutTenantMatching(request: { readonly entityName: "Tenant"; toQuery(): SelectQuery }): this {
174
+ this.filters.push({
175
+ "tenant": {
176
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
177
+ },
178
+ });
179
+ return this;
180
+ }
181
+
182
+ selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
183
+ this.query.relationQuery(
184
+ "orderItemList", request.toQuery(), "id", "purchaseOrder", true,
185
+ { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" });
186
+ return this;
187
+ }
188
+
189
+ haveOrderItems(): this {
190
+ return this.withOrderItemListMatching({
191
+ entityName: "OrderItem",
192
+ toQuery: () => new SelectQuery("OrderItem"),
193
+ });
194
+ }
195
+
196
+ haveNoOrderItems(): this {
197
+ return this.withoutOrderItemListMatching({
198
+ entityName: "OrderItem",
199
+ toQuery: () => new SelectQuery("OrderItem"),
200
+ });
201
+ }
202
+
203
+ withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
204
+ this.filters.push({
205
+ "id": {
206
+ "$inSubquery": {
207
+ query: request.toQuery(), field: "purchaseOrder",
208
+ },
209
+ },
210
+ });
211
+ return this;
212
+ }
213
+
214
+ withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
215
+ this.filters.push({
216
+ "id": {
217
+ "$notInSubquery": {
218
+ query: request.toQuery(), field: "purchaseOrder",
219
+ },
220
+ },
221
+ });
222
+ return this;
223
+ }
224
+
225
+ countOrderItems(): this {
226
+ return this.countOrderItemsAs("countOrderItems");
227
+ }
228
+
229
+ countOrderItemsAs(alias: string): this {
230
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
231
+ this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query });
232
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
233
+ kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias };
234
+ return this;
235
+ }
236
+
237
+ countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
238
+ const query = child.toQuery().clone();
239
+ query.aggregateItems = [];
240
+ query.aggregate("Count", "id", alias);
241
+ this.query.relationAggregate("orderItemList", alias, query, true,
242
+ { kind: "relation-count", method: "countOrderItemsWith", relation: "orderItemList", alias });
243
+ return this;
244
+ }
245
+
246
+ minUnitPriceOfOrderItems(): this {
247
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
248
+ return this.minUnitPriceOfOrderItemsAs(
249
+ "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
250
+ }
251
+
252
+ minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
253
+ const query = child.toQuery().clone();
254
+ query.aggregateItems = [];
255
+ query.aggregate("min", "unitPrice", alias);
256
+ this.query.relationAggregate("orderItemList", alias, query, true,
257
+ { kind: "aggregate", method: "minUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
258
+ return this;
259
+ }
260
+ maxUnitPriceOfOrderItems(): this {
261
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
262
+ return this.maxUnitPriceOfOrderItemsAs(
263
+ "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
264
+ }
265
+
266
+ maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
267
+ const query = child.toQuery().clone();
268
+ query.aggregateItems = [];
269
+ query.aggregate("max", "unitPrice", alias);
270
+ this.query.relationAggregate("orderItemList", alias, query, true,
271
+ { kind: "aggregate", method: "maxUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
272
+ return this;
273
+ }
274
+ sumUnitPriceOfOrderItems(): this {
275
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
276
+ return this.sumUnitPriceOfOrderItemsAs(
277
+ "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
278
+ }
279
+
280
+ sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
281
+ const query = child.toQuery().clone();
282
+ query.aggregateItems = [];
283
+ query.aggregate("sum", "unitPrice", alias);
284
+ this.query.relationAggregate("orderItemList", alias, query, true,
285
+ { kind: "aggregate", method: "sumUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
286
+ return this;
287
+ }
288
+ avgUnitPriceOfOrderItems(): this {
289
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
290
+ return this.avgUnitPriceOfOrderItemsAs(
291
+ "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
292
+ }
293
+
294
+ avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
295
+ const query = child.toQuery().clone();
296
+ query.aggregateItems = [];
297
+ query.aggregate("avg", "unitPrice", alias);
298
+ this.query.relationAggregate("orderItemList", alias, query, true,
299
+ { kind: "aggregate", method: "avgUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
300
+ return this;
301
+ }
302
+ standardDeviationUnitPriceOfOrderItems(): this {
303
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
304
+ return this.standardDeviationUnitPriceOfOrderItemsAs(
305
+ "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
306
+ }
307
+
308
+ standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
309
+ const query = child.toQuery().clone();
310
+ query.aggregateItems = [];
311
+ query.aggregate("stddev", "unitPrice", alias);
312
+ this.query.relationAggregate("orderItemList", alias, query, true,
313
+ { kind: "aggregate", method: "standardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
314
+ return this;
315
+ }
316
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this {
317
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
318
+ return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(
319
+ "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
320
+ }
321
+
322
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
323
+ const query = child.toQuery().clone();
324
+ query.aggregateItems = [];
325
+ query.aggregate("stddev_pop", "unitPrice", alias);
326
+ this.query.relationAggregate("orderItemList", alias, query, true,
327
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
328
+ return this;
329
+ }
330
+ sampleVarianceUnitPriceOfOrderItems(): this {
331
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
332
+ return this.sampleVarianceUnitPriceOfOrderItemsAs(
333
+ "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
334
+ }
335
+
336
+ sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
337
+ const query = child.toQuery().clone();
338
+ query.aggregateItems = [];
339
+ query.aggregate("var_samp", "unitPrice", alias);
340
+ this.query.relationAggregate("orderItemList", alias, query, true,
341
+ { kind: "aggregate", method: "sampleVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
342
+ return this;
343
+ }
344
+ samplePopulationVarianceUnitPriceOfOrderItems(): this {
345
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
346
+ return this.samplePopulationVarianceUnitPriceOfOrderItemsAs(
347
+ "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
348
+ }
349
+
350
+ samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
351
+ const query = child.toQuery().clone();
352
+ query.aggregateItems = [];
353
+ query.aggregate("var_pop", "unitPrice", alias);
354
+ this.query.relationAggregate("orderItemList", alias, query, true,
355
+ { kind: "aggregate", method: "samplePopulationVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
356
+ return this;
357
+ }
358
+
359
+ withIdIs(val: string): this {
360
+ this.filters.push({ "id": { "$eq": val } });
361
+ return this;
362
+ }
363
+
364
+ withIdIsNot(val: string): this {
365
+ this.filters.push({ "id": { "$ne": val } });
366
+ return this;
367
+ }
368
+
369
+ withIdIn(...vals: string[]): this {
370
+ this.filters.push({ "id": { "$in": vals } });
371
+ return this;
372
+ }
373
+
374
+ withIdNotIn(...vals: string[]): this {
375
+ this.filters.push({ "id": { "$notIn": vals } });
376
+ return this;
377
+ }
378
+
379
+ withIdGreaterThan(val: string): this {
380
+ this.filters.push({ "id": { "$gt": val } });
381
+ return this;
382
+ }
383
+
384
+ withIdGreaterThanOrEqualTo(val: string): this {
385
+ this.filters.push({ "id": { "$gte": val } });
386
+ return this;
387
+ }
388
+
389
+ withIdLessThan(val: string): this {
390
+ this.filters.push({ "id": { "$lt": val } });
391
+ return this;
392
+ }
393
+
394
+ withIdLessThanOrEqualTo(val: string): this {
395
+ this.filters.push({ "id": { "$lte": val } });
396
+ return this;
397
+ }
398
+
399
+ withIdBetween(lower: string, upper: string): this {
400
+ this.filters.push({ "id": { "$between": [lower, upper] } });
401
+ return this;
402
+ }
403
+
404
+ withIdIsKnown(): this {
405
+ this.filters.push({ "id": { "$isNull": false } });
406
+ return this;
407
+ }
408
+
409
+ withIdIsUnknown(): this {
410
+ this.filters.push({ "id": { "$isNull": true } });
411
+ return this;
412
+ }
413
+
414
+ filterByTenant(val: any): this {
415
+ this.filters.push({ "tenant": { "$eq": val } });
416
+ return this;
417
+ }
418
+
419
+ filterByTenantIn(...vals: any[]): this {
420
+ this.filters.push({ "tenant": { "$in": vals } });
421
+ return this;
422
+ }
423
+
424
+ withTenantIsKnown(): this {
425
+ this.filters.push({ "tenant": { "$isNull": false } });
426
+ return this;
427
+ }
428
+
429
+ withTenantIsUnknown(): this {
430
+ this.filters.push({ "tenant": { "$isNull": true } });
431
+ return this;
432
+ }
433
+
434
+ withContactPhoneContaining(val: string): this {
435
+ this.filters.push({ "contactPhone": { "$contains": val } });
436
+ return this;
437
+ }
438
+
439
+ withContactPhoneIs(val: string): this {
440
+ this.filters.push({ "contactPhone": { "$eq": val } });
441
+ return this;
442
+ }
443
+
444
+ withContactPhoneIsNot(val: string): this {
445
+ this.filters.push({ "contactPhone": { "$ne": val } });
446
+ return this;
447
+ }
448
+
449
+ withContactPhoneIn(...vals: string[]): this {
450
+ this.filters.push({ "contactPhone": { "$in": vals } });
451
+ return this;
452
+ }
453
+
454
+ withContactPhoneNotIn(...vals: string[]): this {
455
+ this.filters.push({ "contactPhone": { "$notIn": vals } });
456
+ return this;
457
+ }
458
+
459
+ withContactPhoneGreaterThan(val: string): this {
460
+ this.filters.push({ "contactPhone": { "$gt": val } });
461
+ return this;
462
+ }
463
+
464
+ withContactPhoneGreaterThanOrEqualTo(val: string): this {
465
+ this.filters.push({ "contactPhone": { "$gte": val } });
466
+ return this;
467
+ }
468
+
469
+ withContactPhoneLessThan(val: string): this {
470
+ this.filters.push({ "contactPhone": { "$lt": val } });
471
+ return this;
472
+ }
473
+
474
+ withContactPhoneLessThanOrEqualTo(val: string): this {
475
+ this.filters.push({ "contactPhone": { "$lte": val } });
476
+ return this;
477
+ }
478
+
479
+ withContactPhoneBetween(lower: string, upper: string): this {
480
+ this.filters.push({ "contactPhone": { "$between": [lower, upper] } });
481
+ return this;
482
+ }
483
+
484
+ withContactPhoneIsKnown(): this {
485
+ this.filters.push({ "contactPhone": { "$isNull": false } });
486
+ return this;
487
+ }
488
+
489
+ withContactPhoneIsUnknown(): this {
490
+ this.filters.push({ "contactPhone": { "$isNull": true } });
491
+ return this;
492
+ }
493
+ withContactPhoneNotContaining(val: string): this {
494
+ this.filters.push({ "contactPhone": { "$notContains": val } });
495
+ return this;
496
+ }
497
+
498
+ withContactPhoneStartingWith(val: string): this {
499
+ this.filters.push({ "contactPhone": { "$startsWith": val } });
500
+ return this;
501
+ }
502
+
503
+ withContactPhoneNotStartingWith(val: string): this {
504
+ this.filters.push({ "contactPhone": { "$notStartsWith": val } });
505
+ return this;
506
+ }
507
+
508
+ withContactPhoneEndingWith(val: string): this {
509
+ this.filters.push({ "contactPhone": { "$endsWith": val } });
510
+ return this;
511
+ }
512
+
513
+ withContactPhoneNotEndingWith(val: string): this {
514
+ this.filters.push({ "contactPhone": { "$notEndsWith": val } });
515
+ return this;
516
+ }
517
+
518
+ withContactPhoneSoundingLike(val: string): this {
519
+ this.filters.push({ "contactPhone": { "$soundLike": val } });
520
+ return this;
521
+ }
522
+
523
+ withInternalNoteContaining(val: string): this {
524
+ this.filters.push({ "internalNote": { "$contains": val } });
525
+ return this;
526
+ }
527
+
528
+ withInternalNoteIs(val: string): this {
529
+ this.filters.push({ "internalNote": { "$eq": val } });
530
+ return this;
531
+ }
532
+
533
+ withInternalNoteIsNot(val: string): this {
534
+ this.filters.push({ "internalNote": { "$ne": val } });
535
+ return this;
536
+ }
537
+
538
+ withInternalNoteIn(...vals: string[]): this {
539
+ this.filters.push({ "internalNote": { "$in": vals } });
540
+ return this;
541
+ }
542
+
543
+ withInternalNoteNotIn(...vals: string[]): this {
544
+ this.filters.push({ "internalNote": { "$notIn": vals } });
545
+ return this;
546
+ }
547
+
548
+ withInternalNoteGreaterThan(val: string): this {
549
+ this.filters.push({ "internalNote": { "$gt": val } });
550
+ return this;
551
+ }
552
+
553
+ withInternalNoteGreaterThanOrEqualTo(val: string): this {
554
+ this.filters.push({ "internalNote": { "$gte": val } });
555
+ return this;
556
+ }
557
+
558
+ withInternalNoteLessThan(val: string): this {
559
+ this.filters.push({ "internalNote": { "$lt": val } });
560
+ return this;
561
+ }
562
+
563
+ withInternalNoteLessThanOrEqualTo(val: string): this {
564
+ this.filters.push({ "internalNote": { "$lte": val } });
565
+ return this;
566
+ }
567
+
568
+ withInternalNoteBetween(lower: string, upper: string): this {
569
+ this.filters.push({ "internalNote": { "$between": [lower, upper] } });
570
+ return this;
571
+ }
572
+
573
+ withInternalNoteIsKnown(): this {
574
+ this.filters.push({ "internalNote": { "$isNull": false } });
575
+ return this;
576
+ }
577
+
578
+ withInternalNoteIsUnknown(): this {
579
+ this.filters.push({ "internalNote": { "$isNull": true } });
580
+ return this;
581
+ }
582
+ withInternalNoteNotContaining(val: string): this {
583
+ this.filters.push({ "internalNote": { "$notContains": val } });
584
+ return this;
585
+ }
586
+
587
+ withInternalNoteStartingWith(val: string): this {
588
+ this.filters.push({ "internalNote": { "$startsWith": val } });
589
+ return this;
590
+ }
591
+
592
+ withInternalNoteNotStartingWith(val: string): this {
593
+ this.filters.push({ "internalNote": { "$notStartsWith": val } });
594
+ return this;
595
+ }
596
+
597
+ withInternalNoteEndingWith(val: string): this {
598
+ this.filters.push({ "internalNote": { "$endsWith": val } });
599
+ return this;
600
+ }
601
+
602
+ withInternalNoteNotEndingWith(val: string): this {
603
+ this.filters.push({ "internalNote": { "$notEndsWith": val } });
604
+ return this;
605
+ }
606
+
607
+ withInternalNoteSoundingLike(val: string): this {
608
+ this.filters.push({ "internalNote": { "$soundLike": val } });
609
+ return this;
610
+ }
611
+
612
+ withCreateTimeIs(val: unknown): this {
613
+ this.filters.push({ "createTime": { "$eq": val } });
614
+ return this;
615
+ }
616
+
617
+ withCreateTimeIsNot(val: unknown): this {
618
+ this.filters.push({ "createTime": { "$ne": val } });
619
+ return this;
620
+ }
621
+
622
+ withCreateTimeIn(...vals: unknown[]): this {
623
+ this.filters.push({ "createTime": { "$in": vals } });
624
+ return this;
625
+ }
626
+
627
+ withCreateTimeNotIn(...vals: unknown[]): this {
628
+ this.filters.push({ "createTime": { "$notIn": vals } });
629
+ return this;
630
+ }
631
+
632
+ withCreateTimeGreaterThan(val: unknown): this {
633
+ this.filters.push({ "createTime": { "$gt": val } });
634
+ return this;
635
+ }
636
+
637
+ withCreateTimeGreaterThanOrEqualTo(val: unknown): this {
638
+ this.filters.push({ "createTime": { "$gte": val } });
639
+ return this;
640
+ }
641
+
642
+ withCreateTimeLessThan(val: unknown): this {
643
+ this.filters.push({ "createTime": { "$lt": val } });
644
+ return this;
645
+ }
646
+
647
+ withCreateTimeLessThanOrEqualTo(val: unknown): this {
648
+ this.filters.push({ "createTime": { "$lte": val } });
649
+ return this;
650
+ }
651
+
652
+ withCreateTimeBetween(lower: unknown, upper: unknown): this {
653
+ this.filters.push({ "createTime": { "$between": [lower, upper] } });
654
+ return this;
655
+ }
656
+
657
+ withCreateTimeIsKnown(): this {
658
+ this.filters.push({ "createTime": { "$isNull": false } });
659
+ return this;
660
+ }
661
+
662
+ withCreateTimeIsUnknown(): this {
663
+ this.filters.push({ "createTime": { "$isNull": true } });
664
+ return this;
665
+ }
666
+
667
+ withUpdateTimeIs(val: unknown): this {
668
+ this.filters.push({ "updateTime": { "$eq": val } });
669
+ return this;
670
+ }
671
+
672
+ withUpdateTimeIsNot(val: unknown): this {
673
+ this.filters.push({ "updateTime": { "$ne": val } });
674
+ return this;
675
+ }
676
+
677
+ withUpdateTimeIn(...vals: unknown[]): this {
678
+ this.filters.push({ "updateTime": { "$in": vals } });
679
+ return this;
680
+ }
681
+
682
+ withUpdateTimeNotIn(...vals: unknown[]): this {
683
+ this.filters.push({ "updateTime": { "$notIn": vals } });
684
+ return this;
685
+ }
686
+
687
+ withUpdateTimeGreaterThan(val: unknown): this {
688
+ this.filters.push({ "updateTime": { "$gt": val } });
689
+ return this;
690
+ }
691
+
692
+ withUpdateTimeGreaterThanOrEqualTo(val: unknown): this {
693
+ this.filters.push({ "updateTime": { "$gte": val } });
694
+ return this;
695
+ }
696
+
697
+ withUpdateTimeLessThan(val: unknown): this {
698
+ this.filters.push({ "updateTime": { "$lt": val } });
699
+ return this;
700
+ }
701
+
702
+ withUpdateTimeLessThanOrEqualTo(val: unknown): this {
703
+ this.filters.push({ "updateTime": { "$lte": val } });
704
+ return this;
705
+ }
706
+
707
+ withUpdateTimeBetween(lower: unknown, upper: unknown): this {
708
+ this.filters.push({ "updateTime": { "$between": [lower, upper] } });
709
+ return this;
710
+ }
711
+
712
+ withUpdateTimeIsKnown(): this {
713
+ this.filters.push({ "updateTime": { "$isNull": false } });
714
+ return this;
715
+ }
716
+
717
+ withUpdateTimeIsUnknown(): this {
718
+ this.filters.push({ "updateTime": { "$isNull": true } });
719
+ return this;
720
+ }
721
+
722
+ withVersionIs(val: unknown): this {
723
+ this.filters.push({ "version": { "$eq": val } });
724
+ return this;
725
+ }
726
+
727
+ withVersionIsNot(val: unknown): this {
728
+ this.filters.push({ "version": { "$ne": val } });
729
+ return this;
730
+ }
731
+
732
+ withVersionIn(...vals: unknown[]): this {
733
+ this.filters.push({ "version": { "$in": vals } });
734
+ return this;
735
+ }
736
+
737
+ withVersionNotIn(...vals: unknown[]): this {
738
+ this.filters.push({ "version": { "$notIn": vals } });
739
+ return this;
740
+ }
741
+
742
+ withVersionGreaterThan(val: unknown): this {
743
+ this.filters.push({ "version": { "$gt": val } });
744
+ return this;
745
+ }
746
+
747
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
748
+ this.filters.push({ "version": { "$gte": val } });
749
+ return this;
750
+ }
751
+
752
+ withVersionLessThan(val: unknown): this {
753
+ this.filters.push({ "version": { "$lt": val } });
754
+ return this;
755
+ }
756
+
757
+ withVersionLessThanOrEqualTo(val: unknown): this {
758
+ this.filters.push({ "version": { "$lte": val } });
759
+ return this;
760
+ }
761
+
762
+ withVersionBetween(lower: unknown, upper: unknown): this {
763
+ this.filters.push({ "version": { "$between": [lower, upper] } });
764
+ return this;
765
+ }
766
+
767
+ withVersionIsKnown(): this {
768
+ this.filters.push({ "version": { "$isNull": false } });
769
+ return this;
770
+ }
771
+
772
+ withVersionIsUnknown(): this {
773
+ this.filters.push({ "version": { "$isNull": true } });
774
+ return this;
775
+ }
776
+
777
+ orderByIdAscending(): this {
778
+ this.query.orderBy("id", "asc");
779
+ return this;
780
+ }
781
+
782
+ orderByIdDescending(): this {
783
+ this.query.orderBy("id", "desc");
784
+ return this;
785
+ }
786
+
787
+
788
+ orderByContactPhoneAscending(): this {
789
+ this.query.orderBy("contactPhone", "asc");
790
+ return this;
791
+ }
792
+
793
+ orderByContactPhoneDescending(): this {
794
+ this.query.orderBy("contactPhone", "desc");
795
+ return this;
796
+ }
797
+
798
+ orderByInternalNoteAscending(): this {
799
+ this.query.orderBy("internalNote", "asc");
800
+ return this;
801
+ }
802
+
803
+ orderByInternalNoteDescending(): this {
804
+ this.query.orderBy("internalNote", "desc");
805
+ return this;
806
+ }
807
+
808
+ orderByCreateTimeAscending(): this {
809
+ this.query.orderBy("createTime", "asc");
810
+ return this;
811
+ }
812
+
813
+ orderByCreateTimeDescending(): this {
814
+ this.query.orderBy("createTime", "desc");
815
+ return this;
816
+ }
817
+
818
+ orderByUpdateTimeAscending(): this {
819
+ this.query.orderBy("updateTime", "asc");
820
+ return this;
821
+ }
822
+
823
+ orderByUpdateTimeDescending(): this {
824
+ this.query.orderBy("updateTime", "desc");
825
+ return this;
826
+ }
827
+
828
+ orderByVersionAscending(): this {
829
+ this.query.orderBy("version", "asc");
830
+ return this;
831
+ }
832
+
833
+ orderByVersionDescending(): this {
834
+ this.query.orderBy("version", "desc");
835
+ return this;
836
+ }
837
+
838
+
839
+ // --- Aggregations ---
840
+ count(): this {
841
+ this.query.aggregate("Count", "id", "count");
842
+ this._pageCountAlias = "count";
843
+ this._pageCountMethod = "count";
844
+ return this;
845
+ }
846
+
847
+ countAs(retName: string): this {
848
+ this.query.aggregate("Count", "id", retName);
849
+ this._pageCountAlias = retName;
850
+ this._pageCountMethod = "countAs";
851
+ return this;
852
+ }
853
+
854
+
855
+ // --- Group By ---
856
+ groupById(): this {
857
+ this.query.groupBy("id");
858
+ return this;
859
+ }
860
+
861
+ groupByIdAs(retName: string): this {
862
+ this.query.groupBy("id", retName);
863
+ return this;
864
+ }
865
+ groupByTenant(): this {
866
+ this.query.groupBy("tenant");
867
+ return this;
868
+ }
869
+
870
+ groupByTenantAs(retName: string): this {
871
+ this.query.groupBy("tenant", retName);
872
+ return this;
873
+ }
874
+ groupByContactPhone(): this {
875
+ this.query.groupBy("contactPhone");
876
+ return this;
877
+ }
878
+
879
+ groupByContactPhoneAs(retName: string): this {
880
+ this.query.groupBy("contactPhone", retName);
881
+ return this;
882
+ }
883
+ groupByInternalNote(): this {
884
+ this.query.groupBy("internalNote");
885
+ return this;
886
+ }
887
+
888
+ groupByInternalNoteAs(retName: string): this {
889
+ this.query.groupBy("internalNote", retName);
890
+ return this;
891
+ }
892
+ groupByCreateTime(): this {
893
+ this.query.groupBy("createTime");
894
+ return this;
895
+ }
896
+
897
+ groupByCreateTimeAs(retName: string): this {
898
+ this.query.groupBy("createTime", retName);
899
+ return this;
900
+ }
901
+ groupByUpdateTime(): this {
902
+ this.query.groupBy("updateTime");
903
+ return this;
904
+ }
905
+
906
+ groupByUpdateTimeAs(retName: string): this {
907
+ this.query.groupBy("updateTime", retName);
908
+ return this;
909
+ }
910
+ groupByVersion(): this {
911
+ this.query.groupBy("version");
912
+ return this;
913
+ }
914
+
915
+ groupByVersionAs(retName: string): this {
916
+ this.query.groupBy("version", retName);
917
+ return this;
918
+ }
919
+
920
+ // --- Facets ---
921
+ facetByTenantAs(
922
+ facetName: string,
923
+ request: { readonly entityName: "Tenant"; toQuery(): SelectQuery },
924
+ includeAllFacets = true,
925
+ ): this {
926
+ this.query.facetBy(facetName, "tenant", request, includeAllFacets,
927
+ { kind: "facet", method: "facetByTenantAs", relation: "tenant", alias: facetName });
928
+ return this;
929
+ }
930
+
931
+
932
+ private async executeForListInternal(context: UserContext): Promise<SmartList<PurchaseOrder>> {
933
+ this.ensureIntent();
934
+ if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context);
935
+ if (this.filters.length > 0) {
936
+ this.query.filter({ "$and": this.filters });
937
+ }
938
+
939
+ const service = context.requireResource<TeaQLDataService>("dataService");
940
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
941
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
942
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
943
+ row instanceof PurchaseOrder
944
+ ? row
945
+ : PurchaseOrder.fromRecord(row as Record<string, unknown>, new EntityRoot()));
946
+ const result = new SmartList<PurchaseOrder>(data);
947
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
948
+
949
+ if (this.query.facets.length > 0) {
950
+ result.facets = await executeRelationFacets(
951
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
952
+ }
953
+
954
+ return result;
955
+ }
956
+
957
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
958
+ this.ensureIntent();
959
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
960
+ const service = context.requireResource<TeaQLDataService>("dataService");
961
+ return new SmartList<Record<string, unknown>>(
962
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
963
+ }
964
+
965
+ private async executeCountedListInternal(
966
+ context: UserContext,
967
+ ): Promise<SmartList<PurchaseOrder>> {
968
+ this.ensureIntent();
969
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
970
+ const service = context.requireResource<TeaQLDataService>("dataService");
971
+ const preparedQuery = context.prepareQuery(this.query);
972
+ const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined;
973
+ const countOperation = { kind: "named-count" as const,
974
+ method: this._pageCountMethod ?? "count",
975
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
976
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
977
+ preparedQuery, this._pageCountAlias, countOperation);
978
+ const pageQuery = preparedQuery.clone();
979
+ // A page count describes the full filtered set, not an aggregate-only page row.
980
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
981
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
982
+ const rows = await service.executeQuery(pageQuery);
983
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
984
+ ? context.idSetPaginationCount!
985
+ : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation));
986
+ const data = new SmartList(rows.map((row: unknown) =>
987
+ row instanceof PurchaseOrder
988
+ ? row
989
+ : PurchaseOrder.fromRecord(row as Record<string, unknown>, new EntityRoot())));
990
+ data.totalCount = totalCount;
991
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
992
+ if (this.query.facets.length > 0) {
993
+ data.facets = await executeRelationFacets(
994
+ service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets);
995
+ }
996
+ return data;
997
+ }
998
+
999
+ private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<PurchaseOrder> {
1000
+ this.ensureIntent();
1001
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
1002
+ const service = context.requireResource<TeaQLDataService>("dataService");
1003
+ const preparedQuery = context.prepareQuery(this.query);
1004
+ // Prepare Context and capture the runtime request before returning a lazy iterator.
1005
+ const chunks = service.executeForStream(preparedQuery, chunkSize);
1006
+ return (async function* () {
1007
+ for await (const chunk of chunks) {
1008
+ for (const entity of chunk) {
1009
+ yield entity instanceof PurchaseOrder
1010
+ ? entity
1011
+ : PurchaseOrder.fromRecord(entity as Record<string, unknown>, new EntityRoot());
1012
+ }
1013
+ }
1014
+ })();
1015
+ }
1016
+
1017
+ private ensureIntent(): void {
1018
+ // Runtime owns validation, Unicode whitespace rules and typed diagnostics.
1019
+ new QueryIntent(this._comment, this._purpose);
1020
+ }
1021
+
1022
+ }
1023
+
1024
+ export class ExecutablePurchaseOrderRequest {
1025
+ constructor(
1026
+ private readonly execute: (context: UserContext) => Promise<SmartList<PurchaseOrder>>,
1027
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
1028
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<PurchaseOrder>,
1029
+ private readonly limitOne: () => void,
1030
+ private readonly addComment: (comment: string) => void,
1031
+ private readonly ensureIntent: () => void,
1032
+ ) {}
1033
+
1034
+ comment(c: string): this {
1035
+ this.addComment(c);
1036
+ return this;
1037
+ }
1038
+
1039
+ async newEntity(context: UserContext): Promise<PurchaseOrder> {
1040
+ this.ensureIntent();
1041
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
1042
+ return PurchaseOrder.teaqlCreate(context);
1043
+ }
1044
+
1045
+ executeForList(context: UserContext): Promise<SmartList<PurchaseOrder>> {
1046
+ this.ensureIntent();
1047
+ return this.execute(context);
1048
+ }
1049
+
1050
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
1051
+ this.ensureIntent();
1052
+ return this.executeRows(context);
1053
+ }
1054
+
1055
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<PurchaseOrder> {
1056
+ this.ensureIntent();
1057
+ return this.stream(context, chunkSize);
1058
+ }
1059
+
1060
+ async executeForOne(context: UserContext): Promise<PurchaseOrder | undefined> {
1061
+ this.limitOne();
1062
+ return (await this.executeForList(context))[0];
1063
+ }
1064
+ }
source/teaql-ts/examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { Tenant } from '../models/Tenant';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
+
7
+
8
+
9
+ export class TenantRequest {
10
+ private query: SelectQuery;
11
+ private filters: any[] = [];
12
+ private _purpose: string | undefined;
13
+ private _comment: string | undefined;
14
+ private _pageCountAlias: string | undefined;
15
+ private _pageCountMethod: "count" | "countAs" | undefined;
16
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
17
+
18
+ constructor(minimal = false) {
19
+ this.query = new SelectQuery("Tenant");
20
+ this.filters.push({ version: { "$gte": 1 } });
21
+ if (minimal) {
22
+ this.selectId();
23
+ this.selectVersion();
24
+ }
25
+ else this.selectSelfFields();
26
+ }
27
+
28
+ get entityName(): "Tenant" {
29
+ return "Tenant";
30
+ }
31
+
32
+ comment(c: string): this {
33
+ this.query.comment(c);
34
+ this._comment = c;
35
+ return this;
36
+ }
37
+
38
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
39
+ const base = this.query.clone();
40
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
41
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
42
+ this.query = merged.query as SelectQuery;
43
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
44
+ this._dynamicSearchWarnings.push(...merged.warnings);
45
+ return this;
46
+ }
47
+
48
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
49
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
50
+ }
51
+
52
+ purpose(p: string): ExecutableTenantRequest {
53
+ this.query.purpose(p);
54
+ this._purpose = p;
55
+ return new ExecutableTenantRequest(
56
+ (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)),
57
+ (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)),
58
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
59
+ () => this.limit(1),
60
+ (c) => this.comment(c),
61
+ () => this.ensureIntent());
62
+ }
63
+
64
+ optimizeForContinuousPageFetch(): this {
65
+ this.query.optimizeForContinuousPageFetch();
66
+ return this;
67
+ }
68
+
69
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
70
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
71
+ return this;
72
+ }
73
+
74
+ optimizePaginationWithIdSet(): this {
75
+ this.query.optimizePaginationWithIdSet();
76
+ return this;
77
+ }
78
+
79
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
80
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
81
+ return this;
82
+ }
83
+
84
+ topNProbeParentThreshold(threshold: number): this {
85
+ this.query.topNProbeParentThreshold(threshold);
86
+ return this;
87
+ }
88
+
89
+ limit(n: number): this {
90
+ this.query.limit(n);
91
+ return this;
92
+ }
93
+
94
+ offset(n: number): this {
95
+ this.query.offset(n);
96
+ return this;
97
+ }
98
+
99
+ toQuery(): SelectQuery {
100
+ if (this.filters.length > 0) {
101
+ this.query.filter({ "$and": this.filters });
102
+ }
103
+ return this.query;
104
+ }
105
+
106
+ withDeletedRows(): this {
107
+ this.query.withDeletedRows();
108
+ this.filters = this.filters.filter(filter => !("version" in filter));
109
+ return this;
110
+ }
111
+
112
+ deletedRowsOnly(): this {
113
+ this.withDeletedRows();
114
+ this.query.deletedRowsOnly();
115
+ this.filters.push({ version: { "$lte": -1 } });
116
+ return this;
117
+ }
118
+
119
+ selectSelfFields(): this {
120
+ this.query.select(["id", "name", "version"]);
121
+ return this;
122
+ }
123
+
124
+ selectId(): this {
125
+ this.query.select(["id"]);
126
+ return this;
127
+ }
128
+
129
+ selectName(): this {
130
+ this.query.select(["name"]);
131
+ return this;
132
+ }
133
+
134
+ selectVersion(): this {
135
+ this.query.select(["version"]);
136
+ return this;
137
+ }
138
+
139
+
140
+
141
+
142
+ selectPurchaseOrderListWith(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
143
+ this.query.relationQuery(
144
+ "purchaseOrderList", request.toQuery(), "id", "tenant", true,
145
+ { kind: "relation-select", method: "selectPurchaseOrderListWith", relation: "purchaseOrderList" });
146
+ return this;
147
+ }
148
+ selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
149
+ this.query.relationQuery(
150
+ "orderItemList", request.toQuery(), "id", "tenant", true,
151
+ { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" });
152
+ return this;
153
+ }
154
+
155
+ havePurchaseOrders(): this {
156
+ return this.withPurchaseOrderListMatching({
157
+ entityName: "PurchaseOrder",
158
+ toQuery: () => new SelectQuery("PurchaseOrder"),
159
+ });
160
+ }
161
+
162
+ haveNoPurchaseOrders(): this {
163
+ return this.withoutPurchaseOrderListMatching({
164
+ entityName: "PurchaseOrder",
165
+ toQuery: () => new SelectQuery("PurchaseOrder"),
166
+ });
167
+ }
168
+
169
+ withPurchaseOrderListMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
170
+ this.filters.push({
171
+ "id": {
172
+ "$inSubquery": {
173
+ query: request.toQuery(), field: "tenant",
174
+ },
175
+ },
176
+ });
177
+ return this;
178
+ }
179
+
180
+ withoutPurchaseOrderListMatching(request: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
181
+ this.filters.push({
182
+ "id": {
183
+ "$notInSubquery": {
184
+ query: request.toQuery(), field: "tenant",
185
+ },
186
+ },
187
+ });
188
+ return this;
189
+ }
190
+ haveOrderItems(): this {
191
+ return this.withOrderItemListMatching({
192
+ entityName: "OrderItem",
193
+ toQuery: () => new SelectQuery("OrderItem"),
194
+ });
195
+ }
196
+
197
+ haveNoOrderItems(): this {
198
+ return this.withoutOrderItemListMatching({
199
+ entityName: "OrderItem",
200
+ toQuery: () => new SelectQuery("OrderItem"),
201
+ });
202
+ }
203
+
204
+ withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
205
+ this.filters.push({
206
+ "id": {
207
+ "$inSubquery": {
208
+ query: request.toQuery(), field: "tenant",
209
+ },
210
+ },
211
+ });
212
+ return this;
213
+ }
214
+
215
+ withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
216
+ this.filters.push({
217
+ "id": {
218
+ "$notInSubquery": {
219
+ query: request.toQuery(), field: "tenant",
220
+ },
221
+ },
222
+ });
223
+ return this;
224
+ }
225
+
226
+ countPurchaseOrders(): this {
227
+ return this.countPurchaseOrdersAs("countPurchaseOrders");
228
+ }
229
+
230
+ countPurchaseOrdersAs(alias: string): this {
231
+ const query = new SelectQuery("PurchaseOrder").filter({ version: { "$gte": 1 } });
232
+ this.countPurchaseOrdersWith(alias, { entityName: "PurchaseOrder", toQuery: () => query });
233
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
234
+ kind: "relation-count", method: "countPurchaseOrdersAs", relation: "purchaseOrderList", alias };
235
+ return this;
236
+ }
237
+
238
+ countPurchaseOrdersWith(alias: string, child: { readonly entityName: "PurchaseOrder"; toQuery(): SelectQuery }): this {
239
+ const query = child.toQuery().clone();
240
+ query.aggregateItems = [];
241
+ query.aggregate("Count", "id", alias);
242
+ this.query.relationAggregate("purchaseOrderList", alias, query, true,
243
+ { kind: "relation-count", method: "countPurchaseOrdersWith", relation: "purchaseOrderList", alias });
244
+ return this;
245
+ }
246
+
247
+
248
+ countOrderItems(): this {
249
+ return this.countOrderItemsAs("countOrderItems");
250
+ }
251
+
252
+ countOrderItemsAs(alias: string): this {
253
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
254
+ this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query });
255
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
256
+ kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias };
257
+ return this;
258
+ }
259
+
260
+ countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
261
+ const query = child.toQuery().clone();
262
+ query.aggregateItems = [];
263
+ query.aggregate("Count", "id", alias);
264
+ this.query.relationAggregate("orderItemList", alias, query, true,
265
+ { kind: "relation-count", method: "countOrderItemsWith", relation: "orderItemList", alias });
266
+ return this;
267
+ }
268
+
269
+ minUnitPriceOfOrderItems(): this {
270
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
271
+ return this.minUnitPriceOfOrderItemsAs(
272
+ "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
273
+ }
274
+
275
+ minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
276
+ const query = child.toQuery().clone();
277
+ query.aggregateItems = [];
278
+ query.aggregate("min", "unitPrice", alias);
279
+ this.query.relationAggregate("orderItemList", alias, query, true,
280
+ { kind: "aggregate", method: "minUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
281
+ return this;
282
+ }
283
+ maxUnitPriceOfOrderItems(): this {
284
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
285
+ return this.maxUnitPriceOfOrderItemsAs(
286
+ "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
287
+ }
288
+
289
+ maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
290
+ const query = child.toQuery().clone();
291
+ query.aggregateItems = [];
292
+ query.aggregate("max", "unitPrice", alias);
293
+ this.query.relationAggregate("orderItemList", alias, query, true,
294
+ { kind: "aggregate", method: "maxUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
295
+ return this;
296
+ }
297
+ sumUnitPriceOfOrderItems(): this {
298
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
299
+ return this.sumUnitPriceOfOrderItemsAs(
300
+ "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
301
+ }
302
+
303
+ sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
304
+ const query = child.toQuery().clone();
305
+ query.aggregateItems = [];
306
+ query.aggregate("sum", "unitPrice", alias);
307
+ this.query.relationAggregate("orderItemList", alias, query, true,
308
+ { kind: "aggregate", method: "sumUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
309
+ return this;
310
+ }
311
+ avgUnitPriceOfOrderItems(): this {
312
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
313
+ return this.avgUnitPriceOfOrderItemsAs(
314
+ "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
315
+ }
316
+
317
+ avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
318
+ const query = child.toQuery().clone();
319
+ query.aggregateItems = [];
320
+ query.aggregate("avg", "unitPrice", alias);
321
+ this.query.relationAggregate("orderItemList", alias, query, true,
322
+ { kind: "aggregate", method: "avgUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
323
+ return this;
324
+ }
325
+ standardDeviationUnitPriceOfOrderItems(): this {
326
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
327
+ return this.standardDeviationUnitPriceOfOrderItemsAs(
328
+ "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
329
+ }
330
+
331
+ standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
332
+ const query = child.toQuery().clone();
333
+ query.aggregateItems = [];
334
+ query.aggregate("stddev", "unitPrice", alias);
335
+ this.query.relationAggregate("orderItemList", alias, query, true,
336
+ { kind: "aggregate", method: "standardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
337
+ return this;
338
+ }
339
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this {
340
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
341
+ return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(
342
+ "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
343
+ }
344
+
345
+ squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
346
+ const query = child.toQuery().clone();
347
+ query.aggregateItems = [];
348
+ query.aggregate("stddev_pop", "unitPrice", alias);
349
+ this.query.relationAggregate("orderItemList", alias, query, true,
350
+ { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
351
+ return this;
352
+ }
353
+ sampleVarianceUnitPriceOfOrderItems(): this {
354
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
355
+ return this.sampleVarianceUnitPriceOfOrderItemsAs(
356
+ "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
357
+ }
358
+
359
+ sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
360
+ const query = child.toQuery().clone();
361
+ query.aggregateItems = [];
362
+ query.aggregate("var_samp", "unitPrice", alias);
363
+ this.query.relationAggregate("orderItemList", alias, query, true,
364
+ { kind: "aggregate", method: "sampleVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
365
+ return this;
366
+ }
367
+ samplePopulationVarianceUnitPriceOfOrderItems(): this {
368
+ const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } });
369
+ return this.samplePopulationVarianceUnitPriceOfOrderItemsAs(
370
+ "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query });
371
+ }
372
+
373
+ samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this {
374
+ const query = child.toQuery().clone();
375
+ query.aggregateItems = [];
376
+ query.aggregate("var_pop", "unitPrice", alias);
377
+ this.query.relationAggregate("orderItemList", alias, query, true,
378
+ { kind: "aggregate", method: "samplePopulationVarianceUnitPriceOfOrderItemsAs", relation: "orderItemList", alias });
379
+ return this;
380
+ }
381
+
382
+ withIdIs(val: string): this {
383
+ this.filters.push({ "id": { "$eq": val } });
384
+ return this;
385
+ }
386
+
387
+ withIdIsNot(val: string): this {
388
+ this.filters.push({ "id": { "$ne": val } });
389
+ return this;
390
+ }
391
+
392
+ withIdIn(...vals: string[]): this {
393
+ this.filters.push({ "id": { "$in": vals } });
394
+ return this;
395
+ }
396
+
397
+ withIdNotIn(...vals: string[]): this {
398
+ this.filters.push({ "id": { "$notIn": vals } });
399
+ return this;
400
+ }
401
+
402
+ withIdGreaterThan(val: string): this {
403
+ this.filters.push({ "id": { "$gt": val } });
404
+ return this;
405
+ }
406
+
407
+ withIdGreaterThanOrEqualTo(val: string): this {
408
+ this.filters.push({ "id": { "$gte": val } });
409
+ return this;
410
+ }
411
+
412
+ withIdLessThan(val: string): this {
413
+ this.filters.push({ "id": { "$lt": val } });
414
+ return this;
415
+ }
416
+
417
+ withIdLessThanOrEqualTo(val: string): this {
418
+ this.filters.push({ "id": { "$lte": val } });
419
+ return this;
420
+ }
421
+
422
+ withIdBetween(lower: string, upper: string): this {
423
+ this.filters.push({ "id": { "$between": [lower, upper] } });
424
+ return this;
425
+ }
426
+
427
+ withIdIsKnown(): this {
428
+ this.filters.push({ "id": { "$isNull": false } });
429
+ return this;
430
+ }
431
+
432
+ withIdIsUnknown(): this {
433
+ this.filters.push({ "id": { "$isNull": true } });
434
+ return this;
435
+ }
436
+
437
+ withNameContaining(val: string): this {
438
+ this.filters.push({ "name": { "$contains": val } });
439
+ return this;
440
+ }
441
+
442
+ withNameIs(val: string): this {
443
+ this.filters.push({ "name": { "$eq": val } });
444
+ return this;
445
+ }
446
+
447
+ withNameIsNot(val: string): this {
448
+ this.filters.push({ "name": { "$ne": val } });
449
+ return this;
450
+ }
451
+
452
+ withNameIn(...vals: string[]): this {
453
+ this.filters.push({ "name": { "$in": vals } });
454
+ return this;
455
+ }
456
+
457
+ withNameNotIn(...vals: string[]): this {
458
+ this.filters.push({ "name": { "$notIn": vals } });
459
+ return this;
460
+ }
461
+
462
+ withNameGreaterThan(val: string): this {
463
+ this.filters.push({ "name": { "$gt": val } });
464
+ return this;
465
+ }
466
+
467
+ withNameGreaterThanOrEqualTo(val: string): this {
468
+ this.filters.push({ "name": { "$gte": val } });
469
+ return this;
470
+ }
471
+
472
+ withNameLessThan(val: string): this {
473
+ this.filters.push({ "name": { "$lt": val } });
474
+ return this;
475
+ }
476
+
477
+ withNameLessThanOrEqualTo(val: string): this {
478
+ this.filters.push({ "name": { "$lte": val } });
479
+ return this;
480
+ }
481
+
482
+ withNameBetween(lower: string, upper: string): this {
483
+ this.filters.push({ "name": { "$between": [lower, upper] } });
484
+ return this;
485
+ }
486
+
487
+ withNameIsKnown(): this {
488
+ this.filters.push({ "name": { "$isNull": false } });
489
+ return this;
490
+ }
491
+
492
+ withNameIsUnknown(): this {
493
+ this.filters.push({ "name": { "$isNull": true } });
494
+ return this;
495
+ }
496
+ withNameNotContaining(val: string): this {
497
+ this.filters.push({ "name": { "$notContains": val } });
498
+ return this;
499
+ }
500
+
501
+ withNameStartingWith(val: string): this {
502
+ this.filters.push({ "name": { "$startsWith": val } });
503
+ return this;
504
+ }
505
+
506
+ withNameNotStartingWith(val: string): this {
507
+ this.filters.push({ "name": { "$notStartsWith": val } });
508
+ return this;
509
+ }
510
+
511
+ withNameEndingWith(val: string): this {
512
+ this.filters.push({ "name": { "$endsWith": val } });
513
+ return this;
514
+ }
515
+
516
+ withNameNotEndingWith(val: string): this {
517
+ this.filters.push({ "name": { "$notEndsWith": val } });
518
+ return this;
519
+ }
520
+
521
+ withNameSoundingLike(val: string): this {
522
+ this.filters.push({ "name": { "$soundLike": val } });
523
+ return this;
524
+ }
525
+
526
+ withVersionIs(val: unknown): this {
527
+ this.filters.push({ "version": { "$eq": val } });
528
+ return this;
529
+ }
530
+
531
+ withVersionIsNot(val: unknown): this {
532
+ this.filters.push({ "version": { "$ne": val } });
533
+ return this;
534
+ }
535
+
536
+ withVersionIn(...vals: unknown[]): this {
537
+ this.filters.push({ "version": { "$in": vals } });
538
+ return this;
539
+ }
540
+
541
+ withVersionNotIn(...vals: unknown[]): this {
542
+ this.filters.push({ "version": { "$notIn": vals } });
543
+ return this;
544
+ }
545
+
546
+ withVersionGreaterThan(val: unknown): this {
547
+ this.filters.push({ "version": { "$gt": val } });
548
+ return this;
549
+ }
550
+
551
+ withVersionGreaterThanOrEqualTo(val: unknown): this {
552
+ this.filters.push({ "version": { "$gte": val } });
553
+ return this;
554
+ }
555
+
556
+ withVersionLessThan(val: unknown): this {
557
+ this.filters.push({ "version": { "$lt": val } });
558
+ return this;
559
+ }
560
+
561
+ withVersionLessThanOrEqualTo(val: unknown): this {
562
+ this.filters.push({ "version": { "$lte": val } });
563
+ return this;
564
+ }
565
+
566
+ withVersionBetween(lower: unknown, upper: unknown): this {
567
+ this.filters.push({ "version": { "$between": [lower, upper] } });
568
+ return this;
569
+ }
570
+
571
+ withVersionIsKnown(): this {
572
+ this.filters.push({ "version": { "$isNull": false } });
573
+ return this;
574
+ }
575
+
576
+ withVersionIsUnknown(): this {
577
+ this.filters.push({ "version": { "$isNull": true } });
578
+ return this;
579
+ }
580
+
581
+ orderByIdAscending(): this {
582
+ this.query.orderBy("id", "asc");
583
+ return this;
584
+ }
585
+
586
+ orderByIdDescending(): this {
587
+ this.query.orderBy("id", "desc");
588
+ return this;
589
+ }
590
+
591
+ orderByNameAscending(): this {
592
+ this.query.orderBy("name", "asc");
593
+ return this;
594
+ }
595
+
596
+ orderByNameDescending(): this {
597
+ this.query.orderBy("name", "desc");
598
+ return this;
599
+ }
600
+
601
+ orderByVersionAscending(): this {
602
+ this.query.orderBy("version", "asc");
603
+ return this;
604
+ }
605
+
606
+ orderByVersionDescending(): this {
607
+ this.query.orderBy("version", "desc");
608
+ return this;
609
+ }
610
+
611
+
612
+ // --- Aggregations ---
613
+ count(): this {
614
+ this.query.aggregate("Count", "id", "count");
615
+ this._pageCountAlias = "count";
616
+ this._pageCountMethod = "count";
617
+ return this;
618
+ }
619
+
620
+ countAs(retName: string): this {
621
+ this.query.aggregate("Count", "id", retName);
622
+ this._pageCountAlias = retName;
623
+ this._pageCountMethod = "countAs";
624
+ return this;
625
+ }
626
+
627
+
628
+ // --- Group By ---
629
+ groupById(): this {
630
+ this.query.groupBy("id");
631
+ return this;
632
+ }
633
+
634
+ groupByIdAs(retName: string): this {
635
+ this.query.groupBy("id", retName);
636
+ return this;
637
+ }
638
+ groupByName(): this {
639
+ this.query.groupBy("name");
640
+ return this;
641
+ }
642
+
643
+ groupByNameAs(retName: string): this {
644
+ this.query.groupBy("name", retName);
645
+ return this;
646
+ }
647
+ groupByVersion(): this {
648
+ this.query.groupBy("version");
649
+ return this;
650
+ }
651
+
652
+ groupByVersionAs(retName: string): this {
653
+ this.query.groupBy("version", retName);
654
+ return this;
655
+ }
656
+
657
+ // --- Facets ---
658
+
659
+ private async executeForListInternal(context: UserContext): Promise<SmartList<Tenant>> {
660
+ this.ensureIntent();
661
+ if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context);
662
+ if (this.filters.length > 0) {
663
+ this.query.filter({ "$and": this.filters });
664
+ }
665
+
666
+ const service = context.requireResource<TeaQLDataService>("dataService");
667
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
668
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
669
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
670
+ row instanceof Tenant
671
+ ? row
672
+ : Tenant.fromRecord(row as Record<string, unknown>, new EntityRoot()));
673
+ const result = new SmartList<Tenant>(data);
674
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
675
+
676
+ if (this.query.facets.length > 0) {
677
+ result.facets = await executeRelationFacets(
678
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
679
+ }
680
+
681
+ return result;
682
+ }
683
+
684
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
685
+ this.ensureIntent();
686
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
687
+ const service = context.requireResource<TeaQLDataService>("dataService");
688
+ return new SmartList<Record<string, unknown>>(
689
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
690
+ }
691
+
692
+ private async executeCountedListInternal(
693
+ context: UserContext,
694
+ ): Promise<SmartList<Tenant>> {
695
+ this.ensureIntent();
696
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
697
+ const service = context.requireResource<TeaQLDataService>("dataService");
698
+ const preparedQuery = context.prepareQuery(this.query);
699
+ const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined;
700
+ const countOperation = { kind: "named-count" as const,
701
+ method: this._pageCountMethod ?? "count",
702
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
703
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
704
+ preparedQuery, this._pageCountAlias, countOperation);
705
+ const pageQuery = preparedQuery.clone();
706
+ // A page count describes the full filtered set, not an aggregate-only page row.
707
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
708
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
709
+ const rows = await service.executeQuery(pageQuery);
710
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
711
+ ? context.idSetPaginationCount!
712
+ : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation));
713
+ const data = new SmartList(rows.map((row: unknown) =>
714
+ row instanceof Tenant
715
+ ? row
716
+ : Tenant.fromRecord(row as Record<string, unknown>, new EntityRoot())));
717
+ data.totalCount = totalCount;
718
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
719
+ if (this.query.facets.length > 0) {
720
+ data.facets = await executeRelationFacets(
721
+ service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets);
722
+ }
723
+ return data;
724
+ }
725
+
726
+ private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<Tenant> {
727
+ this.ensureIntent();
728
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
729
+ const service = context.requireResource<TeaQLDataService>("dataService");
730
+ const preparedQuery = context.prepareQuery(this.query);
731
+ // Prepare Context and capture the runtime request before returning a lazy iterator.
732
+ const chunks = service.executeForStream(preparedQuery, chunkSize);
733
+ return (async function* () {
734
+ for await (const chunk of chunks) {
735
+ for (const entity of chunk) {
736
+ yield entity instanceof Tenant
737
+ ? entity
738
+ : Tenant.fromRecord(entity as Record<string, unknown>, new EntityRoot());
739
+ }
740
+ }
741
+ })();
742
+ }
743
+
744
+ private ensureIntent(): void {
745
+ // Runtime owns validation, Unicode whitespace rules and typed diagnostics.
746
+ new QueryIntent(this._comment, this._purpose);
747
+ }
748
+
749
+ }
750
+
751
+ export class ExecutableTenantRequest {
752
+ constructor(
753
+ private readonly execute: (context: UserContext) => Promise<SmartList<Tenant>>,
754
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
755
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<Tenant>,
756
+ private readonly limitOne: () => void,
757
+ private readonly addComment: (comment: string) => void,
758
+ private readonly ensureIntent: () => void,
759
+ ) {}
760
+
761
+ comment(c: string): this {
762
+ this.addComment(c);
763
+ return this;
764
+ }
765
+
766
+ async newEntity(context: UserContext): Promise<Tenant> {
767
+ this.ensureIntent();
768
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation");
769
+ return Tenant.teaqlCreate(context);
770
+ }
771
+
772
+ executeForList(context: UserContext): Promise<SmartList<Tenant>> {
773
+ this.ensureIntent();
774
+ return this.execute(context);
775
+ }
776
+
777
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
778
+ this.ensureIntent();
779
+ return this.executeRows(context);
780
+ }
781
+
782
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<Tenant> {
783
+ this.ensureIntent();
784
+ return this.stream(context, chunkSize);
785
+ }
786
+
787
+ async executeForOne(context: UserContext): Promise<Tenant | undefined> {
788
+ this.limitOne();
789
+ return (await this.executeForList(context))[0];
790
+ }
791
+ }
source/teaql-ts/examples/fix-e-alignment/generated/src/runtime-module.ts ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts';
2
+ import { ObjectLocation, RuntimeModule } from "teaql-ts";
3
+ import { ENTITY_SCHEMAS } from "./teaql-node-sql";
4
+ import { ensureGeneratedBootstrap } from "./generated-bootstrap";
5
+
6
+ /** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */
7
+ export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({
8
+ profile: "camelCase" as const,
9
+ entities: Object.freeze({
10
+ "Tenant": Object.freeze({
11
+ entityType: "Tenant",
12
+ profile: "camelCase" as const,
13
+ fields: Object.freeze({
14
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
15
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
16
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
17
+ }),
18
+ }),
19
+ "PurchaseOrder": Object.freeze({
20
+ entityType: "PurchaseOrder",
21
+ profile: "camelCase" as const,
22
+ fields: Object.freeze({
23
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
24
+ "tenant": Object.freeze({ canonicalName: "tenant", wireName: "tenant", aliases: Object.freeze([] as string[]) }),
25
+ "contact_phone": Object.freeze({ canonicalName: "contact_phone", wireName: "contactPhone", aliases: Object.freeze([] as string[]) }),
26
+ "internal_note": Object.freeze({ canonicalName: "internal_note", wireName: "internalNote", aliases: Object.freeze([] as string[]) }),
27
+ "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }),
28
+ "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }),
29
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
30
+ }),
31
+ }),
32
+ "OrderItem": Object.freeze({
33
+ entityType: "OrderItem",
34
+ profile: "camelCase" as const,
35
+ fields: Object.freeze({
36
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
37
+ "purchase_order": Object.freeze({ canonicalName: "purchase_order", wireName: "purchaseOrder", aliases: Object.freeze([] as string[]) }),
38
+ "tenant": Object.freeze({ canonicalName: "tenant", wireName: "tenant", aliases: Object.freeze([] as string[]) }),
39
+ "product_name": Object.freeze({ canonicalName: "product_name", wireName: "productName", aliases: Object.freeze([] as string[]) }),
40
+ "unit_price": Object.freeze({ canonicalName: "unit_price", wireName: "unitPrice", aliases: Object.freeze([] as string[]) }),
41
+ "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }),
42
+ "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }),
43
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
44
+ }),
45
+ })
46
+ }),
47
+ });
48
+
49
+ /** Passive generated metadata manifest. It never modifies the database schema. */
50
+ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, {
51
+ "Tenant": {
52
+ checkAndFix(context, mutation, results) {
53
+ const now = context.getResource("fixTime");
54
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
55
+ 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 });
56
+ 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 });
57
+
58
+
59
+ },
60
+ },
61
+ "PurchaseOrder": {
62
+ checkAndFix(context, mutation, results) {
63
+ const now = context.getResource("fixTime");
64
+ if (mutation.action === "Create") {
65
+ const root = context.requireActiveRoot("Tenant");
66
+ const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"];
67
+ if (supplied == null) {
68
+ mutation.payload["tenant"] = root.id;
69
+ context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "tenant", source: "context", sourceLabel: "activeRoot:Tenant" });
70
+ }
71
+ 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" });
72
+ } else if (mutation.action === "Update" || mutation.action === "Delete" || mutation.action === "Recover") {
73
+ const root = context.requireActiveRoot("Tenant");
74
+ const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"];
75
+ const original = mutation.loadedValues?.["tenant"]?.id ?? mutation.loadedValues?.["tenant"];
76
+ if (original == null) results.push({ ruleId: "invalid_type", location: ObjectLocation.property("tenant"), message: "Mutation requires a loaded context-bound root" });
77
+ 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" });
78
+ }
79
+
80
+
81
+
82
+ if (mutation.action === "Create" && mutation.payload["create_time"] == null) {
83
+ mutation.payload["create_time"] = now;
84
+ context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" });
85
+ }
86
+
87
+ if (mutation.action === "Create" && mutation.payload["update_time"] == null) {
88
+ mutation.payload["update_time"] = now;
89
+ context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" });
90
+ }
91
+ if (mutation.action === "Update") {
92
+ mutation.payload["update_time"] = now;
93
+ context.recordFixEvidence({ entityType: "PurchaseOrder", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" });
94
+ }
95
+
96
+
97
+ if ((mutation.action === "Create" && mutation.payload["tenant"] === undefined) || mutation.payload["tenant"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("tenant") });
98
+
99
+ if ((mutation.action === "Create" && mutation.payload["contact_phone"] === undefined) || mutation.payload["contact_phone"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("contact_phone") });
100
+ 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 });
101
+ 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 });
102
+
103
+ 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 });
104
+
105
+ if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") });
106
+
107
+ if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") });
108
+
109
+
110
+ },
111
+ },
112
+ "OrderItem": {
113
+ checkAndFix(context, mutation, results) {
114
+ const now = context.getResource("fixTime");
115
+ if (mutation.action === "Create") {
116
+ const root = context.requireActiveRoot("Tenant");
117
+ const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"];
118
+ if (supplied == null) {
119
+ mutation.payload["tenant"] = root.id;
120
+ context.recordFixEvidence({ entityType: "OrderItem", modelPath: "tenant", source: "context", sourceLabel: "activeRoot:Tenant" });
121
+ }
122
+ 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" });
123
+ } else if (mutation.action === "Update" || mutation.action === "Delete" || mutation.action === "Recover") {
124
+ const root = context.requireActiveRoot("Tenant");
125
+ const supplied = mutation.payload["tenant"]?.id ?? mutation.payload["tenant"];
126
+ const original = mutation.loadedValues?.["tenant"]?.id ?? mutation.loadedValues?.["tenant"];
127
+ if (original == null) results.push({ ruleId: "invalid_type", location: ObjectLocation.property("tenant"), message: "Mutation requires a loaded context-bound root" });
128
+ 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" });
129
+ }
130
+
131
+
132
+
133
+ if (mutation.action === "Create" && mutation.payload["create_time"] == null) {
134
+ mutation.payload["create_time"] = now;
135
+ context.recordFixEvidence({ entityType: "OrderItem", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" });
136
+ }
137
+
138
+ if (mutation.action === "Create" && mutation.payload["update_time"] == null) {
139
+ mutation.payload["update_time"] = now;
140
+ context.recordFixEvidence({ entityType: "OrderItem", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" });
141
+ }
142
+ if (mutation.action === "Update") {
143
+ mutation.payload["update_time"] = now;
144
+ context.recordFixEvidence({ entityType: "OrderItem", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" });
145
+ }
146
+
147
+
148
+ if ((mutation.action === "Create" && mutation.payload["purchase_order"] === undefined) || mutation.payload["purchase_order"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("purchase_order") });
149
+
150
+ if ((mutation.action === "Create" && mutation.payload["tenant"] === undefined) || mutation.payload["tenant"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("tenant") });
151
+
152
+ if ((mutation.action === "Create" && mutation.payload["product_name"] === undefined) || mutation.payload["product_name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("product_name") });
153
+ 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 });
154
+ 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 });
155
+
156
+ if ((mutation.action === "Create" && mutation.payload["unit_price"] === undefined) || mutation.payload["unit_price"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("unit_price") });
157
+ 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 });
158
+ 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 });
159
+
160
+ if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") });
161
+
162
+ if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") });
163
+
164
+
165
+ },
166
+ }
167
+ }, { ...{
168
+ defaultDomainRoot: { entity: "Tenant", id: "1", values: { "name": "Tenant Name" } },
169
+ constants: []
170
+ }, ensure: ensureGeneratedBootstrap });
source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sql.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntitySchema } from "teaql-ts/sql/core";
2
+
3
+ export const ENTITY_SCHEMAS: Record<string, EntitySchema> = {
4
+ "Tenant": {
5
+ table: "tenant_data",
6
+ auditMaskFields: [],
7
+ 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 }},
8
+ relations: {"purchaseOrderList": { targetEntity: "PurchaseOrder", localKey: "id", foreignKey: "tenant", many: true }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "tenant", many: true }}
9
+ },
10
+ "PurchaseOrder": {
11
+ table: "purchase_order_data",
12
+ auditMaskFields: [],
13
+ 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 }},
14
+ relations: {"tenant": { targetEntity: "Tenant", localKey: "tenant", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "purchaseOrder", many: true }}
15
+ },
16
+ "OrderItem": {
17
+ table: "order_item_data",
18
+ auditMaskFields: [],
19
+ 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 }},
20
+ relations: {"purchaseOrder": { targetEntity: "PurchaseOrder", localKey: "purchaseOrder", foreignKey: "id", many: false }, "tenant": { targetEntity: "Tenant", localKey: "tenant", foreignKey: "id", many: false }}
21
+ }
22
+ };
source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ SQLiteDriver,
3
+ SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient
4
+ } from "teaql-ts/sql/sqlite";
5
+ import { GENERATED_RUNTIME_MODULE } from "./runtime-module";
6
+
7
+ export { SQLiteDriver } from "teaql-ts/sql/sqlite";
8
+
9
+ export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient {
10
+ constructor(filename: string) {
11
+ super(filename, {});
12
+ this.install(GENERATED_RUNTIME_MODULE);
13
+ }
14
+ }
source/teaql-ts/examples/fix-e-alignment/generated/src/teaql-ts.ts ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider,
3
+ SelectQuery as RuntimeSelectQuery, UserContext,
4
+ GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout,
5
+ EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId,
6
+ } from "teaql-ts";
7
+
8
+ export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts";
9
+ export { decimal, compareDecimals } from "teaql-ts";
10
+ export type { Decimal } from "teaql-ts";
11
+ export { long, compareLongs, localTime } from "teaql-ts";
12
+ export type { Long, LocalTime } from "teaql-ts";
13
+ export { entityVersion, nextEntityVersion } from "teaql-ts";
14
+ export { internalId } from "teaql-ts";
15
+ export { EntityCreation, EntityCreationError } from "teaql-ts";
16
+ export { integer32Error } from "teaql-ts";
17
+ export type { EntityVersion } from "teaql-ts";
18
+ export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts";
19
+ export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts";
20
+ export type { EntityKey } from "teaql-ts";
21
+ export type { TeaQLPage } from "teaql-ts";
22
+ import type { QueryOperation } from "teaql-ts";
23
+ import type { EntitySchema } from "teaql-ts/sql/core";
24
+
25
+ function soundex(input: unknown): string {
26
+ const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, "");
27
+ if (!text) return "";
28
+ const code = (char: string): string => "BFPV".includes(char) ? "1"
29
+ : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3"
30
+ : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : "";
31
+ let result = text[0], previous = code(text[0]);
32
+ for (const char of text.slice(1)) {
33
+ const current = code(char);
34
+ if (current && current !== previous) result += current;
35
+ previous = current;
36
+ if (result.length === 4) break;
37
+ }
38
+ return (result + "000").slice(0, 4);
39
+ }
40
+
41
+ /** Generated naming adapter; query policy and execution remain in the formal runtime. */
42
+ export class SelectQuery extends RuntimeSelectQuery {
43
+ orderBy(field: string, direction: string): this {
44
+ return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any);
45
+ }
46
+
47
+ relationQuery(
48
+ name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true,
49
+ operation?: QueryOperation,
50
+ ): this {
51
+ return super.relationQuery(name, query, localKey, foreignKey, many, operation);
52
+ }
53
+ }
54
+
55
+ export interface TeaQLDataService {
56
+ reserveInternalId(entity: string, context: UserContext): Promise<string>;
57
+ executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T>;
58
+ preflightMutation(mutation: any): any;
59
+ afterGraphCommit(work: () => void): void;
60
+ afterGraphRollback(work: () => void): void;
61
+ executeMutation(mutation: any): Promise<any>;
62
+ executeQuery(query: any): Promise<any[]>;
63
+ executeCount(query: any, alias?: string, operation?: QueryOperation): Promise<number>;
64
+ executeForStream(query: any, chunkSize?: number): AsyncIterable<any[]>;
65
+ close?(): Promise<void>;
66
+ }
67
+
68
+ export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService {
69
+ private data: Record<string, Record<string, any>> = {};
70
+ private nextIds: Record<string, number> = {};
71
+ private readonly checkers: Record<string, EntityChecker> = {};
72
+ private readonly schemas: Record<string, EntitySchema> = {};
73
+ private userContext = new UserContext();
74
+ private graphSaveActive = false;
75
+ private activeGraph?: GraphMutationSession;
76
+ private graphCommitActions: Array<() => void> = [];
77
+ private graphRollbackActions: Array<() => void> = [];
78
+ private graphAuditActions: Array<() => Promise<void>> = [];
79
+ private graphSaveTail: Promise<void> = Promise.resolve();
80
+ private readonly mutationGovernanceEvents: any[] = [];
81
+ private readonly auditEvents: Readonly<Record<string, unknown>>[] = [];
82
+ private auditSink?: (event: Readonly<Record<string, unknown>>) => void | Promise<void>;
83
+
84
+ constructor(private storagePath?: string) {
85
+ super();
86
+ if (storagePath) {
87
+ const fs = require("fs");
88
+ if (fs.existsSync(storagePath)) {
89
+ const state = JSON.parse(fs.readFileSync(storagePath, "utf8"));
90
+ this.data = state.data || {};
91
+ this.nextIds = state.nextIds || {};
92
+ }
93
+ }
94
+ }
95
+
96
+ /** Installs passive generated metadata. It never mutates storage. */
97
+ install(module: RuntimeModule): this {
98
+ this.installBootstrap(module.bootstrap);
99
+ Object.assign(this.checkers, module.checkers);
100
+ Object.assign(this.schemas, module.schemas);
101
+ return this;
102
+ }
103
+
104
+ protected enterSchemaContext(context: UserContext): () => void {
105
+ const previous = this.userContext;
106
+ this.userContext = context;
107
+ return () => { this.userContext = previous; };
108
+ }
109
+
110
+ protected async ensurePhysicalSchema(_context: UserContext): Promise<void> {
111
+ // JSON/in-memory storage has no physical DDL. The runtime still requires
112
+ // the explicit Context invocation before running generated bootstrap.
113
+ }
114
+
115
+ private storagePayload(entity: string, payload: Record<string, any>): Record<string, any> {
116
+ const values = { ...payload };
117
+ for (const relation of Object.values(this.schemas[entity]?.relations || {})) {
118
+ if (relation.many) continue;
119
+ const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName;
120
+ const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName)
121
+ ? modelName : relation.localKey;
122
+ if (!Object.prototype.hasOwnProperty.call(values, field)) continue;
123
+ const value = values[field];
124
+ if (value === null || value === undefined || typeof value !== "object") continue;
125
+ if (value.id === null || value.id === undefined) {
126
+ throw new Error(`Unresolved relation identity: ${entity}.${field}`);
127
+ }
128
+ values[field] = String(value.id);
129
+ }
130
+ return values;
131
+ }
132
+
133
+ /** Physical/model keys stay canonical; generated entities use native TS members. */
134
+ private runtimeRecord(entity: string, record: Record<string, any>): Record<string, any> {
135
+ const columns = this.schemas[entity]?.columns;
136
+ if (!columns) return { ...record };
137
+ const result: Record<string, any> = {};
138
+ for (const [name, column] of Object.entries(columns)) {
139
+ const key = column.modelName ?? name;
140
+ result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key]
141
+ : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null;
142
+ }
143
+ if (result.version != null) result.version = entityVersion(result.version);
144
+ return result;
145
+ }
146
+
147
+ private checkedMutationVersion(mutation: any): EntityVersion | undefined {
148
+ if (mutation.action === "Create") return undefined;
149
+ if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined;
150
+ const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion);
151
+ if (mutation.version !== undefined && mutation.expectedVersion !== undefined
152
+ && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type");
153
+ nextEntityVersion(mutation.action, version);
154
+ return version;
155
+ }
156
+
157
+ private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any {
158
+ Object.defineProperties(mutation, {
159
+ version: { value: original, enumerable: true, writable: false, configurable: false },
160
+ expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false },
161
+ action: { value: mutation.action, enumerable: true, writable: false, configurable: false },
162
+ });
163
+ return mutation;
164
+ }
165
+
166
+ setUserContext(context: UserContext): this {
167
+ this.userContext = context;
168
+ return this;
169
+ }
170
+
171
+ get mutationGovernanceTrace(): readonly any[] {
172
+ return [...this.mutationGovernanceEvents];
173
+ }
174
+
175
+ get auditTrace(): ReadonlyArray<Readonly<Record<string, unknown>>> { return [...this.auditEvents]; }
176
+ setAuditSink(sink: (event: Readonly<Record<string, unknown>>) => void | Promise<void>): this {
177
+ this.auditSink = sink;
178
+ return this;
179
+ }
180
+
181
+ async reserveInternalId(entity: string, context: UserContext): Promise<string> {
182
+ if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation");
183
+ if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required");
184
+ if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save");
185
+ const predecessor = this.graphSaveTail;
186
+ let release!: () => void;
187
+ this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
188
+ await predecessor;
189
+ const previous = this.nextIds[entity];
190
+ try {
191
+ const id = internalId(previous ?? 1);
192
+ this.nextIds[entity] = Number(id) + 1;
193
+ this.persist();
194
+ return id;
195
+ } catch (error) {
196
+ if (previous === undefined) delete this.nextIds[entity];
197
+ else this.nextIds[entity] = previous;
198
+ throw error;
199
+ } finally { release(); }
200
+ }
201
+
202
+ private persist() {
203
+ if (!this.storagePath) return;
204
+ const fs = require("fs");
205
+ const path = require("path");
206
+ fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true });
207
+ const temporaryPath = `${this.storagePath}.tmp`;
208
+ fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds }));
209
+ fs.renameSync(temporaryPath, this.storagePath);
210
+ }
211
+
212
+ async executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T> {
213
+ const graph = new GraphMutationSession(intent);
214
+ const executionContext = this.userContext;
215
+ graph.bindExecutionReference(() => this.userContext);
216
+ graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()}));
217
+ for (const name of Object.keys(this.checkers)) {
218
+ graph.bindExecutionReference(() => this.checkers[name]);
219
+ graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix);
220
+ }
221
+ const predecessor = this.graphSaveTail;
222
+ let release!: () => void;
223
+ this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
224
+ await predecessor;
225
+ const dataSnapshot = JSON.parse(JSON.stringify(this.data));
226
+ const nextIdsSnapshot = { ...this.nextIds };
227
+ let fixEvidenceStarted = false;
228
+ let mutationPolicyGraphStarted = false;
229
+ let committed = false;
230
+ try {
231
+ graph.validatePreparedSources();
232
+ this.graphSaveActive = true;
233
+ this.activeGraph = graph;
234
+ this.graphCommitActions = [];
235
+ this.graphRollbackActions = [];
236
+ this.graphAuditActions = [];
237
+ const pending = admit?.(graph);
238
+ if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED");
239
+ graph.captureInputSources();
240
+ if (pending === false) { graph.sealPreparedGraph(); return await work(graph); }
241
+ // Reject a competing Context owner before changing its Fix resources.
242
+ executionContext.beginMutationPolicyGraph();
243
+ mutationPolicyGraphStarted = true;
244
+ executionContext.insertResource("fixTime", executionContext.businessTime());
245
+ executionContext.beginFixEvidence();
246
+ fixEvidenceStarted = true;
247
+ await prepare?.(graph);
248
+ if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph();
249
+ executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity);
250
+ graph.validatePreparedSources();
251
+ const result = await work(graph);
252
+ graph.requirePreparedComplete();
253
+ executionContext.ensureMutationPolicyGraphComplete();
254
+ if (!graph.isPreparedEmpty) this.persist();
255
+ committed = true;
256
+ let failure: unknown;
257
+ let failed = false;
258
+ for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) {
259
+ try { await action(); } catch (error) { if (!failed) failure = error; failed = true; }
260
+ }
261
+ if (failed) throw new GraphCommittedError(failure);
262
+ return result;
263
+ } catch (error) {
264
+ if (!committed) {
265
+ this.data = dataSnapshot;
266
+ this.nextIds = nextIdsSnapshot;
267
+ for (const action of [...this.graphRollbackActions].reverse()) {
268
+ try { action(); } catch { /* retain the original failure */ }
269
+ }
270
+ }
271
+ throw error;
272
+ } finally {
273
+ this.graphSaveActive = false;
274
+ this.activeGraph = undefined;
275
+ this.graphCommitActions = [];
276
+ this.graphRollbackActions = [];
277
+ this.graphAuditActions = [];
278
+ if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph();
279
+ if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence();
280
+ release();
281
+ }
282
+ }
283
+
284
+ afterGraphCommit(work: () => void): void {
285
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
286
+ this.graphCommitActions.push(work);
287
+ }
288
+
289
+ afterGraphRollback(work: () => void): void {
290
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
291
+ this.graphRollbackActions.push(work);
292
+ }
293
+
294
+ preflightMutation(mutation: any): any {
295
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
296
+ request.graphSession?.recordPreparedMutation();
297
+ mutation = this.checkAndFixMutation(request);
298
+ if (request.graphSession) {
299
+ const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())];
300
+ request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated",
301
+ parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) });
302
+ }
303
+ const schema = this.schemas[mutation.entity];
304
+ const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many)
305
+ .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity]));
306
+ const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation;
307
+ this.userContext.recordMutationPolicyPreflight(policyMutation);
308
+ return mutation;
309
+ }
310
+
311
+ private checkAndFixMutation(mutation: any): any {
312
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
313
+ if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) {
314
+ throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability");
315
+ }
316
+ const prepared = request.graphSession?.replayPreparedMutation(request);
317
+ if (prepared) return prepared;
318
+ mutation = request.mutation;
319
+ const schema = this.schemas[String(mutation.entity)];
320
+ if (schema) {
321
+ const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name));
322
+ fields.validate(mutation.payload ?? {}, mutation.action === "Update");
323
+ if (mutation.ledgerKey && mutation.ledgerRoot) {
324
+ if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");
325
+ fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update");
326
+ }
327
+ }
328
+ const originalVersion = this.checkedMutationVersion(mutation);
329
+ mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } };
330
+ request.bindCheckerLoadedValues(mutation);
331
+ Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true });
332
+ const declaringEntityType = String(mutation.entity);
333
+ const width = new ModeledInteger32Layout(declaringEntityType, schema);
334
+ const checker = this.checkers[declaringEntityType];
335
+ if (!checker) {
336
+ const violations = width.checkMutation(mutation.payload || {});
337
+ if (violations.length) throw new CheckException(violations);
338
+ return this.sealMutationVersion(mutation, originalVersion);
339
+ }
340
+ const results: any[] = [];
341
+ const ownsFixTime = this.userContext.getResource("fixTime") === undefined;
342
+ if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence();
343
+ try {
344
+ checker.checkAndFix(this.userContext, mutation, results);
345
+ if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion)
346
+ throw new MutationVersionError("invalid_type");
347
+ width.checkMutation(mutation.payload || {}, results);
348
+ this.userContext.translateCheckResults(results, declaringEntityType);
349
+ if (results.length) throw new CheckException(results);
350
+ // Loaded Delete values are validation/audit input, never field-write intent.
351
+ if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value);
352
+ return this.sealMutationVersion(mutation, originalVersion);
353
+ } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); }
354
+ }
355
+
356
+ async executeMutation(mutation: any): Promise<any> {
357
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
358
+ request.graphSession?.requireMutationAllowed();
359
+ mutation = this.checkAndFixMutation(request);
360
+ const nextVersion = nextEntityVersion(mutation.action, mutation.version);
361
+ const mutationGovernance = this.userContext.enterMutationPolicy(mutation);
362
+ const table = this.data[mutation.entity] ||= {};
363
+ const payload = this.storagePayload(mutation.entity, mutation.payload);
364
+ if (mutation.action === "Create") {
365
+ const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1);
366
+ if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`);
367
+ this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1);
368
+ const record = { ...payload, id: String(id), version: nextVersion };
369
+ table[String(id)] = record;
370
+ if (!this.graphSaveActive) this.persist();
371
+ return this.finishMutation(request, mutation, mutationGovernance,
372
+ { success: true, id: String(id), version: record.version, persistedRecord: { ...record } });
373
+ }
374
+ if (["Update", "Delete", "Recover"].includes(mutation.action)) {
375
+ const id = String(mutation.id);
376
+ if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
377
+ const expectedVersion = entityVersion(mutation.version);
378
+ const currentVersion = entityVersion(table[id].version);
379
+ if (expectedVersion !== currentVersion) {
380
+ throw new Error(
381
+ `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
382
+ }
383
+ table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion };
384
+ if (!this.graphSaveActive) this.persist();
385
+ return this.finishMutation(request, mutation, mutationGovernance,
386
+ { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } });
387
+ }
388
+ throw new Error(`Unsupported mutation action: ${mutation.action}`);
389
+ }
390
+ private async finishMutation(request: MutationRequest<any>, mutation: any,
391
+ mutationGovernance: unknown, result: any): Promise<any> {
392
+ request.graphSession?.recordPreparedResult(request, result);
393
+ const event = Object.freeze({ entity: mutation.entity, action: mutation.action,
394
+ id: result.id, version: result.version,
395
+ ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload),
396
+ changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()),
397
+ mutationGovernance,
398
+ actor: this.userContext.getResource("bootstrapActor"),
399
+ category: this.userContext.getResource("bootstrapCategory"),
400
+ recordedAt: (this.userContext.getResource<Date>("fixTime") ?? new Date()).toISOString() });
401
+ const publish = async () => {
402
+ this.mutationGovernanceEvents.push(mutationGovernance);
403
+ this.auditEvents.push(event);
404
+ await this.auditSink?.(event);
405
+ };
406
+ if (request.graphSession) this.graphAuditActions.push(publish);
407
+ else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } }
408
+ return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) };
409
+ }
410
+ async query(context: any, req: any): Promise<any> {
411
+ return { rows: [] };
412
+ }
413
+ async executeQuery(query: any): Promise<any> {
414
+ const request = query instanceof QueryRequest ? query : new QueryRequest(query);
415
+ query = request.query;
416
+ if (!(query instanceof RuntimeSelectQuery)) {
417
+ throw new Error("TeaQL list execution requires the formal runtime SelectQuery");
418
+ }
419
+ query.prepareForList();
420
+ const visibility = query.deletionVisibility ?? "live";
421
+ if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY");
422
+ let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row));
423
+ if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row =>
424
+ compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1));
425
+ const matches = (row: any, expression: any): boolean => {
426
+ if (expression?.$and) return expression.$and.every((item: any) => matches(row, item));
427
+ return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => {
428
+ const compare = (value: any): number => field === "version" && value != null && row[field] != null
429
+ ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value)))
430
+ : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1;
431
+ const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value);
432
+ if (predicate?.$eq !== undefined) return equal(predicate.$eq);
433
+ if (predicate?.$ne !== undefined) return !equal(predicate.$ne);
434
+ if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains));
435
+ if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains));
436
+ if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith));
437
+ if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith));
438
+ if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith));
439
+ if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith));
440
+ if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike);
441
+ if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value));
442
+ if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value));
443
+ if (predicate?.$between !== undefined) return field === "version"
444
+ ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0
445
+ : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1];
446
+ if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined;
447
+ if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined;
448
+ if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt;
449
+ if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte;
450
+ if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt;
451
+ if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte;
452
+ return true;
453
+ });
454
+ };
455
+ if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition));
456
+ if (query.aggregateItems?.length) {
457
+ return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => {
458
+ if (String(aggregate.function).toLowerCase() !== "count") {
459
+ throw new Error(`Unsupported local aggregate: ${aggregate.function}`);
460
+ }
461
+ return [aggregate.alias, rows.length];
462
+ }))];
463
+ }
464
+ for (const order of [...query.orderItems].reverse()) {
465
+ rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version))
466
+ : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1));
467
+ }
468
+ const start = query.offsetValue || 0;
469
+ rows = rows.slice(start, start + query.limitValue);
470
+ for (const relation of (query.relations || []) as any[]) {
471
+ for (const row of rows) {
472
+ // Scope before ordering/offset/limit. A nested bound belongs to
473
+ // each parent, not to unrelated children from earlier saves.
474
+ const childQuery = relation.query.clone();
475
+ childQuery.filter({$and: [childQuery.filterCondition ?? {},
476
+ {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]});
477
+ const matches = await this.executeQuery(request.derive(childQuery, relation.name));
478
+ row[relation.name] = relation.many === false ? matches[0] : matches;
479
+ }
480
+ }
481
+ if (query.selectItems.length > 0) {
482
+ const selections = new Set(query.selectItems);
483
+ for (const relation of (query.relations || []) as any[]) selections.add(relation.name);
484
+ rows = rows.map((row: any) => Object.fromEntries(
485
+ Object.entries(row).filter(([field]) => selections.has(field))));
486
+ }
487
+ const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]);
488
+ for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]);
489
+ return rows;
490
+ }
491
+ async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise<number> {
492
+ if (typeof query?.forExactCount !== "function") {
493
+ throw new Error("TeaQL exact count requires the formal runtime SelectQuery");
494
+ }
495
+ const alias = countAlias ?? "__teaql_total";
496
+ const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? {
497
+ kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) });
498
+ const rows = await this.executeQuery(request.query);
499
+ const value = rows[0]?.[alias];
500
+ if (typeof value !== "number" || !Number.isFinite(value)) {
501
+ throw new Error(`TeaQL provider did not return exact count alias ${alias}`);
502
+ }
503
+ return value;
504
+ }
505
+ async *executeForStream(query: any, chunkSize = 1000): AsyncIterable<any[]> {
506
+ query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query;
507
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer");
508
+ const rows = await this.executeQuery(query);
509
+ for (let offset = 0; offset < rows.length; offset += chunkSize) {
510
+ yield rows.slice(offset, offset + chunkSize);
511
+ }
512
+ }
513
+ }
514
+
515
+ declare const require: any;
516
+
517
+ export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; }
518
+ export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; }
source/teaql-ts/examples/fix-e-alignment/generated/teaql-i18n.json ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "teaql.i18n/v1",
3
+ "defaultLocale": "en",
4
+ "locales": {
5
+ "de": {
6
+ "vocabulary": {
7
+ },
8
+ "messages": {
9
+ }
10
+ },
11
+ "ko": {
12
+ "vocabulary": {
13
+ },
14
+ "messages": {
15
+ }
16
+ },
17
+ "pt": {
18
+ "vocabulary": {
19
+ },
20
+ "messages": {
21
+ }
22
+ },
23
+ "zh-TW": {
24
+ "vocabulary": {
25
+ },
26
+ "messages": {
27
+ }
28
+ },
29
+ "fil": {
30
+ "vocabulary": {
31
+ },
32
+ "messages": {
33
+ }
34
+ },
35
+ "en": {
36
+ "vocabulary": {
37
+ "property.orderItem.id": "Id",
38
+ "property.orderItem.createTime": "Create Time",
39
+ "property.purchaseOrder.id": "Id",
40
+ "property.orderItem.purchaseOrder": "Purchase Order",
41
+ "entity.orderItem": "Order Item",
42
+ "property.purchaseOrder.tenant": "Tenant",
43
+ "property.purchaseOrder.updateTime": "Update Time",
44
+ "property.orderItem.unitPrice": "Unit Price",
45
+ "property.purchaseOrder.internalNote": "Internal Note",
46
+ "property.tenant.id": "Id",
47
+ "property.orderItem.productName": "Product Name",
48
+ "entity.purchaseOrder": "Purchase Order",
49
+ "property.orderItem.tenant": "Tenant",
50
+ "property.orderItem.version": "Version",
51
+ "property.orderItem.updateTime": "Update Time",
52
+ "property.purchaseOrder.contactPhone": "Contact Phone",
53
+ "property.purchaseOrder.version": "Version",
54
+ "property.purchaseOrder.createTime": "Create Time",
55
+ "property.tenant.name": "Name",
56
+ "property.tenant.version": "Version",
57
+ "entity.tenant": "Tenant"
58
+ },
59
+ "messages": {
60
+ }
61
+ },
62
+ "fr": {
63
+ "vocabulary": {
64
+ },
65
+ "messages": {
66
+ }
67
+ },
68
+ "zh-CN": {
69
+ "vocabulary": {
70
+ },
71
+ "messages": {
72
+ }
73
+ },
74
+ "es": {
75
+ "vocabulary": {
76
+ },
77
+ "messages": {
78
+ }
79
+ },
80
+ "ar": {
81
+ "vocabulary": {
82
+ },
83
+ "messages": {
84
+ }
85
+ },
86
+ "vi": {
87
+ "vocabulary": {
88
+ },
89
+ "messages": {
90
+ }
91
+ },
92
+ "th": {
93
+ "vocabulary": {
94
+ },
95
+ "messages": {
96
+ }
97
+ },
98
+ "uk": {
99
+ "vocabulary": {
100
+ },
101
+ "messages": {
102
+ }
103
+ },
104
+ "ja": {
105
+ "vocabulary": {
106
+ },
107
+ "messages": {
108
+ }
109
+ },
110
+ "id": {
111
+ "vocabulary": {
112
+ },
113
+ "messages": {
114
+ }
115
+ }
116
+ }
117
+ }
source/teaql-ts/examples/fix-e-alignment/generated/tsconfig.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022",
4
+ "module": "commonjs",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "skipLibCheck": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "declaration": true
10
+ },
11
+ "include": ["src/**/*", "*.d.ts"]
12
+ }
source/teaql-ts/examples/fix-e-alignment/graph-fix-idempotence.test.ts ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {CheckException, decimal, FixedBusinessClock, UserContext} from '../../src';
2
+ import {Q} from 'generated/generated/Q';
3
+ import {E} from 'generated/generated/E';
4
+ import {SQLiteTeaQLClient} from 'generated/teaql-node-sqlite';
5
+
6
+ const emit = (name: string, facts: unknown) => process.stdout.write('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE=' + JSON.stringify({case: name, facts}) + '\n');
7
+ const database = process.env.TEAQL_FIX_E_DB! + '.idempotence.sqlite';
8
+ const instant = Date.parse('2033-01-02T03:04:05Z');
9
+ async function setup(filename: string) {
10
+ const context = new UserContext().withActiveRoot({entity: 'Tenant', id: '1'})
11
+ .withBusinessClock(new FixedBusinessClock(new Date(instant)));
12
+ const client = new SQLiteTeaQLClient(filename).setUserContext(context).setDiagnosticSQLLogSink(undefined);
13
+ context.insertResource('dataService', client); await context.ensureSchema();
14
+ return {context, client, driver: (client as any).driver};
15
+ }
16
+ async function make(context: UserContext, label: string) {
17
+ const parent = (await Q.purchaseOrders().comment('Prepare the graph owner ' + label).purpose('Verify Fix traversal identity')
18
+ .newEntity(context)).updateContactPhone('5550140');
19
+ const child = (await Q.orderItems().comment('Prepare the graph child ' + label).purpose('Verify one entity Fix per graph')
20
+ .newEntity(context)).updateProductName(label).updateUnitPrice(decimal('12.34'));
21
+ parent.orderItemList().push(child); return {parent, child};
22
+ }
23
+ function observe(client: SQLiteTeaQLClient, context: UserContext) {
24
+ const driver = (client as any).driver, checkers = (client as any).checkers;
25
+ const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'), allocation = jest.spyOn(driver, 'nextId');
26
+ const effects = () => [query.mock.calls.length, transaction.mock.calls.length, allocation.mock.calls.length];
27
+ const visits: Array<{entity: string; action: string; time: number; providerCallsDuringFix: number}> = [];
28
+ for (const type of ['PurchaseOrder', 'OrderItem']) {
29
+ const delegate = checkers[type]; checkers[type] = {checkAndFix(ctx: UserContext, mutation: any, results: any[]) {
30
+ const before = effects(); delegate.checkAndFix(ctx, mutation, results);
31
+ expect(effects()).toEqual(before);
32
+ visits.push({entity: type, action: mutation.action, time: context.requireResource<Date>('fixTime').getTime(), providerCallsDuringFix: 0});
33
+ }};
34
+ }
35
+ return {visits, effects, transaction, clear: () => {visits.length = 0; query.mockClear(); transaction.mockClear(); allocation.mockClear();}};
36
+ }
37
+
38
+ test('the same child instance reached twice is fixed and persisted once per invocation', async () => {
39
+ const filename = database, round = Number(process.env.TEAQL_FIX_E_ROUND);
40
+ const {client, context} = await setup(filename), observed = observe(client, context);
41
+ let tick = instant + round * 1000; const created = tick;
42
+ context.withBusinessClock({now: () => new Date(tick++)});
43
+ try {
44
+ const {parent, child} = (await make(context, 'Repeated child')); parent.orderItemList().push(child);
45
+ let failure: unknown;
46
+ try {await parent.auditAs('Create with repeated references to one child instance').save(context);} catch (error) {failure = error;}
47
+ const createFacts = {round, visits: [...observed.visits], clockCaptures: tick - created, providerEffects: observed.effects(),
48
+ error: failure instanceof Error ? {name: failure.name, code: (failure as any).code ?? null,
49
+ violations: failure instanceof CheckException ? failure.violations.map(v => ({ruleId: v.ruleId, path: v.location.modelPath()})) : []} : null,
50
+ scopeReleased: context.getResource('fixTime') === undefined && context.getResource('fixEvidenceCurrent') === undefined};
51
+ emit('duplicate-create', createFacts);
52
+ if (failure) throw failure;
53
+ expect(createFacts.visits.map(v => v.entity)).toEqual(['PurchaseOrder', 'OrderItem']);
54
+ expect(createFacts.visits.every(v => v.time === created && v.providerCallsDuringFix === 0)).toBe(true);
55
+ expect(tick).toBe(created + 1); expect(createFacts.scopeReleased).toBe(true);
56
+ parent.updateContactPhone('5550141'); child.updateUnitPrice(decimal('23.45')); observed.clear(); const updated = tick;
57
+ await parent.auditAs('Update the same repeated child once at a new graph instant').save(context);
58
+ expect(observed.visits.map(v => v.entity)).toEqual(['PurchaseOrder', 'OrderItem']); expect(observed.visits.every(v => v.time === updated)).toBe(true);
59
+ expect(tick).toBe(created + 2); expect(context.getResource('fixTime')).toBeUndefined(); expect(context.getResource('fixEvidenceCurrent')).toBeUndefined();
60
+ const owner = (await Q.purchaseOrders().withIdIs(parent.id!).limit(1).comment('Reload the deduplicated owner').purpose('Verify persisted Fix values').executeForList(context))[0];
61
+ const item = (await Q.orderItems().withIdIs(child.id!).limit(1).comment('Reload the deduplicated child').purpose('Verify once-only persistence').executeForList(context))[0];
62
+ expect(E.purchaseOrder(owner).version().eval()).toBe(2); expect(E.orderItem(item).version().eval()).toBe(2);
63
+ expect(new Date(E.orderItem(item).createTime().eval()!).getTime()).toBe(created); expect(new Date(E.orderItem(item).updateTime().eval()!).getTime()).toBe(updated);
64
+ expect(E.orderItem(item).productName().eval()).toBe('Repeated child'); expect(E.purchaseOrder(owner).contactPhone().eval()).toBe('5550141');
65
+ emit('duplicate-update', {round, visits: [...observed.visits], clockCaptures: 1, created, updated, parentId: parent.id, childId: child.id, version: 2});
66
+ } finally {await client.close();}
67
+ });
68
+
69
+ test('overlapping real generated graphs on separate contexts keep their own snapshot and receipt', async () => {
70
+ const filename = database, round = Number(process.env.TEAQL_FIX_E_ROUND);
71
+ const first = await setup(filename + '.first.sqlite'), second = await setup(filename + '.second.sqlite');
72
+ const a = observe(first.client, first.context), b = observe(second.client, second.context);
73
+ let tick = instant + round * 2000; const firstInstant = tick;
74
+ const clock = {now: () => new Date(tick++)}; first.context.withBusinessClock(clock); second.context.withBusinessClock(clock);
75
+ let entered!: () => void, release!: () => void;
76
+ const ready = new Promise<void>(resolve => {entered = resolve;}), hold = new Promise<void>(resolve => {release = resolve;});
77
+ const transaction = first.driver.transaction.bind(first.driver);
78
+ let pending: Promise<unknown> | undefined;
79
+ try {
80
+ const left = (await make(first.context, 'First context')), right = (await make(second.context, 'Second context'));
81
+ // Creation reserves IDs in its own transaction. Hold only the save boundary.
82
+ a.transaction.mockImplementationOnce(async (work: any) => {entered(); await hold; return transaction(work);});
83
+ pending = left.parent.auditAs('Hold the first generated graph before provider entry').save(first.context);
84
+ await Promise.race([ready, pending.then(() => {throw Error('first graph finished without reaching the held transaction');})]);
85
+ const receipt = first.context.getResource('fixEvidenceCurrent'); expect(receipt).toBeDefined();
86
+ await right.parent.auditAs('Commit another generated graph on an independent context').save(second.context);
87
+ expect(first.context.requireResource<Date>('fixTime').getTime()).toBe(firstInstant); expect(first.context.getResource('fixEvidenceCurrent')).toBe(receipt);
88
+ release(); await pending;
89
+ 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);
90
+ 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);}
91
+ emit('independent-real-graphs', {round, first: [...a.visits], second: [...b.visits], clockCaptures: 2, heldEvidencePreserved: true, scopesReleased: true,
92
+ receiptsIndependent: first.context.lastFixEvidence() !== second.context.lastFixEvidence()});
93
+ } finally {release(); if (pending) await pending.catch(() => undefined); await first.client.close(); await second.client.close();}
94
+ });
95
+
96
+ test('different object views of one ID are not silently skipped by the identity traversal guard', async () => {
97
+ const {client, context} = await setup(database + '.identity.sqlite');
98
+ const observed = observe(client, context), {parent, child} = (await make(context, 'Distinct views'));
99
+ try {
100
+ await parent.auditAs('Create a baseline for duplicate identity protection').save(context);
101
+ 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];
102
+ expect(other).not.toBe(child); expect(other.id).toBe(child.id);
103
+ child.updateUnitPrice(decimal('23.45')); other.updateUnitPrice(decimal('34.56')); parent.orderItemList().push(other); observed.clear();
104
+ let failure: unknown;
105
+ try {await parent.auditAs('Reject two conflicting views rather than skip by ID').save(context);} catch (error) {failure = error;}
106
+ expect(failure).toBeInstanceOf(CheckException); expect((failure as CheckException).violations.some(v => v.ruleId === 'mutation_changed_after_preparation')).toBe(true);
107
+ expect(observed.effects()).toEqual([0, 0, 0]);
108
+ 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];
109
+ expect(E.orderItem(persisted).version().eval()).toBe(1); expect(String(E.orderItem(persisted).unitPrice().eval())).toBe('12.34');
110
+ 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'});
111
+ } finally {await client.close();}
112
+ });
source/teaql-ts/examples/fix-e-alignment/loading-probe.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, TeaQLNotLoadedError, UserContext } from '../../src';
2
+ import { E } from 'generated/generated/E';
3
+ import { Q } from 'generated/generated/Q';
4
+
5
+ export async function verifyLoading(context: UserContext,
6
+ orderId: Parameters<ReturnType<typeof Q.purchaseOrders>['withIdIs']>[0]): Promise<void> {
7
+ const rows = await Q.purchaseOrders().withIdIs(orderId)
8
+ .selectTenantWith(Q.tenantsWithMinimalFields().withIdIs('2').limit(1)
9
+ .comment("Load only a different tenant's detail"))
10
+ .limit(1).comment('Keep the selected FK when target detail is filtered out')
11
+ .purpose('Verify filtered target detail is NotLoaded rather than loaded null').executeForList(context);
12
+ expect(rows).toHaveLength(1);
13
+ const owner = rows[0];
14
+ expect(String(E.purchaseOrder(owner).tenantId().eval())).toBe('1');
15
+ let detail: ReturnType<TeaQLNotLoadedError['toWire']> | undefined;
16
+ try { E.purchaseOrder(owner).tenant().name().eval(); }
17
+ catch (error) {
18
+ if (!(error instanceof TeaQLNotLoadedError)) throw error;
19
+ detail = error.toWire();
20
+ expect(detail.code).toBe('NOT_LOADED');
21
+ expect(detail.attemptedInstancePath).toBe('/tenant/name');
22
+ }
23
+ expect(detail).toBeDefined();
24
+ owner.updateContactPhone('5550102');
25
+ await owner.auditAs('Change only the complete owner').save(context);
26
+ const complete = await Q.purchaseOrders().withIdIs(orderId).limit(1)
27
+ .comment('Reload the successful owner update')
28
+ .purpose('Verify untouched partial targets do not prevent saving the owner').executeForList(context);
29
+ expect(complete).toHaveLength(1);
30
+ expect(E.purchaseOrder(complete[0]).contactPhone().eval()).toBe('5550102');
31
+ const version = E.purchaseOrder(complete[0]).version().eval();
32
+ const partial = await Q.purchaseOrdersWithMinimalFields().withIdIs(orderId).limit(1)
33
+ .comment('Load an identity-only owner')
34
+ .purpose('Reject changes to an incomplete owner before persistence').executeForList(context);
35
+ expect(partial).toHaveLength(1);
36
+ partial[0].updateContactPhone('5550103');
37
+ let rejected = false;
38
+ try { await partial[0].auditAs('Attempt to modify an incomplete owner').save(context); }
39
+ catch (error) {
40
+ if (!(error instanceof CheckException)) throw error;
41
+ expect(error.violations.some(result => result.ruleId === 'invalid_type')).toBe(true);
42
+ rejected = true;
43
+ }
44
+ expect(rejected).toBe(true);
45
+ const unchanged = await Q.purchaseOrders().withIdIs(orderId).limit(1)
46
+ .comment('Reload after the rejected incomplete mutation')
47
+ .purpose('Verify persisted values and optimistic version remain unchanged').executeForList(context);
48
+ expect(unchanged).toHaveLength(1);
49
+ expect(E.purchaseOrder(unchanged[0]).contactPhone().eval()).toBe('5550102');
50
+ expect(E.purchaseOrder(unchanged[0]).version().eval()).toEqual(version);
51
+ process.stdout.write('CORE_LOAD_EXAMPLE=' + JSON.stringify({
52
+ language: 'typescript', passed: true, foreignKeyPreserved: true, filteredDetailNotLoaded: detail,
53
+ untouchedPartialTargetSave: true, modifiedPartialOwnerRejected: true, rejectedVersionUnchanged: true,
54
+ }) + '\n');
55
+ }
source/teaql-ts/examples/fix-e-alignment/model.xml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <root name="checker-fix-advanced" org="teaql" data_service="sqlite">
3
+ <tenant name="Tenant Name|[1,80]"/>
4
+ <purchase_order
5
+ tenant="tenant(contextRoot=true)"
6
+ contact_phone="Contact Phone|[1,32]"
7
+ internal_note="Optional note?"
8
+ create_time="createTime()"
9
+ update_time="updateTime()"/>
10
+ <order_item
11
+ purchase_order="purchase_order()"
12
+ tenant="tenant(contextRoot=true)"
13
+ product_name="Product Name|[1,80]"
14
+ unit_price="10.00|[0.01,1000000]"
15
+ create_time="createTime()"
16
+ update_time="updateTime()"/>
17
+ </root>
source/teaql-ts/examples/fix-e-alignment/owned-command.cjs ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+ // POSIX compiler/test runner. The detached group belongs only to this command;
3
+ // no service, shared cache or other session is a termination target.
4
+ const cp = require('node:child_process');
5
+ const fs = require('node:fs'), path = require('node:path');
6
+ const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
7
+ function alive(pid) {
8
+ try { process.kill(-pid, 0); return true; }
9
+ catch (error) { if (error.code === 'ESRCH') return false; throw error; }
10
+ }
11
+ function signal(pid, name) {
12
+ if (!pid) return;
13
+ try { process.kill(-pid, name); }
14
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
15
+ }
16
+ function createOwnedRunner() {
17
+ let active, interrupted, unsafeGroup, killer;
18
+ const terminateActive = () => {
19
+ if (!active?.pid) return;
20
+ signal(active.pid, 'SIGTERM');
21
+ killer ||= setTimeout(() => { if (active?.pid) signal(active.pid, 'SIGKILL'); }, 500);
22
+ };
23
+ const cancel = name => {
24
+ interrupted ||= name;
25
+ terminateActive();
26
+ };
27
+ const onInt = () => cancel('SIGINT'), onTerm = () => cancel('SIGTERM');
28
+ process.on('SIGINT', onInt); process.on('SIGTERM', onTerm);
29
+ return {
30
+ get interrupted() { return interrupted; },
31
+ get unsafeGroup() { return unsafeGroup; },
32
+ get safeToClean() { return !active && !unsafeGroup; },
33
+ cancel,
34
+ async run(command, options) {
35
+ if (active) throw new Error('owned commands must be awaited, not overlapped');
36
+ if (interrupted) return {status: interrupted === 'SIGINT' ? 130 : 143, signal: interrupted};
37
+ let timedOut = false, timer;
38
+ const {timeout, ...spawnOptions} = options;
39
+ const child = cp.spawn(command[0], command.slice(1), {...spawnOptions, detached: true});
40
+ active = child;
41
+ try {
42
+ const result = await new Promise(resolve => {
43
+ child.once('error', error => resolve({status: null, signal: null, error: error.message}));
44
+ child.once('close', (status, childSignal) => resolve({status, signal: childSignal}));
45
+ timer = setTimeout(() => { timedOut = true; terminateActive(); }, timeout);
46
+ });
47
+ clearTimeout(timer);
48
+ // Reap the direct child and stop any compiler descendants which outlive
49
+ // it. Keep signal handlers installed until the complete owned group ends.
50
+ if (child.pid && alive(child.pid)) {
51
+ signal(child.pid, 'SIGTERM');
52
+ for (let attempt = 0; attempt < 100 && alive(child.pid); attempt++) {
53
+ if (attempt === 10) signal(child.pid, 'SIGKILL');
54
+ await delay(25);
55
+ }
56
+ if (alive(child.pid)) { unsafeGroup = child.pid; throw new Error('owned process group remains live: ' + child.pid); }
57
+ }
58
+ if (timedOut) return {...result, status: 124};
59
+ if (interrupted) return {...result, status: interrupted === 'SIGINT' ? 130 : 143};
60
+ return result;
61
+ } finally { clearTimeout(timer); clearTimeout(killer); killer = undefined; active = undefined; }
62
+ },
63
+ dispose() {
64
+ if (active) throw new Error('cannot dispose a live owned command');
65
+ process.off('SIGINT', onInt); process.off('SIGTERM', onTerm);
66
+ },
67
+ };
68
+ }
69
+ function ownedBytes(directory) {
70
+ const seen = new Set();
71
+ function visit(file) {
72
+ const stat = fs.lstatSync(file), key = stat.dev + ':' + stat.ino;
73
+ if (seen.has(key)) return 0;
74
+ seen.add(key);
75
+ return stat.size + (stat.isDirectory() ? fs.readdirSync(file).reduce((sum, name) => sum + visit(path.join(file, name)), 0) : 0);
76
+ }
77
+ return visit(directory);
78
+ }
79
+ module.exports = {createOwnedRunner, alive, ownedBytes};
source/teaql-ts/examples/fix-e-alignment/ownership-probe.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserContext } from '../../src';
2
+ import { E } from 'generated/generated/E';
3
+ import { Q } from 'generated/generated/Q';
4
+ import { verifyPageStream } from './paged-ownership';
5
+
6
+ export async function verifyOwnership(context: UserContext): Promise<void> {
7
+ const before = await Q.purchaseOrders().limit(20).comment('Inspect the initial ownership fixture')
8
+ .purpose('Verify Context and multi-root results do not own shared mutation ledgers').executeForList(context);
9
+ const first = (await Q.purchaseOrders().comment('Prepare independent new owner A')
10
+ .purpose('Verify Context does not own mutation ledgers').newEntity(context));
11
+ const second = (await Q.purchaseOrders().comment('Prepare independent new owner B')
12
+ .purpose('Verify Context does not own mutation ledgers').newEntity(context));
13
+ first.updateContactPhone('5550300'); second.updateContactPhone('5550400');
14
+ const savedA = await first.auditAs('Save only independent new owner A').save(context);
15
+ const initial = await Q.purchaseOrders().limit(20).comment("Inspect A's save before saving B")
16
+ .purpose('Verify an independent new owner did not leak into persistence').executeForList(context);
17
+ expect(initial).toHaveLength(before.length + 1);
18
+ const savedB = await second.auditAs('Explicitly save independent new owner B').save(context);
19
+ const batch = await Q.purchaseOrders().limit(20).comment('Load independent owners in one batch')
20
+ .purpose('Verify independently saveable list roots retain separate mutation boundaries').executeForList(context);
21
+ expect(batch).toHaveLength(before.length + 2);
22
+ const ownerA = batch.find(row => row.id === savedA.id)!;
23
+ const ownerB = batch.find(row => row.id === savedB.id)!;
24
+ expect(ownerA).toBeDefined(); expect(ownerB).toBeDefined();
25
+ ownerA.updateContactPhone('5550301'); ownerB.updateContactPhone('5550401');
26
+ await ownerA.auditAs('Save only A from a multi-root query result').save(context);
27
+ const unchanged = (await Q.purchaseOrders().withIdIs(savedB.id!).limit(1)
28
+ .comment('Inspect B after saving only A').purpose('Verify A neither persists nor commits B').executeForList(context))[0];
29
+ expect(E.purchaseOrder(unchanged).contactPhone().eval()).toBe('5550400');
30
+ expect(E.purchaseOrder(unchanged).version().eval()).toBe(1);
31
+ await ownerB.auditAs('Save B after A without discarding its pending mutation').save(context);
32
+ const changed = (await Q.purchaseOrders().withIdIs(savedB.id!).limit(1)
33
+ .comment('Inspect the later independent B save').purpose("Verify B's pending mutation survived A's save").executeForList(context))[0];
34
+ expect(E.purchaseOrder(changed).contactPhone().eval()).toBe('5550401');
35
+ expect(E.purchaseOrder(changed).version().eval()).toBe(2);
36
+ await verifyPageStream(context, savedA.id!, savedB.id!);
37
+ process.stdout.write('CORE_MUTATION_OWNERSHIP=' + JSON.stringify({
38
+ language: 'typescript', passed: true, independentNewRoots: true,
39
+ batchRootIsolation: true, siblingVersionUnchanged: true, siblingPendingMutationRetained: true,
40
+ }) + '\n');
41
+ }
source/teaql-ts/examples/fix-e-alignment/paged-ownership.ts ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserContext } from '../../src';
2
+ import { E } from 'generated/generated/E';
3
+ import { Q } from 'generated/generated/Q';
4
+ import { PurchaseOrder } from 'generated/generated/models/PurchaseOrder';
5
+
6
+ export async function verifyPageStream(context: UserContext,
7
+ idA: Parameters<ReturnType<typeof Q.purchaseOrders>['withIdIs']>[0],
8
+ idB: Parameters<ReturnType<typeof Q.purchaseOrders>['withIdIs']>[0]): Promise<void> {
9
+ const before = await Q.purchaseOrders().limit(20).comment('Inspect the page ownership fixture')
10
+ .purpose('Establish the bounded exact total').executeForList(context);
11
+ const sentinel = (await Q.purchaseOrders().comment('Prepare a page-offset sentinel')
12
+ .purpose('Exercise a genuine nonzero page offset').newEntity(context));
13
+ sentinel.updateContactPhone('5550500');
14
+ await sentinel.auditAs('Save the synthetic page sentinel').save(context);
15
+ const exercise = async (rows: Iterable<PurchaseOrder>, label: string, previous: string, next: string, version: number) => {
16
+ const values = Array.from(rows);
17
+ const a = values.find(row => row.id === idA)!; const b = values.find(row => row.id === idB)!;
18
+ expect(a).toBeDefined(); expect(b).toBeDefined();
19
+ a.updateContactPhone('55503' + next.slice(-2)); b.updateContactPhone(next);
20
+ await Q.tenantsWithMinimalFields().limit(1).comment('Run an unrelated query before deferred saves')
21
+ .purpose('Verify deferred ownership survives Context reuse').executeForList(context);
22
+ await a.auditAs('Save only A from ' + label).save(context);
23
+ let persisted = await Q.purchaseOrders().withIdIs(idB).limit(1).comment('Inspect B after deferred A save')
24
+ .purpose('Verify unrelated root value and version remain untouched').executeForList(context);
25
+ expect(persisted).toHaveLength(1);
26
+ expect(E.purchaseOrder(persisted[0]).contactPhone().eval()).toBe(previous);
27
+ expect(E.purchaseOrder(persisted[0]).version().eval()).toBe(version);
28
+ await b.auditAs('Save B later from ' + label).save(context);
29
+ persisted = await Q.purchaseOrders().withIdIs(idB).limit(1).comment('Inspect the later deferred B save')
30
+ .purpose("Verify B's pending mutation survived A's commit").executeForList(context);
31
+ expect(persisted).toHaveLength(1);
32
+ expect(E.purchaseOrder(persisted[0]).contactPhone().eval()).toBe(next);
33
+ expect(E.purchaseOrder(persisted[0]).version().eval()).toBe(version + 1);
34
+ };
35
+ const page = await Q.purchaseOrders().orderByIdDescending().offset(1).limit(2).count()
36
+ .comment('Load a nonzero-offset page of independent roots').purpose('Verify exact count and page ownership').executeForList(context);
37
+ expect(page).toHaveLength(2); expect(page.totalCount).toBe(before.length + 1);
38
+ await exercise(page, 'a nonzero-offset page', '5550401', '5550402', 2);
39
+ const streamed: PurchaseOrder[] = [];
40
+ for await (const row of Q.purchaseOrders().orderByIdAscending().limit(20)
41
+ .comment('Stream independent roots across single-row chunks').purpose('Verify cross-chunk deferred-save ownership')
42
+ .executeForStream(context, 1)) streamed.push(row);
43
+ expect(streamed).toHaveLength(before.length + 1);
44
+ await exercise(streamed, 'a fully consumed scalar stream', '5550402', '5550403', 3);
45
+ process.stdout.write('CORE_MUTATION_PAGING=' + JSON.stringify({
46
+ language: 'typescript', passed: true, pageOffset: 1, pageSize: 2, exactCount: before.length + 1,
47
+ pageRootIsolation: true, deferredSaveAfterContextReuse: true, streamProfile: 'scalar-typed',
48
+ streamChunkSize: 1, streamRootIsolation: true, siblingPendingMutationRetained: true,
49
+ }) + '\n');
50
+ }
source/teaql-ts/examples/fix-e-alignment/partial-ancestors-probe.ts ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src';
2
+ import { checkResultToWire } from '../../src/core/i18n';
3
+ import { Q } from 'generated/generated/Q';
4
+ import { E } from 'generated/generated/E';
5
+ import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite';
6
+ import Database from 'better-sqlite3';
7
+
8
+ /** Generated Q/E and audited save; no generated implementations are edited. */
9
+ export async function verifyPartialAncestors(filename: string): Promise<void> {
10
+ const createdAt = new Date('2032-02-29T10:15:30Z');
11
+ const updatedAt = new Date(createdAt.getTime() + 24 * 60 * 60 * 1000);
12
+ const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt));
13
+ const client = new SQLiteTeaQLClient(filename).setUserContext(context);
14
+ context.insertResource('dataService', client);
15
+ const driver = (client as any).driver;
16
+ const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction');
17
+ const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy');
18
+ const review = jest.fn(() => undefined);
19
+ context.withMutationPolicyRegistry({resolve: review});
20
+ let auditStart = 0;
21
+ const effects = () => ({queries: query.mock.calls.length, transactions: transaction.mock.calls.length,
22
+ allocations: allocation.mock.calls.length, policies: policy.mock.calls.length, reviews: review.mock.calls.length,
23
+ audits: client.auditTrace.length - auditStart,
24
+ mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i
25
+ .test(String(call[0]).replace(/"/g, ''))).length});
26
+ const reset = () => {query.mockClear(); transaction.mockClear(); allocation.mockClear();
27
+ policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length;};
28
+ const zero = {queries: 0, transactions: 0, allocations: 0, policies: 0, reviews: 0, audits: 0, mutations: 0};
29
+ try {
30
+ await context.ensureSchema();
31
+ reset();
32
+ const order = (await Q.purchaseOrders().comment('Prepare the partial-ancestor fixture')
33
+ .purpose('Validate only modified business objects for graph saves').newEntity(context))
34
+ .updateContactPhone('5550600').updateInternalNote(null);
35
+ const child = (await Q.orderItems().comment('Prepare one complete leaf')
36
+ .purpose('Use the generated relation and audited save').newEntity(context))
37
+ .updateProductName('Partial graph original').updateUnitPrice(decimal('10.00'));
38
+ order.orderItemList().push(child);
39
+ const reservations = effects();
40
+ expect(reservations.transactions).toBe(2); expect(reservations.allocations).toBe(2);
41
+ expect(reservations.mutations).toBe(0); expect(reservations.audits).toBe(0);
42
+ reset();
43
+ await order.auditAs('Create the partial-ancestor graph').save(context);
44
+ const calibration = effects();
45
+ expect(calibration.transactions).toBe(1); expect(calibration.allocations).toBe(0);
46
+ expect(calibration.mutations).toBe(2); expect(calibration.audits).toBe(2);
47
+ expect(calibration.policies).toBeGreaterThan(0); expect(calibration.reviews).toBeGreaterThan(0);
48
+ if (!order.id) throw new Error('the saved order has no real identity');
49
+ const orderId = order.id, active = context.requireActiveRoot('Tenant');
50
+ const seeded = (await Q.purchaseOrders().withIdIs(orderId)
51
+ .selectOrderItemListWith(Q.orderItems().limit(1).comment('Read the persisted fixture leaf'))
52
+ .limit(1).comment('Read the saved graph identity').purpose('Do not infer a child ID from allocation order')
53
+ .executeForList(context))[0];
54
+ expect(E.purchaseOrder(seeded).orderItemList().size().eval()).toBe(1);
55
+ const childId = E.purchaseOrder(seeded).orderItemList().first().id().eval();
56
+ if (!childId) throw new Error('the saved leaf has no real identity');
57
+ const load = async (complete: boolean) => {
58
+ const leaf = (complete ? Q.orderItems() : Q.orderItemsWithMinimalFields()).withIdIs(childId)
59
+ .limit(1).comment(complete ? 'Load every scalar of the modified leaf' : 'Load an incomplete modified leaf');
60
+ const root = (await Q.tenantsWithMinimalFields().withIdIs(String(active.id))
61
+ .selectPurchaseOrderListWith(Q.purchaseOrdersWithMinimalFields().withIdIs(orderId)
62
+ .selectOrderItemListWith(leaf).limit(1).comment('Keep the untouched parent partial'))
63
+ .limit(1).comment('Load two untouched partial ancestors above one leaf')
64
+ .purpose('Exercise Q E JSON and graph mutation in one bounded example').executeForList(context))[0];
65
+ expect(root).toBeDefined(); expect(E.tenant(root).purchaseOrderList().size().eval()).toBe(1);
66
+ const parent = root.purchaseOrderList()[0];
67
+ expect(E.purchaseOrder(parent).orderItemList().size().eval()).toBe(1);
68
+ return {root, parent, leaf: parent.orderItemList()[0]};
69
+ };
70
+ const graph = await load(true);
71
+ const empty = (await Q.purchaseOrdersWithMinimalFields().withIdIs(orderId)
72
+ .selectOrderItemListWith(Q.orderItemsWithMinimalFields().withIdIs('0').limit(1)
73
+ .comment('Explicitly select an empty child list'))
74
+ .limit(1).comment('Distinguish selected empty from an unselected reverse relation')
75
+ .purpose('Native JSON must preserve relation availability without querying').executeForList(context))[0];
76
+ expect(E.purchaseOrder(empty).orderItemList().size().eval()).toBe(0);
77
+ reset();
78
+ const missing = (read: () => unknown, pointer: string) => {
79
+ let failure: unknown; try {read();} catch (error) {failure = error;}
80
+ expect(failure).toBeInstanceOf(TeaQLNotLoadedError);
81
+ expect((failure as TeaQLNotLoadedError).toWire().instancePath).toBe(pointer);
82
+ };
83
+ missing(() => E.tenant(graph.root).name().eval(), '/name');
84
+ missing(() => E.tenant(graph.root).purchaseOrderList().first().contactPhone().eval(), '/purchaseOrderList/0/contactPhone');
85
+ expect(String(E.orderItem(graph.leaf).unitPrice().eval())).toBe(String(decimal('10.00')));
86
+ const json = JSON.parse(JSON.stringify(graph.root));
87
+ expect(json).not.toHaveProperty('name'); expect(json.purchaseOrderList).toHaveLength(1);
88
+ expect(json).not.toHaveProperty('orderItemList');
89
+ expect(json.purchaseOrderList[0]).not.toHaveProperty('contactPhone');
90
+ expect(json.purchaseOrderList[0].orderItemList).toHaveLength(1);
91
+ expect(JSON.parse(JSON.stringify(empty)).orderItemList).toEqual([]);
92
+ expect(effects()).toEqual(zero); const guardEffects = effects();
93
+ context.withBusinessClock(new FixedBusinessClock(updatedAt));
94
+ graph.leaf.updateProductName('Partial graph updated');
95
+ await graph.root.auditAs('Save the complete modified leaf through untouched partial ancestors').save(context);
96
+ const saveEffects = effects();
97
+ expect(saveEffects.transactions).toBe(1); expect(saveEffects.allocations).toBe(0);
98
+ expect(saveEffects.mutations).toBe(1); expect(saveEffects.audits).toBe(1);
99
+ expect(saveEffects.policies).toBeGreaterThan(0); expect(saveEffects.reviews).toBeGreaterThan(0);
100
+ const physical = () => {
101
+ const db = new Database(filename, {readonly: true, fileMustExist: true});
102
+ try {return {
103
+ roots: db.prepare('SELECT id,name,version FROM tenant_data ORDER BY id').all(),
104
+ parents: db.prepare('SELECT id,tenant,contact_phone,internal_note,version,create_time,update_time FROM purchase_order_data WHERE id = ?').all(orderId),
105
+ 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),
106
+ };} finally {db.close();}
107
+ };
108
+ const stored = physical();
109
+ expect(stored.roots).toEqual([{id: Number(active.id), name: 'Tenant Name', version: 1}]);
110
+ expect(stored.parents).toEqual([expect.objectContaining({id: Number(orderId), tenant: Number(active.id), contact_phone: '5550600', internal_note: null,
111
+ version: 1, create_time: createdAt.getTime(), update_time: createdAt.getTime()})]);
112
+ expect(stored.leaves).toEqual([expect.objectContaining({id: Number(childId), purchase_order: Number(orderId), tenant: Number(active.id),
113
+ product_name: 'Partial graph updated', unit_price: String(decimal('10.00')), version: 2,
114
+ create_time: createdAt.getTime(), update_time: updatedAt.getTime()})]);
115
+ const partial = await load(false);
116
+ partial.leaf.updateProductName('Rejected partial leaf');
117
+ const key = {entity: 'OrderItem', id: (partial.leaf as any)._ledgerId};
118
+ const pending = () => JSON.stringify((partial.leaf as any)._root.change(key));
119
+ const before = pending(), rejections: unknown[][] = [], rejectionEffects: Array<ReturnType<typeof effects>> = [];
120
+ for (let attempt = 0; attempt < 2; attempt++) {
121
+ reset(); let failure: unknown;
122
+ try {await partial.root.auditAs('Reject the incomplete modified leaf before any provider work').save(context);}
123
+ catch (error) {failure = error;}
124
+ expect(failure).toBeInstanceOf(CheckException);
125
+ const violations = (failure as CheckException).violations.map(result => checkResultToWire(result));
126
+ expect(violations.length).toBeGreaterThan(0);
127
+ for (const violation of violations) {
128
+ expect(violation.ruleId).toBe('invalid_type'); expect(violation.entityType).toBe('OrderItem');
129
+ expect(violation.instancePath).toMatch(/^\/purchaseOrderList\/0\/orderItemList\/0\//);
130
+ }
131
+ expect(effects()).toEqual(zero); expect(pending()).toBe(before); expect(physical()).toEqual(stored);
132
+ rejections.push(violations); rejectionEffects.push(effects());
133
+ }
134
+ process.stdout.write('CORE_TS_PARTIAL_ANCESTORS_RESULT=' + JSON.stringify({language: 'typescript', passed: true,
135
+ orderId: String(orderId), leafId: String(childId), ancestorVersions: [1, 1], leafVersion: 2, calibration, guardEffects, saveEffects,
136
+ cases: ['partial-ancestor-guards-and-JSON-no-I/O', 'complete-leaf-saved-through-two-untouched-partial-ancestors',
137
+ 'partial-leaf-rejected-twice-before-provider-with-intent-retained'], rejections, rejectionEffects,
138
+ intentRetained: true, selectedEmptySerialized: true, unselectedListOmitted: true, generatedImplementationsModified: false}) + '\n');
139
+ } finally {
140
+ query.mockRestore(); transaction.mockRestore(); allocation.mockRestore(); policy.mockRestore(); await client.close();
141
+ }
142
+ }
source/teaql-ts/examples/fix-e-alignment/partial-root-probe.ts ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src';
2
+ import { checkResultToWire } from '../../src/core/i18n';
3
+ import { Q } from 'generated/generated/Q';
4
+ import { E } from 'generated/generated/E';
5
+ import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite';
6
+ import Database from 'better-sqlite3';
7
+
8
+ /** Application-owned regression; all business preparation uses generated Q/E/save. */
9
+ export async function verifyPartialRoot(filename: string): Promise<void> {
10
+ const createdAt = new Date('2032-04-01T10:15:30Z');
11
+ const updatedAt = new Date(createdAt.getTime() + 86400000);
12
+ const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt));
13
+ const client = new SQLiteTeaQLClient(filename).setUserContext(context);
14
+ context.insertResource('dataService', client);
15
+ const driver = (client as any).driver;
16
+ const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction');
17
+ const exec = jest.spyOn(driver.database as Database.Database, 'exec');
18
+ const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy');
19
+ const review = jest.fn(() => undefined);
20
+ context.withMutationPolicyRegistry({resolve: review});
21
+ let auditStart = 0;
22
+ const effects = () => ({
23
+ queries: query.mock.calls.length, transactions: transaction.mock.calls.length,
24
+ begins: exec.mock.calls.filter(call => /^BEGIN\b/i.test(call[0])).length,
25
+ commits: exec.mock.calls.filter(call => /^COMMIT\b/i.test(call[0])).length,
26
+ rollbacks: exec.mock.calls.filter(call => /^ROLLBACK\b/i.test(call[0])).length,
27
+ allocations: allocation.mock.calls.length, policyLookups: policy.mock.calls.length,
28
+ policyReviews: review.mock.calls.length, audits: client.auditTrace.length - auditStart,
29
+ mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i
30
+ .test(String(call[0]).replace(/"/g, ''))).length,
31
+ rootLookups: query.mock.calls.filter(call => /\bFROM\s+tenant_data\b/i.test(String(call[0]).replace(/"/g, ''))).length,
32
+ });
33
+ const reset = () => {
34
+ query.mockClear(); transaction.mockClear(); exec.mockClear(); allocation.mockClear();
35
+ policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length;
36
+ };
37
+ const zero = {queries: 0, transactions: 0, begins: 0, commits: 0, rollbacks: 0,
38
+ allocations: 0, policyLookups: 0, policyReviews: 0, audits: 0, mutations: 0, rootLookups: 0};
39
+ const physical = () => {
40
+ const db = new Database(filename, {readonly: true, fileMustExist: true});
41
+ try { return {
42
+ tenant_data: db.prepare('SELECT id,version,name FROM tenant_data ORDER BY id').all(),
43
+ 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(),
44
+ 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(),
45
+ }; } finally { db.close(); }
46
+ };
47
+ try {
48
+ await context.ensureSchema();
49
+ const active = context.requireActiveRoot('Tenant');
50
+ reset();
51
+ const other = (await Q.tenants().comment('Prepare another persisted domain root')
52
+ .purpose('Test wrong context with a real root, not an invented ID').newEntity(context))
53
+ .updateName('Independent partial root');
54
+ await other.auditAs('Create an independent root for managed-root verification').save(context);
55
+ expect(other.id).toBeTruthy(); expect(String(other.id)).not.toBe(String(active.id));
56
+ const order = (await Q.purchaseOrders().comment('Prepare the managed partial-ancestor fixture')
57
+ .purpose('Verify ownership through an unchanged sparse graph').newEntity(context))
58
+ .updateContactPhone('5550801').updateInternalNote(null);
59
+ const child = (await Q.orderItems().comment('Prepare the complete managed leaf')
60
+ .purpose('Persist a leaf owned by the original domain root').newEntity(context))
61
+ .updateProductName('Managed partial original').updateUnitPrice(decimal('10.00'));
62
+ order.orderItemList().push(child);
63
+ await order.auditAs('Create the owned graph for partial-ancestor admission').save(context);
64
+ expect(order.id).toBeTruthy(); expect(child.id).toBeTruthy();
65
+ const orderId = order.id!, childId = child.id!;
66
+ await Q.tenants().withIdIs(String(other.id)).limit(1).comment('Calibrate root SELECT observation')
67
+ .purpose('Prove that admission would detect provider root lookups').executeForList(context);
68
+ const rollback = new Error('intentional observer calibration');
69
+ await expect(driver.transaction(async () => { throw rollback; })).rejects.toBe(rollback);
70
+ const calibration = effects();
71
+ for (const count of Object.values(calibration)) expect(count).toBeGreaterThan(0);
72
+ const root = (await Q.tenantsWithMinimalFields().withIdIs(String(active.id))
73
+ .selectPurchaseOrderListWith(Q.purchaseOrdersWithMinimalFields().withIdIs(orderId)
74
+ .selectOrderItemListWith(Q.orderItems().withIdIs(childId).limit(1)
75
+ .comment('Load the complete leaf, including its unchanged owner'))
76
+ .limit(1).comment('Keep the unmodified parent partial'))
77
+ .limit(1).comment('Load two partial ancestors above the owned complete leaf')
78
+ .purpose('Prove admission checks unchanged loaded ownership at a deep graph node')
79
+ .executeForList(context))[0];
80
+ expect(E.tenant(root).purchaseOrderList().size().eval()).toBe(1);
81
+ const parent = root.purchaseOrderList()[0];
82
+ expect(E.purchaseOrder(parent).orderItemList().size().eval()).toBe(1);
83
+ const leaf = parent.orderItemList()[0];
84
+ expect(String(E.orderItem(leaf).tenantId().eval())).toBe(String(active.id));
85
+ const sparse = () => {
86
+ for (const read of [() => E.tenant(root).name().eval(), () => E.purchaseOrder(parent).contactPhone().eval()]) {
87
+ let error: unknown; try { read(); } catch (caught) { error = caught; }
88
+ expect(error).toBeInstanceOf(TeaQLNotLoadedError);
89
+ }
90
+ const value = JSON.parse(JSON.stringify(root));
91
+ expect(value).not.toHaveProperty('name');
92
+ expect(value.purchaseOrderList[0]).not.toHaveProperty('contactPhone');
93
+ return JSON.stringify({rootVersion: root.version, parentVersion: parent.version,
94
+ keys: Object.keys(value).sort(), parentKeys: Object.keys(value.purchaseOrderList[0]).sort()});
95
+ };
96
+ const projection = sparse(), beforeStorage = physical();
97
+ context.withBusinessClock(new FixedBusinessClock(updatedAt));
98
+ leaf.updateProductName('Managed partial retry');
99
+ const key = {entity: 'OrderItem', id: (leaf as any)._ledgerId};
100
+ const pending = () => JSON.stringify((leaf as any)._root.change(key));
101
+ const intent = pending(); expect(JSON.parse(intent)).not.toHaveProperty('tenant');
102
+ context.insertResource('activeRoot', {entity: 'Tenant', id: other.id!});
103
+ const denials: Array<Record<string, unknown>> = [];
104
+ for (let attempt = 1; attempt <= 2; attempt++) {
105
+ reset(); let failure: unknown;
106
+ try { await root.auditAs('Reject the complete leaf under another active root').save(context); }
107
+ catch (error) { failure = error; }
108
+ const denied = effects(), storageUnchanged = JSON.stringify(physical()) === JSON.stringify(beforeStorage);
109
+ const observation = {attempt, effects: denied, intentRetained: pending() === intent,
110
+ sparseViewUnchanged: sparse() === projection, storageUnchanged,
111
+ violations: failure instanceof CheckException ? failure.violations.map(result => checkResultToWire(result)) : []};
112
+ denials.push(observation);
113
+ process.stdout.write('CORE_TS_PARTIAL_ROOT_DENIAL=' + JSON.stringify(observation) + '\n');
114
+ expect(failure).toBeInstanceOf(CheckException); expect(denied).toEqual(zero);
115
+ expect(observation.intentRetained && observation.sparseViewUnchanged && storageUnchanged).toBe(true);
116
+ expect(observation.violations).toEqual([expect.objectContaining({ruleId: 'context_root_mismatch', entityType: 'OrderItem',
117
+ instancePath: '/purchaseOrderList/0/orderItemList/0/tenant', message: 'Context-bound root must match the active context'})]);
118
+ }
119
+ context.insertResource('activeRoot', active); reset();
120
+ await root.auditAs('Save the same complete leaf under its original active root').save(context);
121
+ const acceptedEffects = effects();
122
+ expect(acceptedEffects).toEqual({...zero, queries: 2, transactions: 1, begins: 1, commits: 1,
123
+ policyLookups: 1, policyReviews: 1, audits: 1, mutations: 1});
124
+ expect((leaf as any)._root.change(key)).toEqual({}); expect(sparse()).toBe(projection);
125
+ const stored = physical();
126
+ expect(stored.purchase_order_data.find((row: any) => String(row.id) === String(orderId))).toEqual({
127
+ id: Number(orderId), version: 1, tenant: Number(active.id), contact_phone: '5550801', internal_note: null,
128
+ create_time: createdAt.getTime(), update_time: createdAt.getTime()});
129
+ expect(stored.order_item_data.find((row: any) => String(row.id) === String(childId))).toEqual({
130
+ id: Number(childId), version: 2, tenant: Number(active.id), purchase_order: Number(orderId),
131
+ product_name: 'Managed partial retry', unit_price: '10.00', create_time: createdAt.getTime(), update_time: updatedAt.getTime()});
132
+ process.stdout.write('CORE_TS_PARTIAL_ROOT_RESULT=' + JSON.stringify({language: 'typescript', passed: true,
133
+ orderId: String(orderId), leafId: String(childId), activeRootId: String(active.id), otherRootId: String(other.id),
134
+ calibration, denials, acceptedEffects, ancestorVersions: [root.version, parent.version], leafVersion: leaf.version,
135
+ sameGraphRetry: true, intentClearedAfterCommit: true, generatedImplementationsModified: false}) + '\n');
136
+ } finally {
137
+ query.mockRestore(); transaction.mockRestore(); exec.mockRestore(); allocation.mockRestore(); policy.mockRestore();
138
+ await client.close();
139
+ }
140
+ }
source/teaql-ts/examples/fix-e-alignment/unchanged-views-probe.ts ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src';
2
+ import { Q } from 'generated/generated/Q';
3
+ import { E } from 'generated/generated/E';
4
+ import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite';
5
+ import Database from 'better-sqlite3';
6
+
7
+ export const unchangedViewCases = [
8
+ 'sparse-null-forward', 'complete-independent-other', 'empty-reverse',
9
+ 'rollback-after-write', 'rollback-before-commit',
10
+ ] as const;
11
+ export type UnchangedViewCase = typeof unchangedViewCases[number];
12
+
13
+ /** Business preparation uses Q/E/mutation; spies and readonly SQL are test oracles. */
14
+ export async function verifyUnchangedView(filename: string, scenario: UnchangedViewCase): Promise<void> {
15
+ const round = Number(process.env.TEAQL_FIX_E_ROUND);
16
+ if (![1, 2].includes(round)) throw new Error('An explicit retained-example round is required');
17
+ const createdAt = new Date(Date.parse('2032-02-29T10:15:30Z') + (round - 1) * 86400000);
18
+ const updatedAt = new Date(createdAt.getTime() + 7200000);
19
+ const context = new UserContext().withBusinessClock(new FixedBusinessClock(createdAt));
20
+ const client = new SQLiteTeaQLClient(filename).setUserContext(context);
21
+ context.insertResource('dataService', client);
22
+ const driver = (client as any).driver;
23
+ const actualQuery = driver.query.bind(driver), actualExec = driver.database.exec.bind(driver.database);
24
+ const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction');
25
+ const exec = jest.spyOn(driver.database as Database.Database, 'exec');
26
+ const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy');
27
+ const review = jest.fn(() => undefined); context.withMutationPolicyRegistry({resolve: review});
28
+ let auditStart = client.auditTrace.length;
29
+ const effects = () => ({
30
+ queries: query.mock.calls.length, transactions: transaction.mock.calls.length,
31
+ begins: exec.mock.calls.filter(call => /^BEGIN\b/i.test(call[0])).length,
32
+ commits: exec.mock.calls.filter(call => /^COMMIT\b/i.test(call[0])).length,
33
+ rollbacks: exec.mock.calls.filter(call => /^ROLLBACK\b/i.test(call[0])).length,
34
+ allocations: allocation.mock.calls.length, policyLookups: policy.mock.calls.length,
35
+ policyReviews: review.mock.calls.length, audits: client.auditTrace.length - auditStart,
36
+ mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i
37
+ .test(String(call[0]).replace(/"/g, ''))).length,
38
+ rootLookups: query.mock.calls.filter(call => /\bFROM\s+tenant_data\b/i.test(String(call[0]).replace(/"/g, ''))).length,
39
+ });
40
+ const zero = {queries: 0, transactions: 0, begins: 0, commits: 0, rollbacks: 0,
41
+ allocations: 0, policyLookups: 0, policyReviews: 0, audits: 0, mutations: 0, rootLookups: 0};
42
+ const reset = () => {
43
+ query.mockClear(); transaction.mockClear(); exec.mockClear(); allocation.mockClear();
44
+ policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length;
45
+ };
46
+ const physical = (id: unknown) => {
47
+ const oracle = new Database(filename, {readonly: true, fileMustExist: true});
48
+ try {return oracle.prepare('SELECT id,version,contact_phone,internal_note,create_time,update_time FROM purchase_order_data WHERE id = ?').get(id);}
49
+ finally {oracle.close();}
50
+ };
51
+ try {
52
+ await context.ensureSchema(); reset();
53
+ const original = (await Q.purchaseOrders().comment('Prepare the unchanged-view graph fixture')
54
+ .purpose('Verify no-op geometry and genuine transaction rollback through generated APIs').newEntity(context))
55
+ .updateContactPhone('5550800').updateInternalNote(null);
56
+ await original.auditAs('Create one unchanged-view control').save(context);
57
+ const id = original.id!;
58
+ await Q.tenants().withIdIs('1').limit(1).comment('Calibrate root SELECT observation')
59
+ .purpose('Prove the root-lookup spy observes real provider work').executeForList(context);
60
+ const calibrationFailure = new Error('owned rollback observer calibration');
61
+ await expect(driver.transaction(async () => {throw calibrationFailure;})).rejects.toBe(calibrationFailure);
62
+ const calibration = effects();
63
+ for (const value of Object.values(calibration)) expect(value).toBeGreaterThan(0);
64
+
65
+ const sparse = scenario === 'sparse-null-forward';
66
+ let request = sparse ? Q.purchaseOrdersWithMinimalFields().selectContactPhone().selectInternalNote() : Q.purchaseOrders();
67
+ if (scenario === 'empty-reverse') {
68
+ request = request.selectOrderItemListWith(Q.orderItemsWithMinimalFields().limit(1)
69
+ .comment('Load an explicitly empty child list'));
70
+ } else {
71
+ request = request.selectTenantWith(Q.tenantsWithMinimalFields().limit(1)
72
+ .comment('Load a sparse forward edge without the target name'));
73
+ }
74
+ const row = (await request.withIdIs(id).limit(1).comment('Load the bounded original object view')
75
+ .purpose('Retain selected nulls, sparse fields and explicit relation geometry across saves').executeForList(context))[0];
76
+ expect(row).toBeDefined();
77
+ const key = {entity: 'PurchaseOrder', id: (row as any)._ledgerId};
78
+ const pending = () => (row as any)._root.change(key);
79
+ const root = (row as any)._root;
80
+ const geometry = () => {
81
+ expect(E.purchaseOrder(row).internalNote().eval()).toBeNull();
82
+ const json = JSON.parse(JSON.stringify(row)); expect(json).toHaveProperty('internalNote', null);
83
+ if (sparse) {
84
+ expect(() => E.purchaseOrder(row).createTime().eval()).toThrow(TeaQLNotLoadedError);
85
+ expect(json).not.toHaveProperty('createTime');
86
+ }
87
+ if (scenario === 'empty-reverse') {
88
+ expect(E.purchaseOrder(row).orderItemList().size().eval()).toBe(0);
89
+ expect(json).toHaveProperty('orderItemList', []);
90
+ } else {
91
+ expect(String(E.purchaseOrder(row).tenantId().eval())).toBe('1');
92
+ expect(String(E.purchaseOrder(row).tenant().eval()!.id)).toBe('1');
93
+ expect(() => E.purchaseOrder(row).tenant().name().eval()).toThrow(TeaQLNotLoadedError);
94
+ expect(json.tenant).not.toHaveProperty('name');
95
+ }
96
+ return JSON.stringify({keys: Object.keys(json).sort(), tenant: json.tenant, children: json.orderItemList});
97
+ };
98
+ const beforeGeometry = geometry(), beforeJSON = JSON.stringify(row), beforeStorage = physical(id);
99
+ const baselineVersion = root.originalVersion(key); expect(baselineVersion).toBe(1);
100
+ let other: typeof row | undefined;
101
+ if (scenario === 'complete-independent-other') {
102
+ other = (await Q.purchaseOrders().withIdIs(id).limit(1).comment('Load a separate mutable view')
103
+ .purpose('A no-op must not consume another view mutation ledger').executeForList(context))[0];
104
+ expect(other).not.toBe(row); other.updateInternalNote('another view remains pending');
105
+ }
106
+ const otherPending = () => other ? (other as any)._root.change({entity: 'PurchaseOrder', id: (other as any)._ledgerId}) : undefined;
107
+ const beforeOther = JSON.stringify(otherPending());
108
+ context.withBusinessClock(new FixedBusinessClock(updatedAt));
109
+ const rollback = scenario.startsWith('rollback-');
110
+ if (!rollback) {
111
+ row.updateContactPhone('5550899').updateContactPhone('5550800'); reset();
112
+ await row.auditAs('Save a restored field without refreshing the object view').save(context);
113
+ const observed = effects(); expect(observed).toEqual(zero);
114
+ expect(JSON.stringify(row)).toBe(beforeJSON); expect(geometry()).toBe(beforeGeometry);
115
+ expect((row as any)._root).toBe(root); expect(pending()).toEqual({});
116
+ expect(root.originalVersion(key)).toBe(baselineVersion); expect(row.version).toBe(1);
117
+ expect(JSON.stringify(otherPending())).toBe(beforeOther); expect(physical(id)).toEqual(beforeStorage);
118
+ process.stdout.write('CORE_TS_UNCHANGED_VIEW_CASE=' + JSON.stringify({scenario, round, id: String(id),
119
+ passed: true, effects: observed, calibration, geometryRetained: true, selectedNullRetained: true,
120
+ independentIntentRetained: true, sameLedger: true, version: row.version, physical: physical(id)}) + '\n');
121
+ return;
122
+ }
123
+
124
+ row.updateContactPhone('5550801');
125
+ const failure = new Error('owned transaction fault: ' + scenario);
126
+ let injected = 0, uncommitted: unknown;
127
+ const observeWritten = () => {
128
+ uncommitted = driver.database.prepare('SELECT contact_phone,version FROM purchase_order_data WHERE id = ?').get(id);
129
+ expect(uncommitted).toEqual({contact_phone: '5550801', version: 2});
130
+ injected++; throw failure;
131
+ };
132
+ if (scenario === 'rollback-after-write') {
133
+ query.mockImplementation(async (sql: unknown, values: unknown) => {
134
+ const result = await actualQuery(sql, values);
135
+ if (/^\s*UPDATE\s+purchase_order_data\b/i.test(String(sql).replace(/"/g, ''))) observeWritten();
136
+ return result;
137
+ });
138
+ } else {
139
+ exec.mockImplementation((sql: string) => {if (/^COMMIT\b/i.test(sql)) observeWritten(); return actualExec(sql);});
140
+ }
141
+ reset();
142
+ await expect(row.auditAs('Roll back a real write without losing the original view or retry intent').save(context)).rejects.toBe(failure);
143
+ const denied = effects();
144
+ expect(injected).toBe(1); expect(denied).toMatchObject({transactions: 1, begins: 1, rollbacks: 1, mutations: 1, audits: 0});
145
+ expect(physical(id)).toEqual(beforeStorage); expect(geometry()).toBe(beforeGeometry);
146
+ expect(row.version).toBe(1); expect((row as any)._root).toBe(root);
147
+ expect(root.originalVersion(key)).toBe(baselineVersion); expect(pending()).toHaveProperty('contact_phone', '5550801');
148
+ expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550801');
149
+ const retainedIntent = {...pending()};
150
+ query.mockImplementation(actualQuery); exec.mockImplementation(actualExec); reset();
151
+ await row.auditAs('Retry the same rolled-back object without querying or rebasing it').save(context);
152
+ const accepted = effects();
153
+ expect(accepted).toMatchObject({queries: 2, transactions: 1, begins: 1, commits: 1, rollbacks: 0,
154
+ mutations: 1, audits: 1, allocations: 0, policyLookups: 1, policyReviews: 1, rootLookups: 0});
155
+ expect(row.version).toBe(2); expect(pending()).toEqual({}); expect(root.originalVersion(key)).toBe(2);
156
+ expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550801');
157
+ expect(new Date(E.purchaseOrder(row).updateTime().eval()!).getTime()).toBe(updatedAt.getTime());
158
+ expect(physical(id)).toEqual({id: Number(id), version: 2, contact_phone: '5550801', internal_note: null,
159
+ create_time: createdAt.getTime(), update_time: updatedAt.getTime()});
160
+ process.stdout.write('CORE_TS_UNCHANGED_VIEW_CASE=' + JSON.stringify({scenario, round, id: String(id), passed: true,
161
+ calibration, injected, uncommitted, denied, accepted, retainedIntent, geometryRetained: true,
162
+ sameObjectRetry: true, originalOptimisticVersionRetained: true, physical: physical(id)}) + '\n');
163
+ } finally {
164
+ query.mockRestore(); transaction.mockRestore(); exec.mockRestore(); allocation.mockRestore(); policy.mockRestore();
165
+ await client.close();
166
+ }
167
+ }
source/teaql-ts/examples/fix-e-alignment/verify-local.cjs ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // Run after npm ci at the runtime root. No remote TeaQL package is substituted.
4
+ 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");
5
+ const example = __dirname, repo = path.resolve(example, "../..");
6
+ const sha = bytes => crypto.createHash("sha256").update(bytes).digest("hex");
7
+ function fingerprint() {
8
+ const manifest = JSON.parse(fs.readFileSync(path.join(example, "fixture-manifest.json")));
9
+ assert.equal(manifest.language, "typescript"); assert.equal(manifest.evaluationErrors, 0);
10
+ assert.equal(sha(fs.readFileSync(path.join(example, "model.xml"))), manifest.modelSha256);
11
+ const actual = [];
12
+ function visit(directory, prefix = "") {
13
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
14
+ const name = path.join(prefix, entry.name), original = path.join(directory, entry.name);
15
+ assert(!entry.isSymbolicLink(), "generated fixture cannot be a symlink");
16
+ if (entry.isDirectory()) visit(original, name); else { assert(entry.isFile()); actual.push(name); }
17
+ }
18
+ }
19
+ visit(path.join(example, "generated"));
20
+ assert.deepEqual(actual.sort(), Object.keys(manifest.files).sort());
21
+ for (const [name, expected] of Object.entries(manifest.files)) assert.equal(sha(fs.readFileSync(path.join(example, "generated", name))), expected, name);
22
+ return manifest;
23
+ }
24
+ const requested = process.env.TEAQL_FIX_E_EVIDENCE_DIR;
25
+ const evidence = requested ? path.resolve(requested) : fs.mkdtempSync(path.join(os.tmpdir(), "teaql-ts-fix-e-evidence-"));
26
+ if (requested) { assert(path.isAbsolute(requested) && !fs.existsSync(evidence)); fs.mkdirSync(evidence, {recursive: true}); }
27
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "teaql-ts-fix-e-build-"));
28
+ const report = {schema: "teaql.typescript-fix-e-example/v1", passed: false, rounds: [], sameDatabase: true,
29
+ runtimeSource: path.join(repo, "src"), databaseRetained: true};
30
+ const {createOwnedRunner, ownedBytes} = require('./owned-command.cjs'), runner = createOwnedRunner();
31
+ async function main() {
32
+ try {
33
+ const manifest = fingerprint(); report.modelSha256 = manifest.modelSha256;
34
+ report.contextRootApplicationSha256 = sha(fs.readFileSync(path.join(example, 'context-root-probe.ts')));
35
+ report.partialAncestorApplicationSha256 = sha(fs.readFileSync(path.join(example, 'partial-ancestors-probe.ts')));
36
+ report.partialRootApplicationSha256 = sha(fs.readFileSync(path.join(example, 'partial-root-probe.ts')));
37
+ report.unchangedViewsApplicationSha256 = sha(fs.readFileSync(path.join(example, 'unchanged-views-probe.ts')));
38
+ report.checkerBoundaryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'checker-boundaries-probe.ts')));
39
+ report.graphFixApplicationSha256 = sha(fs.readFileSync(path.join(example, 'graph-fix-idempotence.test.ts')));
40
+ report.concurrentQueryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'concurrent-query-probe.ts')));
41
+ report.deleteRetryApplicationSha256 = sha(fs.readFileSync(path.join(example, 'delete-retry.test.ts')));
42
+ assert(fs.existsSync(path.join(repo, "node_modules/jest/bin/jest.js")), "run npm ci at the runtime root first");
43
+ const tsconfig = path.join(scratch, "tsconfig.json"), config = path.join(scratch, "jest.cjs");
44
+ fs.writeFileSync(tsconfig, JSON.stringify({extends: path.join(repo, "tsconfig.json"), compilerOptions: {
45
+ types: ["node", "jest"], typeRoots: [path.join(repo, "node_modules/@types")], lib: ["ES2022", "DOM"],
46
+ baseUrl: repo, paths: {"teaql-ts": [path.join(repo, "src/index.ts")], "teaql-ts/*": [path.join(repo, "src/*")],
47
+ "generated/*": [path.join(example, "generated/src/*")]}}}));
48
+ fs.writeFileSync(config, "module.exports = " + JSON.stringify({rootDir: repo, roots: [example], testEnvironment: "node",
49
+ 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"],
50
+ moduleNameMapper: {"^teaql-ts$": path.join(repo, "src/index.ts"), "^teaql-ts/(.*)$": path.join(repo, "src/$1"),
51
+ "^generated/(.*)$": path.join(example, "generated/src/$1")},
52
+ transform: {"^.+\\.tsx?$": ["ts-jest", {tsconfig}]}}) + ";\n");
53
+ for (const round of [1, 2]) {
54
+ const creationDatabases = path.join(evidence, "creation-round-" + round);
55
+ fs.mkdirSync(creationDatabases);
56
+ const command = [path.join(repo, "node_modules/jest/bin/jest.js"), "--config", config,
57
+ "--runInBand", "--cacheDirectory", path.join(scratch, "jest")];
58
+ const log = path.join(evidence, "round-" + round + ".log"), fd = fs.openSync(log, "w");
59
+ let result;
60
+ try { result = await runner.run([process.execPath, ...command], {cwd: repo, timeout: 120000,
61
+ 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]}); }
62
+ finally { fs.closeSync(fd); }
63
+ report.rounds.push({command, exitCode: result.status, signal: result.signal, logSha256: sha(fs.readFileSync(log))});
64
+ if (result.status !== 0) process.exitCode = result.status || 1;
65
+ assert.equal(result.status, 0, fs.readFileSync(log, "utf8").slice(-12000));
66
+ const lines = fs.readFileSync(log, "utf8").split(/\r?\n/);
67
+ const deletes = lines.filter(line => line.startsWith('CORE_TS_FILE_DELETE_RETRY='))
68
+ .map(line => JSON.parse(line.slice('CORE_TS_FILE_DELETE_RETRY='.length)));
69
+ assert.equal(deletes.length, 1); assert.equal(deletes[0].round, round); assert.equal(deletes[0].retryError, null);
70
+ assert.deepEqual(deletes[0].rollback.ledgerFields, []); assert.equal(deletes[0].retryMutations, 1);
71
+ assert.equal(deletes[0].retryPersists, 1); assert.equal(deletes[0].auditDelta, 1);
72
+ report.rounds[report.rounds.length - 1].deleteRetry = deletes[0];
73
+ const viewCases = lines.filter(line => line.startsWith('CORE_TS_UNCHANGED_VIEW_CASE='))
74
+ .map(line => JSON.parse(line.slice('CORE_TS_UNCHANGED_VIEW_CASE='.length)));
75
+ assert.deepEqual(viewCases.map(value => value.scenario).sort(), [
76
+ 'sparse-null-forward', 'complete-independent-other', 'empty-reverse', 'rollback-after-write', 'rollback-before-commit',
77
+ ].sort());
78
+ for (const value of viewCases) {assert.equal(value.passed, true); assert.equal(value.round, round);}
79
+ report.rounds[report.rounds.length - 1].unchangedViewCases = viewCases;
80
+ const checkerCases = lines.filter(line => line.startsWith('CORE_TS_CHECKER_BOUNDARY_CASE='))
81
+ .map(line => JSON.parse(line.slice('CORE_TS_CHECKER_BOUNDARY_CASE='.length)));
82
+ assert.equal(checkerCases.length, 32);
83
+ for (const value of checkerCases) {assert.equal(value.passed, true); assert.equal(value.round, round);}
84
+ const checkerSummary = lines.filter(line => line.startsWith('CORE_TS_CHECKER_BOUNDARY_RESULT='))
85
+ .map(line => JSON.parse(line.slice('CORE_TS_CHECKER_BOUNDARY_RESULT='.length)));
86
+ assert.equal(checkerSummary.length, 1); assert.equal(checkerSummary[0].passed, true);
87
+ assert.equal(checkerSummary[0].round, round); assert.equal(checkerSummary[0].observations, 32);
88
+ report.rounds[report.rounds.length - 1].checkerBoundaryCases = checkerCases;
89
+ const graphCases = lines.filter(line => line.startsWith('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE='))
90
+ .map(line => JSON.parse(line.slice('TYPESCRIPT_GRAPH_FIX_IDEMPOTENCE='.length)));
91
+ assert.deepEqual(graphCases.map(value => value.case).sort(), [
92
+ 'duplicate-create', 'duplicate-update', 'independent-real-graphs', 'distinct-views-same-id-rejected',
93
+ ].sort());
94
+ for (const value of graphCases) assert.equal(value.facts.round, round);
95
+ report.rounds[report.rounds.length - 1].graphFixCases = graphCases;
96
+ const concurrent = lines.filter(line => line.startsWith('TYPESCRIPT_CONCURRENT_QUERY='))
97
+ .map(line => JSON.parse(line.slice('TYPESCRIPT_CONCURRENT_QUERY='.length)));
98
+ assert.equal(concurrent.length, 1); assert(concurrent[0].passed && concurrent[0].observation.round === round);
99
+ assert(concurrent[0].observation.bothLive && concurrent[0].observation.sameContext && concurrent[0].observation.distinctRoots);
100
+ report.rounds[report.rounds.length - 1].concurrentQuery = concurrent[0].observation;
101
+ 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="]) {
102
+ const values = lines.filter(line => line.startsWith(marker)).map(line => JSON.parse(line.slice(marker.length)));
103
+ assert.equal(values.length, 1, marker); assert.equal(values[0].passed, true, marker);
104
+ }
105
+ assert.deepEqual(fingerprint(), manifest);
106
+ }
107
+ report.databaseSha256 = sha(fs.readFileSync(path.join(evidence, "fixture.sqlite")));
108
+ report.deleteRetryFile = {file: 'fixture.sqlite.delete-retry.json',
109
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.delete-retry.json')))};
110
+ report.contextRootDatabase = {file: 'fixture.sqlite.context-root.sqlite',
111
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.context-root.sqlite')))};
112
+ report.contextRootFile = {file: 'fixture.sqlite.context-root.json',
113
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.context-root.json')))};
114
+ report.partialAncestorDatabase = {file: 'fixture.sqlite.partial-ancestors.sqlite',
115
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.partial-ancestors.sqlite')))};
116
+ report.partialRootDatabase = {file: 'fixture.sqlite.partial-root.sqlite',
117
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.partial-root.sqlite')))};
118
+ report.checkerBoundaryDatabases = ['fixture.sqlite.checker-boundaries.sqlite', 'fixture.sqlite.checker-boundaries.sqlite.no-schema.sqlite']
119
+ .map(file => ({file, sha256: sha(fs.readFileSync(path.join(evidence, file)))}));
120
+ report.graphFixDatabases = ['', '.first.sqlite', '.second.sqlite', '.identity.sqlite']
121
+ .map(suffix => {const file = 'fixture.sqlite.idempotence.sqlite' + suffix;
122
+ return {file, sha256: sha(fs.readFileSync(path.join(evidence, file)))};});
123
+ report.concurrentQueryDatabase = {file: 'fixture.sqlite.concurrent-query.sqlite',
124
+ sha256: sha(fs.readFileSync(path.join(evidence, 'fixture.sqlite.concurrent-query.sqlite')))};
125
+ report.passed = true;
126
+ console.log("PASS TypeScript retained Fix/E/loading/ownership example twice on one database");
127
+ } catch (error) { console.error(error.stack); process.exitCode ||= 1; }
128
+ finally {
129
+ // The awaited runner reaps its owned process group before cache/config cleanup.
130
+ report.disposedOwnedBytes = runner.safeToClean ? ownedBytes(scratch) : 0;
131
+ if (runner.safeToClean) fs.rmSync(scratch, {recursive: true});
132
+ else report.unsafeBuildRetention = {path: scratch, processGroup: runner.unsafeGroup};
133
+ report.scratchRemoved = !fs.existsSync(scratch); runner.dispose();
134
+ fs.writeFileSync(path.join(evidence, "receipt.json"), JSON.stringify(report, null, 2) + "\n");
135
+ console.log("Retained compact example evidence: " + evidence);
136
+ }
137
+ }
138
+ main().catch(error => { console.error(error.stack); process.exitCode ||= 1; });
source/teaql-ts/examples/fix-e-alignment/verify.test.ts ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CheckException, decimal, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src';
2
+ import { E } from 'generated/generated/E';
3
+ import { Q } from 'generated/generated/Q';
4
+ import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite';
5
+ import { RuntimeOperation, RuntimeOperationCompletion } from '../../src/core/telemetry';
6
+ import { verifyLoading } from './loading-probe';
7
+ import { verifyOwnership } from './ownership-probe';
8
+ import Database from 'better-sqlite3';
9
+ import { verifyCheckerMetadata, verifyFileCheckerMetadata } from './checker-metadata-probe';
10
+ import { verifyExpressionBoundaries } from './expression-boundary-probe';
11
+ import { verifyContextRoot, verifyFileContextRoot } from './context-root-probe';
12
+ import { verifyPartialAncestors } from './partial-ancestors-probe';
13
+ import { verifyPartialRoot } from './partial-root-probe';
14
+ import { unchangedViewCases, verifyUnchangedView } from './unchanged-views-probe';
15
+ import { verifyCheckerBoundaries } from './checker-boundaries-probe';
16
+ import { verifyConcurrentQuery } from './concurrent-query-probe';
17
+
18
+ test('concurrent generated queries retain independent live request ownership on one Context', async () => {
19
+ const filename = process.env.TEAQL_FIX_E_DB;
20
+ if (!filename) throw new Error('Retained SQLite path required for concurrent-query verification');
21
+ await verifyConcurrentQuery(filename + '.concurrent-query.sqlite');
22
+ }, 15000);
23
+
24
+ test('Checker admission covers required relations, exact completeness, post-Fix values and object-local wire inputs', async () => {
25
+ const filename = process.env.TEAQL_FIX_E_DB;
26
+ if (!filename) throw new Error('Retained SQLite path required for Checker boundary verification');
27
+ await verifyCheckerBoundaries(filename + '.checker-boundaries.sqlite');
28
+ });
29
+
30
+ test.each(unchangedViewCases)('unchanged view and rollback contract: %s', async scenario => {
31
+ const filename = process.env.TEAQL_FIX_E_DB;
32
+ if (!filename) throw new Error('Retained SQLite path required for view restoration verification');
33
+ await verifyUnchangedView(filename + '.unchanged.' + scenario + '.sqlite', scenario);
34
+ });
35
+
36
+ test('a complete modified leaf retains root admission through two untouched partial ancestors', async () => {
37
+ const filename = process.env.TEAQL_FIX_E_DB;
38
+ if (!filename) throw new Error('retained SQLite path required for managed partial-root verification');
39
+ await verifyPartialRoot(filename + '.partial-root.sqlite');
40
+ });
41
+
42
+ test('only modified objects need completeness through two untouched partial ancestors', async () => {
43
+ const filename = process.env.TEAQL_FIX_E_DB;
44
+ if (!filename) throw new Error('retained SQLite path required for partial-ancestor verification');
45
+ await verifyPartialAncestors(filename + '.partial-ancestors.sqlite');
46
+ });
47
+
48
+ test('the file-backed generated client protects loaded root ownership too', async () => {
49
+ const filename = process.env.TEAQL_FIX_E_DB;
50
+ if (!filename) throw new Error('retained file path required for file-backed root verification');
51
+ await verifyFileContextRoot(filename + '.context-root.json');
52
+ });
53
+
54
+ test('generated audited graph saves reject invalid or mismatched context roots before provider work', async () => {
55
+ const filename = process.env.TEAQL_FIX_E_DB;
56
+ if (!filename) throw new Error('retained SQLite database required for root identity verification');
57
+ await verifyContextRoot(filename + '.context-root.sqlite');
58
+ });
59
+
60
+ test('generated E boundaries preserve NotLoaded, absence, native terminals and state without I/O', async () => {
61
+ const filename = process.env.TEAQL_FIX_E_DB;
62
+ if (!filename) throw new Error('retained SQLite database required for E boundary verification');
63
+ await verifyExpressionBoundaries(filename + '.expression-boundaries.sqlite');
64
+ });
65
+
66
+ test('generated Checker violations retain their declaring entity and wire locations', async () => {
67
+ const filename = process.env.TEAQL_FIX_E_DB;
68
+ if (!filename) throw new Error('retained SQLite database required for Checker metadata');
69
+ await verifyCheckerMetadata(filename);
70
+ await verifyFileCheckerMetadata(filename + '.checker-file.json');
71
+ });
72
+
73
+ test('unmodified generated Q/E and audited SQLite saves consume the local Business Clock', async () => {
74
+ const first = new Date('2032-02-29T10:15:30.000Z');
75
+ const second = new Date('2032-03-01T11:16:31.000Z');
76
+ const context = new UserContext().withBusinessClock(new FixedBusinessClock(first));
77
+ const client = new SQLiteTeaQLClient(process.env.TEAQL_FIX_E_DB || ':memory:').setUserContext(context);
78
+ const telemetry: Array<{operation: RuntimeOperation; completion?: RuntimeOperationCompletion}> = [];
79
+ client.setRuntimeTelemetry({start: operation => ({
80
+ success: completion => { telemetry.push({operation, completion}); },
81
+ failure: () => undefined,
82
+ })});
83
+ context.insertResource('dataService', client);
84
+ const diagnostics: ReturnType<TeaQLNotLoadedError['toWire']>[] = [];
85
+ const humanMessages: string[] = [];
86
+ const missing = (read: () => unknown, location: string, attempted: string, expression: string) => {
87
+ try { read(); }
88
+ catch (error) {
89
+ if (!(error instanceof TeaQLNotLoadedError)) throw error;
90
+ const wire = error.toWire();
91
+ expect(wire.code).toBe('NOT_LOADED');
92
+ expect(wire.instancePath).toBe(location);
93
+ expect(wire.attemptedInstancePath).toBe(attempted);
94
+ expect(wire.expressionWithBrokenPoint).toBe(expression);
95
+ expect(wire.expressionWithBrokenPoint.match(/<broken>/g)).toHaveLength(1);
96
+ expect(error.message).not.toContain('PRIVATE-FALLBACK');
97
+ diagnostics.push(wire);
98
+ humanMessages.push(error.message);
99
+ return;
100
+ }
101
+ throw new Error('NotLoaded must not be treated as null or fallback');
102
+ };
103
+ try {
104
+ await context.ensureSchema();
105
+ const order = (await Q.purchaseOrders().comment('Prepare the synthetic clock fixture')
106
+ .purpose('Verify generated Fix and expression diagnostics').newEntity(context));
107
+ order.updateContactPhone('5550100');
108
+ const saved = await order.auditAs('Create the synthetic Fix order').save(context);
109
+ expect(new Date(E.purchaseOrder(saved).createTime().eval()!).getTime()).toBe(first.getTime());
110
+ expect(new Date(E.purchaseOrder(saved).updateTime().eval()!).getTime()).toBe(first.getTime());
111
+ expect(String(E.purchaseOrder(saved).tenantId().eval())).toBe('1');
112
+ expect(E.purchaseOrder(saved).internalNote().orElse('fallback')).toBe('fallback');
113
+
114
+ const partial = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1)
115
+ .comment('Load scalar fields without eager relations').purpose('Verify E requires explicit relation loading')
116
+ .executeForList(context))[0];
117
+ expect(String(E.purchaseOrder(partial).tenantId().eval())).toBe('1');
118
+ missing(() => E.purchaseOrder(partial).tenant().name().eval(), '/tenant', '/tenant/name',
119
+ 'E.purchaseOrder(<root>).tenant()<broken>.name().eval()');
120
+ missing(() => E.purchaseOrder(partial).tenant().purchaseOrderList().first().tenant().name().eval(),
121
+ '/tenant', '/tenant/purchaseOrderList/0/tenant/name',
122
+ 'E.purchaseOrder(<root>).tenant()<broken>.purchaseOrderList().first().tenant().name().eval()');
123
+ missing(() => E.purchaseOrder(partial).orderItemList().get(2).productName().eval(),
124
+ '/orderItemList', '/orderItemList/2/productName',
125
+ 'E.purchaseOrder(<root>).orderItemList()<broken>.get(2).productName().eval()');
126
+ missing(() => E.purchaseOrder(partial).tenant().name().orElse('PRIVATE-FALLBACK'),
127
+ '/tenant', '/tenant/name',
128
+ 'E.purchaseOrder(<root>).tenant()<broken>.name().orElse(<fallback>)');
129
+
130
+ context.withBusinessClock(new FixedBusinessClock(second));
131
+ const loaded = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1)
132
+ .comment('Reload the complete order before changing it')
133
+ .purpose('Verify update Fix preserves the original create time').executeForList(context))[0];
134
+ loaded.updateContactPhone('5550101');
135
+ await loaded.auditAs('Update the synthetic Fix order').save(context);
136
+ const persisted = (await Q.purchaseOrders().withIdIs(saved.id!).limit(1)
137
+ .comment('Reload the persisted update').purpose('Verify Business Clock values using E')
138
+ .executeForList(context))[0];
139
+ expect(new Date(E.purchaseOrder(persisted).createTime().eval()!).getTime()).toBe(first.getTime());
140
+ expect(new Date(E.purchaseOrder(persisted).updateTime().eval()!).getTime()).toBe(second.getTime());
141
+ expect(E.purchaseOrder(persisted).contactPhone().eval()).toBe('5550101');
142
+ expect(context.getResource('fixTime')).toBeUndefined();
143
+ const requests = telemetry.filter(event => event.operation.name === 'PurchaseOrder.request');
144
+ expect(requests.length).toBeGreaterThanOrEqual(3);
145
+ for (const request of requests) expect(request.completion?.attributes?.['teaql.result.cardinality']).toBe(1);
146
+ const statements = telemetry.filter(event => /\.(select|readback)$/.test(event.operation.name));
147
+ expect(statements.length).toBeGreaterThan(0);
148
+ for (const statement of statements) expect(statement.operation.attributes?.['teaql.provider.execution']).toBe('statement');
149
+ process.stdout.write('GENERATED_QUERY_METADATA_PASS language=typescript requestRows=1 providerExecution=statement\n');
150
+ await verifyLoading(context, saved.id!);
151
+ await verifyOwnership(context);
152
+ process.stdout.write('FIX_E_EXAMPLE=' + JSON.stringify({ language: 'typescript', passed: true,
153
+ normalGeneratedSave: true, createTimePreserved: true, updateTimeAdvanced: true,
154
+ declaredContextRootInjected: true, diagnostics, humanMessages }) + '\n');
155
+ } finally { await client.close(); }
156
+ });
157
+
158
+ test('a generated persisted field restored to its baseline has no provider, policy or audit effects', async () => {
159
+ const filename = process.env.TEAQL_FIX_E_DB;
160
+ if (!filename) throw new Error('retained SQLite database required for the independent oracle');
161
+ const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-03-01T12:30:00Z')));
162
+ const client = new SQLiteTeaQLClient(filename).setUserContext(context);
163
+ context.insertResource('dataService', client);
164
+ try {
165
+ await context.ensureSchema();
166
+ const entity = (await Q.purchaseOrders().comment('Prepare the known baseline restoration fixture')
167
+ .purpose('Verify a restored field does not become a business write').newEntity(context));
168
+ entity.updateContactPhone('5550700');
169
+ await entity.auditAs('Create the known baseline restoration fixture').save(context);
170
+ const row = (await Q.purchaseOrders().withIdIs(entity.id!).limit(1)
171
+ .comment('Load the persisted restoration baseline').purpose('Capture actual generated Q provenance')
172
+ .executeForList(context))[0];
173
+ const json = JSON.stringify(row), version = row.version;
174
+ row.updateContactPhone('5550799').updateContactPhone('5550700');
175
+ const driver = (client as any).driver;
176
+ const transaction = jest.spyOn(driver, 'transaction');
177
+ const query = jest.spyOn(driver, 'query');
178
+ const policy = jest.spyOn(context, 'enterMutationPolicy');
179
+ const audits = client.auditTrace.length;
180
+ await row.auditAs('Save the restored baseline without writing').save(context);
181
+ const schema = (client as any).schemas.PurchaseOrder;
182
+ const oracle = new Database(filename, { readonly: true, fileMustExist: true });
183
+ let stored: { contact_phone: string; version: number };
184
+ try { stored = oracle.prepare(`SELECT contact_phone, version FROM "${schema.table}" WHERE id = ?`).get(row.id) as typeof stored; }
185
+ finally { oracle.close(); }
186
+ const result = {language: 'typescript', value: stored.contact_phone, versionBefore: version,
187
+ versionAfter: stored.version, transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length,
188
+ policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - audits,
189
+ projectionUnchanged: JSON.stringify(row) === json};
190
+ process.stdout.write('CORE_BASELINE_RESTORATION=' + JSON.stringify(result) + '\n');
191
+ expect(result).toMatchObject({value: '5550700', versionAfter: version, transactions: 0,
192
+ providerQueries: 0, policyReviews: 0, auditEvents: 0, projectionUnchanged: true});
193
+ expect(E.purchaseOrder(row).contactPhone().eval()).toBe('5550700');
194
+
195
+ const noIO = (scenario: string, auditStart: number) => {
196
+ const effects = {scenario, transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length,
197
+ policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - auditStart};
198
+ process.stdout.write('CORE_BASELINE_RESTORATION_CASE=' + JSON.stringify(effects) + '\n');
199
+ expect(effects).toMatchObject({transactions: 0, providerQueries: 0, policyReviews: 0, auditEvents: 0});
200
+ };
201
+ const reset = () => { transaction.mockClear(); query.mockClear(); policy.mockClear(); return client.auditTrace.length; };
202
+ const rawKey = {entity: 'PurchaseOrder', id: (row as any)._ledgerId};
203
+ (row as any)._root.set(rawKey, 'contact_phone', '5550799');
204
+ (row as any)._root.set(rawKey, 'contact_phone', '5550700');
205
+ const rawAudits = reset();
206
+ await row.auditAs('Save an admitted raw canonical field restored to baseline').save(context);
207
+ const rawResult = {transactions: transaction.mock.calls.length, providerQueries: query.mock.calls.length,
208
+ policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - rawAudits,
209
+ version: row.version, projectionUnchanged: JSON.stringify(row) === json};
210
+ expect(rawResult).toEqual({transactions: 0, providerQueries: 0, policyReviews: 0, auditEvents: 0, version: 1, projectionUnchanged: true});
211
+ process.stdout.write('CORE_BASELINE_RESTORATION_RAW=' + JSON.stringify(rawResult) + '\n');
212
+ const nullBefore = JSON.stringify(row);
213
+ expect(E.purchaseOrder(row).internalNote().eval()).toBeNull();
214
+ row.updateInternalNote('intermediate note').updateInternalNote(null);
215
+ let auditStart = reset();
216
+ await row.auditAs('Save a restored loaded null').save(context);
217
+ noIO('known-null', auditStart); expect(JSON.stringify(row)).toBe(nullBefore);
218
+
219
+ const sparse = (await Q.purchaseOrdersWithMinimalFields().withIdIs(row.id!).selectContactPhone().limit(1)
220
+ .comment('Load only the field needed for the restoration probe').purpose('Preserve the original sparse view')
221
+ .executeForList(context))[0];
222
+ const sparseBefore = JSON.stringify(sparse);
223
+ sparse.updateContactPhone('5550799').updateContactPhone('5550700'); auditStart = reset();
224
+ await sparse.auditAs('Save a restored known field in a sparse view').save(context);
225
+ noIO('known-sparse-field', auditStart); expect(JSON.stringify(sparse)).toBe(sparseBefore);
226
+ expect(() => E.purchaseOrder(sparse).internalNote().eval()).toThrow(TeaQLNotLoadedError);
227
+
228
+ const unknown = (await Q.purchaseOrdersWithMinimalFields().withIdIs(row.id!).limit(1)
229
+ .comment('Load identity without the original phone').purpose('Unknown provenance is not loaded null')
230
+ .executeForList(context))[0];
231
+ unknown.updateContactPhone('5550700'); auditStart = reset();
232
+ await expect(unknown.auditAs('Reject an edit with an unknown original').save(context)).rejects.toThrow(CheckException);
233
+ noIO('unknown-original-rejected', auditStart);
234
+
235
+ const invalid = (await Q.purchaseOrders().withIdIs(row.id!).limit(1)
236
+ .comment('Load the raw admission negative control').purpose('Invalid native keys cannot disappear as no-ops')
237
+ .executeForList(context))[0];
238
+ const invalidKey = {entity: 'PurchaseOrder', id: (invalid as any)._ledgerId};
239
+ (invalid as any)._root.set(invalidKey, 'contact_phone', '5550700');
240
+ (invalid as any)._root.set(invalidKey, 'contactPhone', '5550700'); auditStart = reset();
241
+ await expect(invalid.auditAs('Reject a raw native-member field').save(context)).rejects.toThrow('canonical');
242
+ noIO('invalid-key-before-discard', auditStart);
243
+ expect((invalid as any)._root.change(invalidKey)).toHaveProperty('contact_phone', '5550700');
244
+
245
+ context.withBusinessClock(new FixedBusinessClock(new Date('2032-04-01T09:15:00Z')));
246
+ row.updateContactPhone('5550799').updateContactPhone('5550700').updateInternalNote('genuine remaining edit');
247
+ auditStart = reset(); await row.auditAs('Persist the genuine edit after cancelling the phone change').save(context);
248
+ expect(transaction).toHaveBeenCalledTimes(1); expect(policy).toHaveBeenCalledTimes(1);
249
+ expect(client.auditTrace.length - auditStart).toBe(1);
250
+ expect(row.version).toBe(2); expect(E.purchaseOrder(row).internalNote().eval()).toBe('genuine remaining edit');
251
+ expect(new Date(E.purchaseOrder(row).updateTime().eval()!).toISOString()).toBe('2032-04-01T09:15:00.000Z');
252
+ const remainingOracle = new Database(filename, {readonly: true, fileMustExist: true});
253
+ try {
254
+ expect(remainingOracle.prepare(`SELECT contact_phone, internal_note, version, update_time FROM "${schema.table}" WHERE id = ?`).get(row.id))
255
+ .toEqual({contact_phone: '5550700', internal_note: 'genuine remaining edit', version: 2, update_time: 1964423700000});
256
+ } finally { remainingOracle.close(); }
257
+
258
+ // The complete plan, not only the parent's ledger, controls no-op handling.
259
+ const child = (await Q.orderItems().comment('Prepare a genuine new child on a clean parent')
260
+ .purpose('Verify clean parents still traverse pending child work').newEntity(context));
261
+ child.updateProductName('Widget').updateUnitPrice(decimal('10'));
262
+ entity.orderItemList().push(child);
263
+ auditStart = reset(); await entity.auditAs('Save only the dirty child through its clean parent').save(context);
264
+ expect(entity.version).toBe(1); expect(child.version).toBe(1); expect(transaction).toHaveBeenCalledTimes(1);
265
+ expect(client.auditTrace.length - auditStart).toBe(1);
266
+ const childOracle = new Database(filename, {readonly: true, fileMustExist: true});
267
+ try {
268
+ expect(childOracle.prepare('SELECT purchase_order, product_name, version FROM order_item_data WHERE id = ?').get(child.id))
269
+ .toEqual({purchase_order: Number(entity.id), product_name: 'Widget', version: 1});
270
+ } finally { childOracle.close(); }
271
+ row.updateContactPhone('5550799').updateContactPhone('5550700').markForDeletion();
272
+ auditStart = reset(); await row.auditAs('Keep pending deletion after a restored scalar edit').save(context);
273
+ expect(row.version).toBe(-3); expect(transaction).toHaveBeenCalledTimes(1); expect(policy).toHaveBeenCalledTimes(1);
274
+ expect(client.auditTrace.length - auditStart).toBe(1);
275
+ const deletionOracle = new Database(filename, {readonly: true, fileMustExist: true});
276
+ let deleted;
277
+ try {deleted = deletionOracle.prepare(`SELECT contact_phone, version FROM "${schema.table}" WHERE id = ?`).get(row.id);}
278
+ finally {deletionOracle.close();}
279
+ expect(deleted).toEqual({contact_phone: '5550700', version: -3});
280
+ process.stdout.write('CORE_BASELINE_RESTORATION_DELETE=' + JSON.stringify({version: row.version, transactions: transaction.mock.calls.length,
281
+ policyReviews: policy.mock.calls.length, auditEvents: client.auditTrace.length - auditStart, physical: deleted}) + '\n');
282
+ process.stdout.write('CORE_BASELINE_RESTORATION_COMPLETE=' + JSON.stringify({language: 'typescript', passed: true,
283
+ knownValue: true, knownNull: true, sparseGeometry: true, unknownOriginal: true, rawAdmission: true,
284
+ genuineEdit: true, cleanParentDirtyChild: true, independentReadOnlyOracle: true}) + '\n');
285
+ } finally { jest.restoreAllMocks(); await client.close(); }
286
+ });
source/teaql-ts/examples/managed-creation-fixtures.json ADDED
The diff for this file is too large to render. See raw diff
 
source/teaql-ts/examples/natural-messages/AGENTS.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Checker messages example
2
+
3
+ Run `node scripts/verify-natural-messages.cjs --full --example --output
4
+ /new/evidence/path` from the runtime repository. The output path must not exist.
5
+
6
+ The example consumes the complete immutable generated library and model under
7
+ `fixture/`. Do not read or edit generated library source for
8
+ API discovery. Use current model-aware Assist when application code needs an
9
+ operation not already demonstrated here. Its generated Runtime Module installs
10
+ presentation metadata and actual Checker rules. Do not replace them with manual
11
+ descriptors or hand-written bounds to make the example pass.
12
+
13
+ Keep generated Q bounded and supply comment/purpose. Use generated audited Save
14
+ for every write. Never replace the scalar-length check with the mask's length or
15
+ dump the secret into diagnostics. The verifier runs twice against the same retained
16
+ SQLite database and JSON store, checks the unchanged-parent graph origin and a
17
+ single safe customer renderer invocation, and disposes only its owned source
18
+ copy, dependencies and outputs. Regenerate the fixture through
19
+ `TypescriptNaturalMessagesGenerationTest`; preserve its manifest and evaluation.
source/teaql-ts/examples/natural-messages/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Checker messages from generated Q and E
2
+
3
+ The backend returns `The name of the 2nd entry is required.` or
4
+ `请填写第2项明细的名称。`, while retaining `/entryList/1/name`. The frontend can
5
+ display the message directly and use the structured pointer independently.
6
+
7
+ ```bash
8
+ node scripts/verify-natural-messages.cjs --full --example --output /new/evidence/path
9
+ ```
10
+
11
+ This source-only gate installs pinned dependencies offline in an owned temporary
12
+ copy, typechecks, runs native tests, builds production bundles, checks the message
13
+ module's browser bundle, and runs this example twice against the same SQLite
14
+ database and file-backed JSON store.
15
+ Only `better-sqlite3` and `esbuild` install scripts are enabled in the disposable
16
+ execution manifest. The candidate manifest and dependency versions do not change.
17
+ Build outputs and dependencies are removed after owned child processes exit;
18
+ compact logs, source hashes, response JSON and both data stores remain.
19
+ Source snapshots exclude only the rebuilt `dist/` tree. Missing actual source,
20
+ source symlinks and symlink ancestors still fail the gate; three focused tests
21
+ check that boundary before dependency installation.
22
+
23
+ The complete unedited Catalog/Entry library in `fixture/` is produced by
24
+ `TypescriptNaturalMessagesGenerationTest`. The model supplies Chinese labels and
25
+ classifies `name` as sensitive. Its generated module installs immutable message
26
+ descriptors automatically; no presentation model is installed by the application
27
+ or retained on its Context. The actual generated Checker requires a name and
28
+ limits it to 100 Unicode scalar values.
29
+
30
+ An unchanged parent and two edited children form the failing graph. The second
31
+ child fails required checks in English and Chinese, then exceeds the real length
32
+ bound with 101 private scalars. The message keeps that original count after
33
+ masking. A custom renderer is called once, and its safe text survives graph-path
34
+ relocation without restoring the private input. Every rejection precedes provider
35
+ work and committed mutation audits; the file store also remains byte-identical.
36
+ After restoring the first edit, audited Save updates only the corrected second
37
+ child. Generated Q reloads values and E verifies them. Both provider paths use
38
+ the same runtime privacy and rendering contracts.
39
+
40
+ The complete repository example inventory and published-artifact acceptance
41
+ remain separate gates.
42
+ The runtime renderer is browser-safe and has no Node-only context-local dependency.
43
+
44
+ Tracking: [teaql-ts #65](https://github.com/teaql/teaql-ts/issues/65),
45
+ [conformance #244](https://github.com/teaql/teaql-conformance/issues/244).
source/teaql-ts/examples/natural-messages/fixture/evaluation.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "solids" : [ {
3
+ "ruleId" : "KSML-UPLOAD-001",
4
+ "title" : "Model upload is non-empty",
5
+ "message" : "The upload contains 1 files.",
6
+ "path" : "model.zip",
7
+ "objectName" : null,
8
+ "fieldName" : null,
9
+ "xmlPath" : null,
10
+ "lineNumber" : null,
11
+ "action" : "Check agents/ERROR-FIX.md",
12
+ "reportTarget" : "model.zip"
13
+ }, {
14
+ "ruleId" : "KSML-UPLOAD-005",
15
+ "title" : "Valid entrypoint found",
16
+ "message" : "Resolved entrypoint: model.xml",
17
+ "path" : "model.xml",
18
+ "objectName" : null,
19
+ "fieldName" : null,
20
+ "xmlPath" : "model.xml",
21
+ "lineNumber" : 1,
22
+ "action" : "Check agents/ERROR-FIX.md",
23
+ "reportTarget" : "model.xml"
24
+ }, {
25
+ "ruleId" : "KSML-XML-002",
26
+ "title" : "XML is well-formed",
27
+ "message" : "The XML document model.xml was parsed successfully.",
28
+ "path" : "model.xml",
29
+ "objectName" : null,
30
+ "fieldName" : null,
31
+ "xmlPath" : "model.xml",
32
+ "lineNumber" : 1,
33
+ "action" : "Check agents/ERROR-FIX.md",
34
+ "reportTarget" : "model.xml"
35
+ }, {
36
+ "ruleId" : "KSML-ROOT-003",
37
+ "title" : "Standard root name",
38
+ "message" : "Root name 'natural-message-service' is well-formed.",
39
+ "path" : "/root",
40
+ "objectName" : null,
41
+ "fieldName" : null,
42
+ "xmlPath" : "model.xml",
43
+ "lineNumber" : 1,
44
+ "action" : "Check agents/ERROR-FIX.md",
45
+ "reportTarget" : "/root"
46
+ }, {
47
+ "ruleId" : "KSML-ROOT-008",
48
+ "title" : "Default JSON field naming",
49
+ "message" : "External JSON business fields use the default camelCase profile.",
50
+ "path" : "/root",
51
+ "objectName" : null,
52
+ "fieldName" : null,
53
+ "xmlPath" : "model.xml",
54
+ "lineNumber" : 1,
55
+ "action" : "Check agents/ERROR-FIX.md",
56
+ "reportTarget" : "/root"
57
+ }, {
58
+ "ruleId" : "KSML-REFERENCE-003",
59
+ "title" : "Reference target exists",
60
+ "message" : "Reference 'catalog' in 'entry' successfully resolves to target object 'catalog'.",
61
+ "path" : "/root/entry/catalog",
62
+ "objectName" : "entry",
63
+ "fieldName" : "catalog",
64
+ "xmlPath" : "model.xml",
65
+ "lineNumber" : 3,
66
+ "action" : "Check agents/ERROR-FIX.md",
67
+ "reportTarget" : "entry.catalog"
68
+ }, {
69
+ "ruleId" : "KSML-DOMAIN-ROOT-003",
70
+ "title" : "One domain root found",
71
+ "message" : "Exactly one domain root candidate 'catalog' was found.",
72
+ "path" : "/root",
73
+ "objectName" : null,
74
+ "fieldName" : null,
75
+ "xmlPath" : "model.xml",
76
+ "lineNumber" : 1,
77
+ "action" : "Check agents/ERROR-FIX.md",
78
+ "reportTarget" : "/root"
79
+ } ],
80
+ "warnings" : [ {
81
+ "ruleId" : "KSML-OBJECT-001",
82
+ "title" : "Missing object display metadata",
83
+ "message" : "Object 'catalog' is missing display metadata: _module, _module_key",
84
+ "path" : "/root/catalog",
85
+ "objectName" : "catalog",
86
+ "fieldName" : null,
87
+ "xmlPath" : "model.xml",
88
+ "lineNumber" : 2,
89
+ "action" : "Check agents/ERROR-FIX.md",
90
+ "reportTarget" : "catalog"
91
+ }, {
92
+ "ruleId" : "KSML-OBJECT-001",
93
+ "title" : "Missing object display metadata",
94
+ "message" : "Object 'entry' is missing display metadata: _module, _module_key",
95
+ "path" : "/root/entry",
96
+ "objectName" : "entry",
97
+ "fieldName" : null,
98
+ "xmlPath" : "model.xml",
99
+ "lineNumber" : 3,
100
+ "action" : "Check agents/ERROR-FIX.md",
101
+ "reportTarget" : "entry"
102
+ } ],
103
+ "suggestions" : [ ],
104
+ "errors" : [ ],
105
+ "privacyFindings" : [ ],
106
+ "privacyRegions" : [ ],
107
+ "errorSummaries" : [ ]
108
+ }
source/teaql-ts/examples/natural-messages/fixture/generated-files.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "package.json" : "586e300694b0099b058720ff213730601a9ec25ae6a52f4b15aea5c9fb675054",
3
+ "src/generated-bootstrap.ts" : "677a9cf250a379a43c2be66dec7c34ba16f7c40902ace18ac4848956244a25d2",
4
+ "src/generated-search-models.ts" : "cbef8c139ad276aa2582b260f9bdab1e890964527805493a3887f1bd207f1bc6",
5
+ "src/generated/E.ts" : "169d045fc67673c9bcab19851a962af445193be59d70fd5566a59977056c371a",
6
+ "src/generated/Q.ts" : "482e727f3b0cb5c10dce9924a3aff1d64b0b68d90f2f20374cc2b89018fa9f82",
7
+ "src/generated/models/Catalog.ts" : "f92aaedff2688e897239d149d6f2723792da22588a8737c38f597344de012aea",
8
+ "src/generated/models/Entry.ts" : "0857f86b45f16ba0222220fe12933fd4afa584d0ff826dd206dd6d0c0d8b35da",
9
+ "src/generated/requests/CatalogRequest.ts" : "accacd09d03c992cef2c7a93cf634387d93c37a58c021879fc52ccb0d59283ba",
10
+ "src/generated/requests/EntryRequest.ts" : "b3f3cd544d96ffbcbad6d7203ef3b4735adb60025cecfd2c7fd1f36f9a3cec48",
11
+ "src/runtime-module.ts" : "4e379d29cedf6485d3435fa6eb0ffd62d97e1478c5832ec6262d0258b69ef574",
12
+ "src/teaql-node-sql.ts" : "92133605afea747ce3abdc7b547949860f1761aa2866ca4de8ddada2ad964af3",
13
+ "src/teaql-node-sqlite.ts" : "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c",
14
+ "src/teaql-ts.ts" : "1f0af27f2d14f6bab1963cae88e3776b2fde5e01aa22befd463a50d7a6fb4bab",
15
+ "teaql-i18n.json" : "3142adc809a66c3f45df816e926967273ba7fcf3470c00629fcd6fa8da693f06",
16
+ "teaql/checker-model.json" : "5ac0524fcb22c68970fc358b685d10081e47048af423951514e8d28ec2bd0bc6",
17
+ "teaql/model-provenance.json" : "f03bf5d79f88a745afce41a9c9dd865ba764b8a5525e884468941d835e987ff6",
18
+ "tsconfig.json" : "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037"
19
+ }
source/teaql-ts/examples/natural-messages/fixture/generation.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "teaql.generated-natural-checker-fixture/v1",
3
+ "generatorCommit": "ff5d00f5",
4
+ "scope": "typescript-node-lib-core",
5
+ "test": "TypescriptNaturalMessagesGenerationTest",
6
+ "generationEvidence": "2026-11-12-natural-checker-typescript-generation-qualified",
7
+ "runtimeTarget": "0.5.0-dev.0",
8
+ "dependencyBinding": "repository-local source via the controlled Jest module mapper",
9
+ "sourceFixtureEdited": false,
10
+ "publicPublication": false
11
+ }
source/teaql-ts/examples/natural-messages/fixture/model.xml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <root name="natural-message-service" org="example" data_service="sqlite" teaql_typescript_version="0.5.0-dev.0">
2
+ <catalog _name="catalog" _zh_CN="目录" name="名称:Catalog"/>
3
+ <entry _name="entry" _zh_CN="明细" catalog="catalog()" name="名称:Entry"
4
+ born_at="createTime()" touched_at="updateTime()" _audit_mask_fields="name"/>
5
+ </root>
source/teaql-ts/examples/natural-messages/fixture/package.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "natural-message-service-lib",
3
+ "version": "1.0.0",
4
+ "description": "Generated typescript library",
5
+ "engines": { "node": ">=22" },
6
+ "main": "src/generated/Q.ts",
7
+ "scripts": {
8
+ "build": "tsc --noEmit"
9
+ },
10
+ "dependencies": {
11
+ "teaql-ts": "npm:@teaql/teaql@0.5.0-dev.0",
12
+ "better-sqlite3": "^13.0.3"},
13
+ "devDependencies": {
14
+ "typescript": "^5.0.0",
15
+ "ts-node": "^10.9.2",
16
+ "@types/node": "^22.0.0",
17
+ "@types/better-sqlite3": "^7.6.12"}
18
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated-bootstrap.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserContext, decimal, long, localTime } from './teaql-ts';
2
+ import { Q } from './generated/Q';
3
+ import { Catalog } from './generated/models/Catalog';
4
+
5
+ /** @internal Generated typed Mutation bootstrap; never call from application code. */
6
+ export async function ensureGeneratedBootstrap(context: UserContext): Promise<void> {
7
+ let domainRoot = (await Q.catalogs().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0];
8
+ if (!domainRoot) {
9
+ domainRoot = Catalog.teaqlBootstrapNew('1');
10
+ domainRoot.updateName("Catalog");
11
+ await domainRoot.auditAs('create generated Domain Root Catalog').save(context);
12
+ }
13
+ context.withActiveRoot({ entity: 'Catalog', id: domainRoot.id! });
14
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated-search-models.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { GeneratedSearchModel } from "teaql-ts";
2
+
3
+ /** Generated trusted naming/type metadata. No query execution or authorization lives here. */
4
+ export const GENERATED_SEARCH_MODELS: Readonly<Record<string, GeneratedSearchModel>> = Object.freeze({
5
+ "Catalog": Object.freeze({
6
+ fields: Object.freeze({
7
+ "id": "integer" as const,
8
+ "name": "string" as const,
9
+ "version": "integer" as const,
10
+ }),
11
+ queryFields: Object.freeze({
12
+ "id": "id",
13
+ "name": "name",
14
+ "version": "version",
15
+ }),
16
+ relations: Object.freeze({
17
+ "entryList": "Entry",
18
+ }),
19
+ }),
20
+ "Entry": Object.freeze({
21
+ fields: Object.freeze({
22
+ "id": "integer" as const,
23
+ "catalog": "integer" as const,
24
+ "name": "string" as const,
25
+ "born_at": "timestamp" as const,
26
+ "bornAt": "timestamp" as const,
27
+ "touched_at": "timestamp" as const,
28
+ "touchedAt": "timestamp" as const,
29
+ "version": "integer" as const,
30
+ }),
31
+ queryFields: Object.freeze({
32
+ "id": "id",
33
+ "catalog": "catalog",
34
+ "name": "name",
35
+ "born_at": "bornAt",
36
+ "bornAt": "bornAt",
37
+ "touched_at": "touchedAt",
38
+ "touchedAt": "touchedAt",
39
+ "version": "version",
40
+ }),
41
+ relations: Object.freeze({
42
+ "catalog": "Catalog",
43
+ }),
44
+ }),
45
+ });
source/teaql-ts/examples/natural-messages/fixture/src/generated/E.ts ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts';
2
+ import { Catalog } from './models/Catalog';
3
+ import { Entry } from './models/Entry';
4
+ import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts';
5
+ export { TeaQLNotLoadedError } from '../teaql-ts';
6
+
7
+ export class ValueExpression<T> {
8
+ constructor(
9
+ private readonly value: T | null | undefined,
10
+ private readonly present = true,
11
+ private readonly notLoaded?: TeaQLNotLoadedError,
12
+ private readonly invalidValue?: CheckException,
13
+ ) {}
14
+
15
+ static missing<T>(): ValueExpression<T> {
16
+ return new ValueExpression<T>(undefined, false);
17
+ }
18
+
19
+ static notLoaded<T>(error: TeaQLNotLoadedError): ValueExpression<T> {
20
+ return new ValueExpression<T>(undefined, false, error);
21
+ }
22
+
23
+ static invalid<T>(error: CheckException): ValueExpression<T> {
24
+ return new ValueExpression<T>(undefined, false, undefined, error);
25
+ }
26
+
27
+ eval(): T | null | undefined {
28
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
29
+ if (this.invalidValue) throw this.invalidValue;
30
+ return this.present ? this.value : undefined;
31
+ }
32
+
33
+ isPresent(): boolean {
34
+ if (this.notLoaded) throw this.notLoaded.terminal('isPresent()');
35
+ if (this.invalidValue) throw this.invalidValue;
36
+ return this.present;
37
+ }
38
+
39
+ orElse(fallback: T): T {
40
+ if (this.notLoaded) throw this.notLoaded.terminal('orElse(<fallback>)');
41
+ if (this.invalidValue) throw this.invalidValue;
42
+ const value = this.value;
43
+ return this.present && value != null ? value : fallback;
44
+ }
45
+ }
46
+
47
+ export class CatalogExpression {
48
+ constructor(
49
+ private readonly value: Catalog | null | undefined,
50
+ private readonly root = 'Catalog(null)',
51
+ private readonly path = ExpressionPath.root('E.catalog(<root>)', 'camelCase'),
52
+ private readonly notLoaded?: TeaQLNotLoadedError,
53
+ ) {}
54
+
55
+ eval(): Catalog | null | undefined {
56
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
57
+ return this.value;
58
+ }
59
+
60
+ id(): ValueExpression<string> {
61
+ const path = this.path.member('id', 'id');
62
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
63
+ if (!this.value) return ValueExpression.missing<string>();
64
+ if (!this.value.isLoaded('id')) {
65
+ return ValueExpression.notLoaded<string>(
66
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
67
+ );
68
+ }
69
+ return new ValueExpression<string>(this.value.id);
70
+ }
71
+
72
+ name(): ValueExpression<string> {
73
+ const path = this.path.member('name', 'name');
74
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
75
+ if (!this.value) return ValueExpression.missing<string>();
76
+ if (!this.value.isLoaded('name')) {
77
+ return ValueExpression.notLoaded<string>(
78
+ new TeaQLNotLoadedError(path.markMissing(), 'name'),
79
+ );
80
+ }
81
+ return new ValueExpression<string>(this.value.name);
82
+ }
83
+
84
+ version(): ValueExpression<EntityVersion> {
85
+ const path = this.path.member('version', 'version');
86
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
87
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
88
+ if (!this.value.isLoaded('version')) {
89
+ return ValueExpression.notLoaded<EntityVersion>(
90
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
91
+ );
92
+ }
93
+ return new ValueExpression<EntityVersion>(this.value.version);
94
+ }
95
+
96
+
97
+
98
+ entryList(): EntryListExpression {
99
+ const path = this.path.member('entry_list', 'entryList');
100
+ if (this.notLoaded) {
101
+ return new EntryListExpression([], this.root, path, false, this.notLoaded.withPath(path));
102
+ }
103
+ if (!this.value) return EntryListExpression.missing(this.root, path);
104
+ if (!this.value.isLoaded('entryList')) {
105
+ return new EntryListExpression([], this.root, path, false,
106
+ new TeaQLNotLoadedError(path.markMissing(), 'entry_list'));
107
+ }
108
+ return new EntryListExpression(
109
+ this.value.entryList(), this.root, path,
110
+ );
111
+ }
112
+ }
113
+
114
+ export class EntryExpression {
115
+ constructor(
116
+ private readonly value: Entry | null | undefined,
117
+ private readonly root = 'Entry(null)',
118
+ private readonly path = ExpressionPath.root('E.entry(<root>)', 'camelCase'),
119
+ private readonly notLoaded?: TeaQLNotLoadedError,
120
+ ) {}
121
+
122
+ eval(): Entry | null | undefined {
123
+ if (this.notLoaded) throw this.notLoaded.terminal('eval()');
124
+ return this.value;
125
+ }
126
+
127
+ id(): ValueExpression<string> {
128
+ const path = this.path.member('id', 'id');
129
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
130
+ if (!this.value) return ValueExpression.missing<string>();
131
+ if (!this.value.isLoaded('id')) {
132
+ return ValueExpression.notLoaded<string>(
133
+ new TeaQLNotLoadedError(path.markMissing(), 'id'),
134
+ );
135
+ }
136
+ return new ValueExpression<string>(this.value.id);
137
+ }
138
+
139
+ name(): ValueExpression<string> {
140
+ const path = this.path.member('name', 'name');
141
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
142
+ if (!this.value) return ValueExpression.missing<string>();
143
+ if (!this.value.isLoaded('name')) {
144
+ return ValueExpression.notLoaded<string>(
145
+ new TeaQLNotLoadedError(path.markMissing(), 'name'),
146
+ );
147
+ }
148
+ return new ValueExpression<string>(this.value.name);
149
+ }
150
+
151
+ bornAt(): ValueExpression<string> {
152
+ const path = this.path.member('born_at', 'bornAt');
153
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
154
+ if (!this.value) return ValueExpression.missing<string>();
155
+ if (!this.value.isLoaded('bornAt')) {
156
+ return ValueExpression.notLoaded<string>(
157
+ new TeaQLNotLoadedError(path.markMissing(), 'born_at'),
158
+ );
159
+ }
160
+ return new ValueExpression<string>(this.value.bornAt);
161
+ }
162
+
163
+ touchedAt(): ValueExpression<string> {
164
+ const path = this.path.member('touched_at', 'touchedAt');
165
+ if (this.notLoaded) return ValueExpression.notLoaded<string>(this.notLoaded.withPath(path));
166
+ if (!this.value) return ValueExpression.missing<string>();
167
+ if (!this.value.isLoaded('touchedAt')) {
168
+ return ValueExpression.notLoaded<string>(
169
+ new TeaQLNotLoadedError(path.markMissing(), 'touched_at'),
170
+ );
171
+ }
172
+ return new ValueExpression<string>(this.value.touchedAt);
173
+ }
174
+
175
+ version(): ValueExpression<EntityVersion> {
176
+ const path = this.path.member('version', 'version');
177
+ if (this.notLoaded) return ValueExpression.notLoaded<EntityVersion>(this.notLoaded.withPath(path));
178
+ if (!this.value) return ValueExpression.missing<EntityVersion>();
179
+ if (!this.value.isLoaded('version')) {
180
+ return ValueExpression.notLoaded<EntityVersion>(
181
+ new TeaQLNotLoadedError(path.markMissing(), 'version'),
182
+ );
183
+ }
184
+ return new ValueExpression<EntityVersion>(this.value.version);
185
+ }
186
+
187
+ catalogId(): ValueExpression<string | number> {
188
+ const path = this.path.member('catalog', 'catalogId');
189
+ if (this.notLoaded) return ValueExpression.notLoaded<string | number>(this.notLoaded.withPath(path));
190
+ if (!this.value) return ValueExpression.missing<string | number>();
191
+ if (!this.value.isLoaded('catalog')) {
192
+ return ValueExpression.notLoaded<string | number>(
193
+ new TeaQLNotLoadedError(path.markMissing(), 'catalog'),
194
+ );
195
+ }
196
+ const reference = this.value.catalog;
197
+ return new ValueExpression<string | number>(
198
+ reference instanceof Catalog
199
+ ? reference.id : reference as string | number | undefined,
200
+ );
201
+ }
202
+
203
+ catalog(): CatalogExpression {
204
+ const path = this.path.member('catalog', 'catalog');
205
+ if (this.notLoaded) {
206
+ return new CatalogExpression(undefined, this.root, path, this.notLoaded.withPath(path));
207
+ }
208
+ if (!this.value) return new CatalogExpression(undefined, this.root, path);
209
+ if (!this.value.isLoaded('catalog')) {
210
+ return new CatalogExpression(undefined, this.root, path,
211
+ new TeaQLNotLoadedError(path.markMissing(), 'catalog'));
212
+ }
213
+ const relation = this.value.catalog;
214
+ // An available FK is not an eagerly loaded relation. Keep the FK
215
+ // readable through the Id accessor, without fabricating a child object.
216
+ if (relation != null && !(relation instanceof Catalog)) {
217
+ return new CatalogExpression(undefined, this.root, path,
218
+ new TeaQLNotLoadedError(path.markMissing(), 'catalog'));
219
+ }
220
+ const target = relation instanceof Catalog ? relation : undefined;
221
+ return new CatalogExpression(target, this.root, path);
222
+ }
223
+
224
+ }
225
+
226
+ export class CatalogListExpression {
227
+ constructor(
228
+ private readonly items: readonly Catalog[],
229
+ private readonly root = 'Catalog(null)',
230
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
231
+ private readonly present = true,
232
+ private readonly notLoaded?: TeaQLNotLoadedError,
233
+ ) {}
234
+
235
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): CatalogListExpression {
236
+ return new CatalogListExpression([], root, path, false);
237
+ }
238
+
239
+ size(): ValueExpression<number> {
240
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
241
+ return this.present
242
+ ? new ValueExpression<number>(this.items.length)
243
+ : ValueExpression.missing<number>();
244
+ }
245
+
246
+ first(): CatalogExpression {
247
+ return this.item(0, true);
248
+ }
249
+
250
+ get(index: number): CatalogExpression {
251
+ return this.item(index, false);
252
+ }
253
+
254
+ private item(index: number, first: boolean): CatalogExpression {
255
+ const itemPath = this.path.index(index, first);
256
+ if (this.notLoaded) {
257
+ return new CatalogExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
258
+ }
259
+ return !this.present || index < 0 || index >= this.items.length
260
+ ? new CatalogExpression(undefined, this.root, itemPath)
261
+ : new CatalogExpression(this.items[index], this.root, itemPath);
262
+ }
263
+ }
264
+
265
+ export class EntryListExpression {
266
+ constructor(
267
+ private readonly items: readonly Entry[],
268
+ private readonly root = 'Entry(null)',
269
+ private readonly path = ExpressionPath.root('E.entity(<root>)', 'camelCase'),
270
+ private readonly present = true,
271
+ private readonly notLoaded?: TeaQLNotLoadedError,
272
+ ) {}
273
+
274
+ static missing(root?: string, path = ExpressionPath.root('E.entity(<root>)', 'camelCase')): EntryListExpression {
275
+ return new EntryListExpression([], root, path, false);
276
+ }
277
+
278
+ size(): ValueExpression<number> {
279
+ if (this.notLoaded) return ValueExpression.notLoaded<number>(this.notLoaded.withPath(this.path.operation('size()')));
280
+ return this.present
281
+ ? new ValueExpression<number>(this.items.length)
282
+ : ValueExpression.missing<number>();
283
+ }
284
+
285
+ first(): EntryExpression {
286
+ return this.item(0, true);
287
+ }
288
+
289
+ get(index: number): EntryExpression {
290
+ return this.item(index, false);
291
+ }
292
+
293
+ private item(index: number, first: boolean): EntryExpression {
294
+ const itemPath = this.path.index(index, first);
295
+ if (this.notLoaded) {
296
+ return new EntryExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath));
297
+ }
298
+ return !this.present || index < 0 || index >= this.items.length
299
+ ? new EntryExpression(undefined, this.root, itemPath)
300
+ : new EntryExpression(this.items[index], this.root, itemPath);
301
+ }
302
+ }
303
+
304
+ export class E {
305
+ static catalog(
306
+ value: Catalog | null | undefined,
307
+ ): CatalogExpression {
308
+ return new CatalogExpression(
309
+ value, 'Catalog', ExpressionPath.root('E.catalog(<root>)', 'camelCase'),
310
+ );
311
+ }
312
+
313
+ static entry(
314
+ value: Entry | null | undefined,
315
+ ): EntryExpression {
316
+ return new EntryExpression(
317
+ value, 'Entry', ExpressionPath.root('E.entry(<root>)', 'camelCase'),
318
+ );
319
+ }
320
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated/Q.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { TeaQLClient } from '../teaql-ts';
2
+ import { CatalogRequest } from './requests/CatalogRequest';
3
+ import { EntryRequest } from './requests/EntryRequest';
4
+
5
+ export class Q {
6
+ static catalogs(): CatalogRequest {
7
+ return new CatalogRequest(false);
8
+ }
9
+
10
+ static catalogsWithMinimalFields(): CatalogRequest {
11
+ return new CatalogRequest(true);
12
+ }
13
+ static entries(): EntryRequest {
14
+ return new EntryRequest(false);
15
+ }
16
+
17
+ static entriesWithMinimalFields(): EntryRequest {
18
+ return new EntryRequest(true);
19
+ }
20
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Catalog.ts ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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';
2
+ import { Entry } from './Entry';
3
+
4
+ export class Catalog {
5
+ private static teaqlTemporaryId = 0;
6
+ private static readonly teaqlMutationFields = new MutationFieldLayout("Catalog",
7
+ ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" });
8
+ id?: string;
9
+ name?: string;
10
+ version?: EntityVersion;
11
+
12
+ constructor(init?: Partial<Catalog>) {
13
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
14
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
15
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
16
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Catalog.teaqlTemporaryId, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_entryList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false });
20
+ if (init) {
21
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
22
+ delete fields["entryList"];
23
+ Object.assign(this, fields);
24
+ if (Array.isArray((init as any).entryList)) {
25
+ const selected = (init as any).entryList;
26
+ (this as any)._entryList = new SmartList(selected.map(
27
+ (child: unknown) => child instanceof Entry
28
+ ? child
29
+ : Entry.fromRecord(child as Record<string, unknown>),
30
+ ), { totalCount: selected.totalCount, aggregations: selected.aggregations,
31
+ summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true });
32
+ this.markLoaded("entryList");
33
+ }
34
+ }
35
+ const key = this.teaqlEntityKey();
36
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
37
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
38
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
39
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version);
40
+ }
41
+
42
+ private teaqlEntityKey(): EntityKey { return { entity: "Catalog", id: (this as any)._ledgerId }; }
43
+ /** @internal Restore known equal scalars after the prepared graph completes. */
44
+ private teaqlRestoreFixedValues(values: Readonly<Record<string, unknown>>): void {
45
+ for (const field of [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]) {
46
+ if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical];
47
+ }
48
+ }
49
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
50
+ if ((this as any)._root !== root) {
51
+ root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
52
+ (this as any)._root = root;
53
+ }
54
+ for (const child of (this as any)._entryList) child.teaqlAttachRoot(root, hydration);
55
+ return this;
56
+ }
57
+
58
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Catalog {
59
+ const entity = new Catalog(record as Partial<Catalog>);
60
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
61
+ }
62
+
63
+ toJSON(): Record<string, unknown> {
64
+ return this.teaqlJson(new Set());
65
+ }
66
+
67
+ private static teaqlJsonValue(value: any, active: Set<object>): any {
68
+ if (value === null || value === undefined) return value;
69
+ if (typeof value.teaqlJson === "function") return value.teaqlJson(active);
70
+ if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active));
71
+ if (typeof value.toJSON === "function") return value.toJSON();
72
+ if (typeof value === "object") return Object.fromEntries(Object.entries(value).map(
73
+ ([key, item]) => [key, this.teaqlJsonValue(item, active)]));
74
+ return typeof value === "bigint" ? value.toString() : value;
75
+ }
76
+
77
+ private teaqlJson(active: Set<object>): Record<string, unknown> {
78
+ if (active.has(this)) return { id: this.id, version: this.version };
79
+ active.add(this);
80
+ try {
81
+ // Only enumerable business/query data participates; runtime state is private.
82
+ const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key))
83
+ .map(([key, value]) => [key, Catalog.teaqlJsonValue(value, active)]));
84
+ const childrenEntryList = this.entryList();
85
+ if (childrenEntryList.isLoaded || childrenEntryList.some(child =>
86
+ (child as any)._root.hasPending((child as any).teaqlEntityKey()))) {
87
+ payload["entryList"] = Catalog.teaqlJsonValue(childrenEntryList, active);
88
+ }
89
+ return payload;
90
+ } finally { active.delete(this); }
91
+ }
92
+
93
+ isLoaded(field: string): boolean {
94
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
95
+ }
96
+
97
+ markLoaded(...fields: string[]): this {
98
+ for (const field of fields) (this as any)._loadedFields.add(field);
99
+ return this;
100
+ }
101
+
102
+ markLoadedOnly(...fields: string[]): this {
103
+ (this as any)._fullyLoaded = false;
104
+ (this as any)._loadedFields = new Set(fields);
105
+ return this;
106
+ }
107
+
108
+ static refer(id: string | number): Catalog {
109
+ return new Catalog({ id: String(id) } as Partial<Catalog>);
110
+ }
111
+
112
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
113
+ static teaqlBootstrapNew(id: string | number): Catalog {
114
+ return new Catalog().updateId(String(id));
115
+ }
116
+
117
+ markForDeletion(): this {
118
+ (this as any)._action = "Delete";
119
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
120
+ return this;
121
+ }
122
+
123
+ auditAs(comment: string): this {
124
+ (this as any)._comment = new MutationIntent(comment).comment;
125
+ return this;
126
+ }
127
+
128
+ async save(context: UserContext): Promise<Catalog> {
129
+ const intent = new MutationIntent((this as any)._comment);
130
+ const service = context.requireResource<TeaQLDataService>("dataService");
131
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
132
+ return this.teaqlSaveWithinGraph(context, service, graph);
133
+ }, (graph) => {
134
+ this.teaqlPreflightGraph(context, service, graph);
135
+ this.teaqlValidateLoadedIdentities();
136
+ this.teaqlAdmitGraph();
137
+ graph.sealPreparedGraph();
138
+ }, (graph) => {
139
+ this.teaqlValidateLoadedIdentities();
140
+ this.teaqlDiscardRestoredGraph(graph);
141
+ this.teaqlAdmitGraph();
142
+ this.teaqlNormalizeGraph(graph);
143
+ return this.teaqlAdmitGraph();
144
+ });
145
+ }
146
+
147
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
148
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
149
+ if (seen.has(this)) return;
150
+ seen.add(this);
151
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
152
+ for (const [index, child] of (this as any)._entryList.entries()) {
153
+ try { child.teaqlValidateLoadedIdentities(seen); }
154
+ catch (error) {
155
+ if (!(error instanceof CheckException)) throw error;
156
+ const prefix = ObjectLocation.property("entry_list").index(index);
157
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
158
+ }
159
+ }
160
+ }
161
+
162
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
163
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
164
+ if (seen.has(this)) return;
165
+ seen.add(this);
166
+ graph.discardRestoredFields(Catalog.teaqlMutationFields,
167
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
168
+ for (const child of (this as any)._entryList) child.teaqlDiscardRestoredGraph(graph, seen);
169
+ }
170
+
171
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
172
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
173
+ if (seen.has(this)) return;
174
+ seen.add(this);
175
+ graph.discardRestoredFields(Catalog.teaqlMutationFields,
176
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
177
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
178
+ }, () => ({ ...this.teaqlMutationPayload(),
179
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
180
+ __teaql_comment: (this as any)._comment,
181
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
182
+ "entry_list": graph.sourceMembers((this as any)._entryList)
183
+ }));
184
+ for (const child of (this as any)._entryList) {
185
+ child.teaqlAttachRoot((this as any)._root);
186
+ const currentParent = child.catalog;
187
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
188
+ && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null
189
+ ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this);
190
+ child.teaqlNormalizeGraph(graph, seen);
191
+ }
192
+ }
193
+
194
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
195
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
196
+ if (seen.has(this)) return false;
197
+ seen.add(this);
198
+ const action = (this as any)._action;
199
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
200
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
201
+ Catalog.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
202
+ if (pending) {
203
+ nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version);
204
+ if (action === "Update") {
205
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member));
206
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Catalog", location: ObjectLocation.property(notLoaded.canonical),
207
+ message: "Mutation requires a fully loaded entity"}]);
208
+ }
209
+ }
210
+ let graphPending = pending;
211
+ for (const [index, child] of (this as any)._entryList.entries()) {
212
+ try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; }
213
+ catch (error) {
214
+ if (!(error instanceof CheckException)) throw error;
215
+ const prefix = ObjectLocation.property("entry_list").index(index);
216
+ throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) })));
217
+ }
218
+ }
219
+ return graphPending;
220
+ }
221
+
222
+ /** @internal Validates and fixes the complete graph before its first mutation. */
223
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
224
+ if (!parent) new MutationIntent((this as any)._comment);
225
+ const action = (this as any)._action;
226
+ graph.discardRestoredFields(Catalog.teaqlMutationFields,
227
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
228
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
229
+ if (action === "Update" && pending) {
230
+ const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]
231
+ .find(field => !this.isLoaded(field.member));
232
+ if (notLoaded) {
233
+ throw new CheckException([{
234
+ ruleId: "invalid_type",
235
+ entityType: "Catalog",
236
+ location: ObjectLocation.property(notLoaded.canonical),
237
+ message: "Mutation requires a fully loaded entity",
238
+ }]);
239
+ }
240
+ }
241
+ const request = graph.request({
242
+ entity: "Catalog", action,
243
+ payload: action === "Update"
244
+ ? (this as any)._root.change(this.teaqlEntityKey())
245
+ : this.teaqlMutationPayload(),
246
+ id: (this as any).id,
247
+ version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version,
248
+ comment: (this as any)._comment,
249
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
250
+ }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
251
+ if (pending) service.preflightMutation(request);
252
+ const scope = request.scopeFor(this.teaqlEntityKey());
253
+ for (const [index, child] of (this as any)._entryList.entries()) {
254
+ child.teaqlAttachRoot((this as any)._root);
255
+ const currentParent = child.catalog;
256
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
257
+ && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null
258
+ ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this);
259
+ try { child.teaqlPreflightGraph(context, service, graph, scope); }
260
+ catch (error) {
261
+ if (!(error instanceof CheckException)) throw error;
262
+ const prefix = ObjectLocation.property("entry_list").index(index);
263
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
264
+ ...violation, location: violation.location.prefixedBy(prefix),
265
+ }))));
266
+ }
267
+ }
268
+ }
269
+
270
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
271
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Catalog> {
272
+ if (!parent) new MutationIntent((this as any)._comment);
273
+ const action = (this as any)._action;
274
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
275
+ const mutation = {
276
+ entity: "Catalog",
277
+ action: (this as any)._action,
278
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
279
+ id: (this as any).id,
280
+ version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version,
281
+ comment: (this as any)._comment
282
+ ,ledgerKey: this.teaqlEntityKey()
283
+ ,ledgerRoot: (this as any)._root
284
+ };
285
+ const request = graph.request(mutation, parent, (this as any)._comment)
286
+ .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
287
+ if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) {
288
+ const scope = request.scopeFor(this.teaqlEntityKey());
289
+ for (const [index, child] of (this as any)._entryList.entries()) {
290
+ child.teaqlAttachRoot((this as any)._root);
291
+ const currentParent = child.catalog;
292
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
293
+ && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null
294
+ ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this);
295
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
296
+ catch (error) {
297
+ if (!(error instanceof CheckException)) throw error;
298
+ const prefix = ObjectLocation.property("entry_list").index(index);
299
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
300
+ ...violation, location: violation.location.prefixedBy(prefix),
301
+ }))));
302
+ }
303
+ }
304
+ return this;
305
+ }
306
+ const result = await service.executeMutation(request);
307
+ graph.validatePreparedSources();
308
+ if (!result.persistedRecord) {
309
+ throw new Error("Mutation did not return the authoritative persisted record");
310
+ }
311
+ const rollbackState = {
312
+ ownProperties: Object.getOwnPropertyDescriptors(this),
313
+ ledgerId: (this as any)._ledgerId,
314
+ action: (this as any)._action,
315
+ loadedFields: new Set((this as any)._loadedFields),
316
+ fullyLoaded: (this as any)._fullyLoaded,
317
+ loadedSnapshot: LoadedScalarSnapshot.forEntity(this),
318
+ };
319
+ const oldKey = this.teaqlEntityKey();
320
+ Object.assign(this, result.persistedRecord);
321
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
322
+ const newKey = this.teaqlEntityKey();
323
+ (this as any)._root.rekey(oldKey, newKey);
324
+ const committedSnapshot = this.teaqlScalarSnapshot();
325
+ const activeScope = request.scopeFor(newKey);
326
+ service.afterGraphRollback(() => {
327
+ for (const name of Object.getOwnPropertyNames(this)) {
328
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
329
+ }
330
+ Object.defineProperties(this, rollbackState.ownProperties);
331
+ (this as any)._ledgerId = rollbackState.ledgerId;
332
+ (this as any)._action = rollbackState.action;
333
+ (this as any)._loadedFields = rollbackState.loadedFields;
334
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
335
+ LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot);
336
+ (this as any)._root.rekey(newKey, oldKey);
337
+ });
338
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
339
+ (this as any)._fullyLoaded = false;
340
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
341
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
342
+ const scope = request.scopeFor(newKey);
343
+ for (const [index, child] of (this as any)._entryList.entries()) {
344
+ child.teaqlAttachRoot((this as any)._root);
345
+ const currentParent = child.catalog;
346
+ if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey()))
347
+ && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null
348
+ ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this);
349
+ try { await child.teaqlSaveWithinGraph(context, service, graph, scope); }
350
+ catch (error) {
351
+ if (!(error instanceof CheckException)) throw error;
352
+ const prefix = ObjectLocation.property("entry_list").index(index);
353
+ throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({
354
+ ...violation, location: violation.location.prefixedBy(prefix),
355
+ }))));
356
+ }
357
+ }
358
+ service.afterGraphCommit(() => {
359
+ graph.validatePreparedSources();
360
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
361
+ (this as any)._root.clearEntity(newKey);
362
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
363
+ graph.finishPreparedCommit((this as any)._root, newKey);
364
+ });
365
+ return this;
366
+ }
367
+
368
+ private teaqlMutationPayload(): Record<string, unknown> {
369
+ return {
370
+ "id": this.id,
371
+ "name": this.name,
372
+ "version": this.version
373
+ };
374
+ }
375
+
376
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
377
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
378
+ }
379
+
380
+ updateId(value: string): this {
381
+ this.id = value;
382
+ this.markLoaded("id");
383
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
384
+ return this;
385
+ }
386
+
387
+ updateName(value: string): this {
388
+ this.name = value;
389
+ this.markLoaded("name");
390
+ (this as any)._root.set(this.teaqlEntityKey(), "name", value);
391
+ return this;
392
+ }
393
+
394
+ updateVersion(value: EntityVersion): this {
395
+ this.version = value;
396
+ this.markLoaded("version");
397
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
398
+ return this;
399
+ }
400
+ entryList(): SmartList<Entry> {
401
+ return (this as any)._entryList;
402
+ }
403
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated/models/Entry.ts ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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';
2
+ import { Catalog } from './Catalog';
3
+
4
+ export class Entry {
5
+ private static teaqlTemporaryId = 0;
6
+ private static readonly teaqlMutationFields = new MutationFieldLayout("Entry",
7
+ ["id", "catalog", "name", "born_at", "touched_at", "version"], { id: "immutable_field", version: "immutable_field" });
8
+ id?: string;
9
+ catalog?: Catalog | string;
10
+ name?: string;
11
+ bornAt?: string;
12
+ touchedAt?: string;
13
+ version?: EntityVersion;
14
+
15
+ constructor(init?: Partial<Entry>) {
16
+ Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false });
17
+ Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false });
18
+ Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false });
19
+ Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false });
20
+ Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false });
21
+ Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Entry.teaqlTemporaryId, writable: true, enumerable: false });
22
+ if (init) {
23
+ const fields: Record<string, unknown> = { ...(init as Record<string, unknown>) };
24
+ Object.assign(this, fields);
25
+ if ((init as any).catalog && typeof (init as any).catalog === "object") {
26
+ this.catalog = (init as any).catalog instanceof Catalog
27
+ ? (init as any).catalog
28
+ : Catalog.fromRecord((init as any).catalog);
29
+ this.markLoaded("catalog");
30
+ }
31
+ }
32
+ const key = this.teaqlEntityKey();
33
+ if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version);
34
+ if ((this as any)._action === "Create") (this as any)._root.markAsNew(key);
35
+ else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version);
36
+ LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version);
37
+ }
38
+
39
+ private teaqlEntityKey(): EntityKey { return { entity: "Entry", id: (this as any)._ledgerId }; }
40
+ /** @internal Restore known equal scalars after the prepared graph completes. */
41
+ private teaqlRestoreFixedValues(values: Readonly<Record<string, unknown>>): void {
42
+ 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" }]) {
43
+ if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical];
44
+ }
45
+ }
46
+ private teaqlAttachRoot(root: EntityRoot, hydration = false): this {
47
+ if ((this as any)._root !== root) {
48
+ root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey());
49
+ (this as any)._root = root;
50
+ }
51
+ return this;
52
+ }
53
+
54
+ static fromRecord(record: Record<string, unknown>, root?: EntityRoot): Entry {
55
+ const entity = new Entry(record as Partial<Entry>);
56
+ return root ? entity.teaqlAttachRoot(root, true) : entity;
57
+ }
58
+
59
+ toJSON(): Record<string, unknown> {
60
+ return this.teaqlJson(new Set());
61
+ }
62
+
63
+ private static teaqlJsonValue(value: any, active: Set<object>): any {
64
+ if (value === null || value === undefined) return value;
65
+ if (typeof value.teaqlJson === "function") return value.teaqlJson(active);
66
+ if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active));
67
+ if (typeof value.toJSON === "function") return value.toJSON();
68
+ if (typeof value === "object") return Object.fromEntries(Object.entries(value).map(
69
+ ([key, item]) => [key, this.teaqlJsonValue(item, active)]));
70
+ return typeof value === "bigint" ? value.toString() : value;
71
+ }
72
+
73
+ private teaqlJson(active: Set<object>): Record<string, unknown> {
74
+ if (active.has(this)) return { id: this.id, version: this.version };
75
+ active.add(this);
76
+ try {
77
+ // Only enumerable business/query data participates; runtime state is private.
78
+ const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key))
79
+ .map(([key, value]) => [key, Entry.teaqlJsonValue(value, active)]));
80
+ return payload;
81
+ } finally { active.delete(this); }
82
+ }
83
+
84
+ isLoaded(field: string): boolean {
85
+ return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field);
86
+ }
87
+
88
+ markLoaded(...fields: string[]): this {
89
+ for (const field of fields) (this as any)._loadedFields.add(field);
90
+ return this;
91
+ }
92
+
93
+ markLoadedOnly(...fields: string[]): this {
94
+ (this as any)._fullyLoaded = false;
95
+ (this as any)._loadedFields = new Set(fields);
96
+ return this;
97
+ }
98
+
99
+ static refer(id: string | number): Entry {
100
+ return new Entry({ id: String(id) } as Partial<Entry>);
101
+ }
102
+
103
+ /** @internal Generated Runtime Module fixed-ID construction capability. */
104
+ static teaqlBootstrapNew(id: string | number): Entry {
105
+ return new Entry().updateId(String(id));
106
+ }
107
+
108
+ markForDeletion(): this {
109
+ (this as any)._action = "Delete";
110
+ (this as any)._root.markAsDeleted(this.teaqlEntityKey());
111
+ return this;
112
+ }
113
+
114
+ auditAs(comment: string): this {
115
+ (this as any)._comment = new MutationIntent(comment).comment;
116
+ return this;
117
+ }
118
+
119
+ async save(context: UserContext): Promise<Entry> {
120
+ const intent = new MutationIntent((this as any)._comment);
121
+ const service = context.requireResource<TeaQLDataService>("dataService");
122
+ return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => {
123
+ return this.teaqlSaveWithinGraph(context, service, graph);
124
+ }, (graph) => {
125
+ this.teaqlPreflightGraph(context, service, graph);
126
+ this.teaqlValidateLoadedIdentities();
127
+ this.teaqlAdmitGraph();
128
+ graph.sealPreparedGraph();
129
+ }, (graph) => {
130
+ this.teaqlValidateLoadedIdentities();
131
+ this.teaqlDiscardRestoredGraph(graph);
132
+ this.teaqlAdmitGraph();
133
+ this.teaqlNormalizeGraph(graph);
134
+ return this.teaqlAdmitGraph();
135
+ });
136
+ }
137
+
138
+ /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */
139
+ private teaqlValidateLoadedIdentities(seen = new Set<object>()): void {
140
+ if (seen.has(this)) return;
141
+ seen.add(this);
142
+ LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version);
143
+ }
144
+
145
+ /** @internal Cancel known no-ops across the graph before any derived FK edits. */
146
+ private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
147
+ if (seen.has(this)) return;
148
+ seen.add(this);
149
+ graph.discardRestoredFields(Entry.teaqlMutationFields,
150
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
151
+ }
152
+
153
+ /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */
154
+ private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set<object>()): void {
155
+ if (seen.has(this)) return;
156
+ seen.add(this);
157
+ graph.discardRestoredFields(Entry.teaqlMutationFields,
158
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
159
+ graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), {
160
+ "catalog": "Catalog"
161
+ }, () => ({ ...this.teaqlMutationPayload(),
162
+ __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action,
163
+ __teaql_comment: (this as any)._comment,
164
+ __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()},
165
+ }));
166
+ }
167
+
168
+ /** @internal Whole-input version/completeness pass; does not use Context or Fix. */
169
+ private teaqlAdmitGraph(seen = new Set<object>()): boolean {
170
+ if (seen.has(this)) return false;
171
+ seen.add(this);
172
+ const action = (this as any)._action;
173
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
174
+ LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey());
175
+ Entry.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update");
176
+ if (pending) {
177
+ nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version);
178
+ if (action === "Update") {
179
+ 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));
180
+ if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Entry", location: ObjectLocation.property(notLoaded.canonical),
181
+ message: "Mutation requires a fully loaded entity"}]);
182
+ }
183
+ }
184
+ let graphPending = pending;
185
+ return graphPending;
186
+ }
187
+
188
+ /** @internal Validates and fixes the complete graph before its first mutation. */
189
+ teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void {
190
+ if (!parent) new MutationIntent((this as any)._comment);
191
+ const action = (this as any)._action;
192
+ graph.discardRestoredFields(Entry.teaqlMutationFields,
193
+ (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this));
194
+ const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey());
195
+ if (action === "Update" && pending) {
196
+ 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" }]
197
+ .find(field => !this.isLoaded(field.member));
198
+ if (notLoaded) {
199
+ throw new CheckException([{
200
+ ruleId: "invalid_type",
201
+ entityType: "Entry",
202
+ location: ObjectLocation.property(notLoaded.canonical),
203
+ message: "Mutation requires a fully loaded entity",
204
+ }]);
205
+ }
206
+ }
207
+ const request = graph.request({
208
+ entity: "Entry", action,
209
+ payload: action === "Update"
210
+ ? (this as any)._root.change(this.teaqlEntityKey())
211
+ : this.teaqlMutationPayload(),
212
+ id: (this as any).id,
213
+ version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version,
214
+ comment: (this as any)._comment,
215
+ ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root,
216
+ }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
217
+ if (pending) service.preflightMutation(request);
218
+ const scope = request.scopeFor(this.teaqlEntityKey());
219
+ }
220
+
221
+ /** @internal Used by generated relation cascades inside the root graph transaction. */
222
+ async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise<Entry> {
223
+ if (!parent) new MutationIntent((this as any)._comment);
224
+ const action = (this as any)._action;
225
+ const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey());
226
+ const mutation = {
227
+ entity: "Entry",
228
+ action: (this as any)._action,
229
+ payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(),
230
+ id: (this as any).id,
231
+ version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version,
232
+ comment: (this as any)._comment
233
+ ,ledgerKey: this.teaqlEntityKey()
234
+ ,ledgerRoot: (this as any)._root
235
+ };
236
+ const request = graph.request(mutation, parent, (this as any)._comment)
237
+ .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot());
238
+ if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) {
239
+ const scope = request.scopeFor(this.teaqlEntityKey());
240
+ return this;
241
+ }
242
+ const result = await service.executeMutation(request);
243
+ graph.validatePreparedSources();
244
+ if (!result.persistedRecord) {
245
+ throw new Error("Mutation did not return the authoritative persisted record");
246
+ }
247
+ const rollbackState = {
248
+ ownProperties: Object.getOwnPropertyDescriptors(this),
249
+ ledgerId: (this as any)._ledgerId,
250
+ action: (this as any)._action,
251
+ loadedFields: new Set((this as any)._loadedFields),
252
+ fullyLoaded: (this as any)._fullyLoaded,
253
+ loadedSnapshot: LoadedScalarSnapshot.forEntity(this),
254
+ };
255
+ const oldKey = this.teaqlEntityKey();
256
+ Object.assign(this, result.persistedRecord);
257
+ (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId;
258
+ const newKey = this.teaqlEntityKey();
259
+ (this as any)._root.rekey(oldKey, newKey);
260
+ const committedSnapshot = this.teaqlScalarSnapshot();
261
+ const activeScope = request.scopeFor(newKey);
262
+ service.afterGraphRollback(() => {
263
+ for (const name of Object.getOwnPropertyNames(this)) {
264
+ if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name];
265
+ }
266
+ Object.defineProperties(this, rollbackState.ownProperties);
267
+ (this as any)._ledgerId = rollbackState.ledgerId;
268
+ (this as any)._action = rollbackState.action;
269
+ (this as any)._loadedFields = rollbackState.loadedFields;
270
+ (this as any)._fullyLoaded = rollbackState.fullyLoaded;
271
+ LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot);
272
+ (this as any)._root.rekey(newKey, oldKey);
273
+ });
274
+ (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord));
275
+ (this as any)._fullyLoaded = false;
276
+ if (mutation.action !== "Delete") (this as any)._action = "Update";
277
+ graph.acceptPreparedResult((this as any)._root, oldKey, newKey);
278
+ const scope = request.scopeFor(newKey);
279
+ service.afterGraphCommit(() => {
280
+ graph.validatePreparedSources();
281
+ LoadedScalarSnapshot.restoreFor(this, committedSnapshot);
282
+ (this as any)._root.clearEntity(newKey);
283
+ if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version);
284
+ graph.finishPreparedCommit((this as any)._root, newKey);
285
+ });
286
+ return this;
287
+ }
288
+
289
+ private teaqlMutationPayload(): Record<string, unknown> {
290
+ return {
291
+ "id": this.id,
292
+ "catalog": this.catalog,
293
+ "name": this.name,
294
+ "born_at": this.bornAt,
295
+ "touched_at": this.touchedAt,
296
+ "version": this.version
297
+ };
298
+ }
299
+
300
+ private teaqlScalarSnapshot(): LoadedScalarSnapshot {
301
+ return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version);
302
+ }
303
+
304
+ updateId(value: string): this {
305
+ this.id = value;
306
+ this.markLoaded("id");
307
+ (this as any)._root.set(this.teaqlEntityKey(), "id", value);
308
+ return this;
309
+ }
310
+
311
+ updateName(value: string): this {
312
+ this.name = value;
313
+ this.markLoaded("name");
314
+ (this as any)._root.set(this.teaqlEntityKey(), "name", value);
315
+ return this;
316
+ }
317
+
318
+ updateBornAt(value: string): this {
319
+ this.bornAt = value;
320
+ this.markLoaded("bornAt");
321
+ (this as any)._root.set(this.teaqlEntityKey(), "born_at", value);
322
+ return this;
323
+ }
324
+
325
+ updateTouchedAt(value: string): this {
326
+ this.touchedAt = value;
327
+ this.markLoaded("touchedAt");
328
+ (this as any)._root.set(this.teaqlEntityKey(), "touched_at", value);
329
+ return this;
330
+ }
331
+
332
+ updateVersion(value: EntityVersion): this {
333
+ this.version = value;
334
+ this.markLoaded("version");
335
+ (this as any)._root.set(this.teaqlEntityKey(), "version", value);
336
+ return this;
337
+ }
338
+ updateCatalog(value: any): this {
339
+ this.catalog = value?.id ?? value;
340
+ this.markLoaded("catalog");
341
+ (this as any)._root.set(this.teaqlEntityKey(), "catalog", this.catalog);
342
+ return this;
343
+ }
344
+
345
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/CatalogRequest.ts ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { Catalog } from '../models/Catalog';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
+
7
+
8
+
9
+ export class CatalogRequest {
10
+ private query: SelectQuery;
11
+ private filters: any[] = [];
12
+ private _purpose: string | undefined;
13
+ private _comment: string | undefined;
14
+ private _pageCountAlias: string | undefined;
15
+ private _pageCountMethod: "count" | "countAs" | undefined;
16
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
17
+
18
+ constructor(minimal = false) {
19
+ this.query = new SelectQuery("Catalog");
20
+ this.filters.push({ version: { "$gte": 1 } });
21
+ if (minimal) {
22
+ this.selectId();
23
+ this.selectVersion();
24
+ }
25
+ else this.selectSelfFields();
26
+ }
27
+
28
+ comment(c: string): this {
29
+ this.query.comment(c);
30
+ this._comment = c;
31
+ return this;
32
+ }
33
+
34
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
35
+ const base = this.query.clone();
36
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
37
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
38
+ this.query = merged.query as SelectQuery;
39
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
40
+ this._dynamicSearchWarnings.push(...merged.warnings);
41
+ return this;
42
+ }
43
+
44
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
45
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
46
+ }
47
+
48
+ purpose(p: string): ExecutableCatalogRequest {
49
+ this.query.purpose(p);
50
+ this._purpose = p;
51
+ return new ExecutableCatalogRequest(
52
+ (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)),
53
+ (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.query.withDeletedRows();
104
+ this.filters = this.filters.filter(filter => !("version" in filter));
105
+ return this;
106
+ }
107
+
108
+ deletedRowsOnly(): this {
109
+ this.withDeletedRows();
110
+ this.query.deletedRowsOnly();
111
+ this.filters.push({ version: { "$lte": -1 } });
112
+ return this;
113
+ }
114
+
115
+ selectSelfFields(): this {
116
+ this.query.select(["id", "name", "version"]);
117
+ return this;
118
+ }
119
+
120
+ selectId(): this {
121
+ this.query.select(["id"]);
122
+ return this;
123
+ }
124
+
125
+ selectName(): this {
126
+ this.query.select(["name"]);
127
+ return this;
128
+ }
129
+
130
+ selectVersion(): this {
131
+ this.query.select(["version"]);
132
+ return this;
133
+ }
134
+
135
+
136
+
137
+
138
+ selectEntryListWith(request: { toQuery(): SelectQuery }): this {
139
+ this.query.relationQuery(
140
+ "entryList", request.toQuery(), "id", "catalog", true,
141
+ { kind: "relation-select", method: "selectEntryListWith", relation: "entryList" });
142
+ return this;
143
+ }
144
+
145
+ haveEntries(): this {
146
+ return this.withEntryListMatching({
147
+ toQuery: () => new SelectQuery("Entry"),
148
+ });
149
+ }
150
+
151
+ haveNoEntries(): this {
152
+ return this.withoutEntryListMatching({
153
+ toQuery: () => new SelectQuery("Entry"),
154
+ });
155
+ }
156
+
157
+ withEntryListMatching(request: { toQuery(): SelectQuery }): this {
158
+ this.filters.push({
159
+ "id": {
160
+ "$inSubquery": {
161
+ query: request.toQuery(), field: "catalog",
162
+ },
163
+ },
164
+ });
165
+ return this;
166
+ }
167
+
168
+ withoutEntryListMatching(request: { toQuery(): SelectQuery }): this {
169
+ this.filters.push({
170
+ "id": {
171
+ "$notInSubquery": {
172
+ query: request.toQuery(), field: "catalog",
173
+ },
174
+ },
175
+ });
176
+ return this;
177
+ }
178
+
179
+ countEntries(): this {
180
+ return this.countEntriesAs("countEntries");
181
+ }
182
+
183
+ countEntriesAs(alias: string): this {
184
+ const query = new SelectQuery("Entry").filter({ version: { "$gte": 1 } });
185
+ this.countEntriesWith(alias, { toQuery: () => query });
186
+ this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = {
187
+ kind: "relation-count", method: "countEntriesAs", relation: "entryList", alias };
188
+ return this;
189
+ }
190
+
191
+ countEntriesWith(alias: string, child: { toQuery(): SelectQuery }): this {
192
+ const query = child.toQuery().clone();
193
+ query.aggregateItems = [];
194
+ query.aggregate("Count", "id", alias);
195
+ this.query.relationAggregate("entryList", alias, query, true,
196
+ { kind: "relation-count", method: "countEntriesWith", relation: "entryList", alias });
197
+ return this;
198
+ }
199
+
200
+
201
+
202
+ withIdIs(val: any): this {
203
+ this.filters.push({ "id": { "$eq": val } });
204
+ return this;
205
+ }
206
+
207
+ withIdIsNot(val: any): this {
208
+ this.filters.push({ "id": { "$ne": val } });
209
+ return this;
210
+ }
211
+
212
+ withIdIn(...vals: any[]): this {
213
+ this.filters.push({ "id": { "$in": vals } });
214
+ return this;
215
+ }
216
+
217
+ withIdNotIn(...vals: any[]): this {
218
+ this.filters.push({ "id": { "$notIn": vals } });
219
+ return this;
220
+ }
221
+
222
+ withIdGreaterThan(val: any): this {
223
+ this.filters.push({ "id": { "$gt": val } });
224
+ return this;
225
+ }
226
+
227
+ withIdGreaterThanOrEqualTo(val: any): this {
228
+ this.filters.push({ "id": { "$gte": val } });
229
+ return this;
230
+ }
231
+
232
+ withIdLessThan(val: any): this {
233
+ this.filters.push({ "id": { "$lt": val } });
234
+ return this;
235
+ }
236
+
237
+ withIdLessThanOrEqualTo(val: any): this {
238
+ this.filters.push({ "id": { "$lte": val } });
239
+ return this;
240
+ }
241
+
242
+ withIdBetween(lower: any, upper: any): this {
243
+ this.filters.push({ "id": { "$between": [lower, upper] } });
244
+ return this;
245
+ }
246
+
247
+ withIdIsKnown(): this {
248
+ this.filters.push({ "id": { "$isNull": false } });
249
+ return this;
250
+ }
251
+
252
+ withIdIsUnknown(): this {
253
+ this.filters.push({ "id": { "$isNull": true } });
254
+ return this;
255
+ }
256
+
257
+ withNameContaining(val: string): this {
258
+ this.filters.push({ "name": { "$contains": val } });
259
+ return this;
260
+ }
261
+
262
+ withNameIs(val: string): this {
263
+ this.filters.push({ "name": { "$eq": val } });
264
+ return this;
265
+ }
266
+
267
+ withNameIsNot(val: any): this {
268
+ this.filters.push({ "name": { "$ne": val } });
269
+ return this;
270
+ }
271
+
272
+ withNameIn(...vals: any[]): this {
273
+ this.filters.push({ "name": { "$in": vals } });
274
+ return this;
275
+ }
276
+
277
+ withNameNotIn(...vals: any[]): this {
278
+ this.filters.push({ "name": { "$notIn": vals } });
279
+ return this;
280
+ }
281
+
282
+ withNameGreaterThan(val: any): this {
283
+ this.filters.push({ "name": { "$gt": val } });
284
+ return this;
285
+ }
286
+
287
+ withNameGreaterThanOrEqualTo(val: any): this {
288
+ this.filters.push({ "name": { "$gte": val } });
289
+ return this;
290
+ }
291
+
292
+ withNameLessThan(val: any): this {
293
+ this.filters.push({ "name": { "$lt": val } });
294
+ return this;
295
+ }
296
+
297
+ withNameLessThanOrEqualTo(val: any): this {
298
+ this.filters.push({ "name": { "$lte": val } });
299
+ return this;
300
+ }
301
+
302
+ withNameBetween(lower: any, upper: any): this {
303
+ this.filters.push({ "name": { "$between": [lower, upper] } });
304
+ return this;
305
+ }
306
+
307
+ withNameIsKnown(): this {
308
+ this.filters.push({ "name": { "$isNull": false } });
309
+ return this;
310
+ }
311
+
312
+ withNameIsUnknown(): this {
313
+ this.filters.push({ "name": { "$isNull": true } });
314
+ return this;
315
+ }
316
+ withNameNotContaining(val: string): this {
317
+ this.filters.push({ "name": { "$notContains": val } });
318
+ return this;
319
+ }
320
+
321
+ withNameStartingWith(val: string): this {
322
+ this.filters.push({ "name": { "$startsWith": val } });
323
+ return this;
324
+ }
325
+
326
+ withNameNotStartingWith(val: string): this {
327
+ this.filters.push({ "name": { "$notStartsWith": val } });
328
+ return this;
329
+ }
330
+
331
+ withNameEndingWith(val: string): this {
332
+ this.filters.push({ "name": { "$endsWith": val } });
333
+ return this;
334
+ }
335
+
336
+ withNameNotEndingWith(val: string): this {
337
+ this.filters.push({ "name": { "$notEndsWith": val } });
338
+ return this;
339
+ }
340
+
341
+ withNameSoundingLike(val: string): this {
342
+ this.filters.push({ "name": { "$soundLike": val } });
343
+ return this;
344
+ }
345
+
346
+ withVersionIs(val: any): this {
347
+ this.filters.push({ "version": { "$eq": val } });
348
+ return this;
349
+ }
350
+
351
+ withVersionIsNot(val: any): this {
352
+ this.filters.push({ "version": { "$ne": val } });
353
+ return this;
354
+ }
355
+
356
+ withVersionIn(...vals: any[]): this {
357
+ this.filters.push({ "version": { "$in": vals } });
358
+ return this;
359
+ }
360
+
361
+ withVersionNotIn(...vals: any[]): this {
362
+ this.filters.push({ "version": { "$notIn": vals } });
363
+ return this;
364
+ }
365
+
366
+ withVersionGreaterThan(val: any): this {
367
+ this.filters.push({ "version": { "$gt": val } });
368
+ return this;
369
+ }
370
+
371
+ withVersionGreaterThanOrEqualTo(val: any): this {
372
+ this.filters.push({ "version": { "$gte": val } });
373
+ return this;
374
+ }
375
+
376
+ withVersionLessThan(val: any): this {
377
+ this.filters.push({ "version": { "$lt": val } });
378
+ return this;
379
+ }
380
+
381
+ withVersionLessThanOrEqualTo(val: any): this {
382
+ this.filters.push({ "version": { "$lte": val } });
383
+ return this;
384
+ }
385
+
386
+ withVersionBetween(lower: any, upper: any): this {
387
+ this.filters.push({ "version": { "$between": [lower, upper] } });
388
+ return this;
389
+ }
390
+
391
+ withVersionIsKnown(): this {
392
+ this.filters.push({ "version": { "$isNull": false } });
393
+ return this;
394
+ }
395
+
396
+ withVersionIsUnknown(): this {
397
+ this.filters.push({ "version": { "$isNull": true } });
398
+ return this;
399
+ }
400
+
401
+ orderByIdAscending(): this {
402
+ this.query.orderBy("id", "asc");
403
+ return this;
404
+ }
405
+
406
+ orderByIdDescending(): this {
407
+ this.query.orderBy("id", "desc");
408
+ return this;
409
+ }
410
+
411
+ orderByNameAscending(): this {
412
+ this.query.orderBy("name", "asc");
413
+ return this;
414
+ }
415
+
416
+ orderByNameDescending(): this {
417
+ this.query.orderBy("name", "desc");
418
+ return this;
419
+ }
420
+
421
+ orderByVersionAscending(): this {
422
+ this.query.orderBy("version", "asc");
423
+ return this;
424
+ }
425
+
426
+ orderByVersionDescending(): this {
427
+ this.query.orderBy("version", "desc");
428
+ return this;
429
+ }
430
+
431
+
432
+ // --- Aggregations ---
433
+ count(): this {
434
+ this.query.aggregate("Count", "id", "count");
435
+ this._pageCountAlias = "count";
436
+ this._pageCountMethod = "count";
437
+ return this;
438
+ }
439
+
440
+ countAs(retName: string): this {
441
+ this.query.aggregate("Count", "id", retName);
442
+ this._pageCountAlias = retName;
443
+ this._pageCountMethod = "countAs";
444
+ return this;
445
+ }
446
+
447
+
448
+ // --- Group By ---
449
+ groupById(): this {
450
+ this.query.groupBy("id");
451
+ return this;
452
+ }
453
+
454
+ groupByIdAs(retName: string): this {
455
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
456
+ return this;
457
+ }
458
+ groupByName(): this {
459
+ this.query.groupBy("name");
460
+ return this;
461
+ }
462
+
463
+ groupByNameAs(retName: string): this {
464
+ this.query.groupBy("name"); // In TS we don't alias group by yet natively
465
+ return this;
466
+ }
467
+ groupByVersion(): this {
468
+ this.query.groupBy("version");
469
+ return this;
470
+ }
471
+
472
+ groupByVersionAs(retName: string): this {
473
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
474
+ return this;
475
+ }
476
+
477
+ // --- Facets ---
478
+
479
+ private async executeForListInternal(context: UserContext): Promise<SmartList<Catalog>> {
480
+ this.ensureIntent();
481
+ if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows");
482
+ if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context);
483
+ if (this.filters.length > 0) {
484
+ this.query.filter({ "$and": this.filters });
485
+ }
486
+
487
+ const service = context.requireResource<TeaQLDataService>("dataService");
488
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
489
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
490
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
491
+ row instanceof Catalog
492
+ ? row
493
+ : Catalog.fromRecord(row as Record<string, unknown>, new EntityRoot()));
494
+ const result = new SmartList<Catalog>(data);
495
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
496
+
497
+ if (this.query.facets.length > 0) {
498
+ result.facets = await executeRelationFacets(
499
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
500
+ }
501
+
502
+ return result;
503
+ }
504
+
505
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
506
+ this.ensureIntent();
507
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
508
+ const service = context.requireResource<TeaQLDataService>("dataService");
509
+ return new SmartList<Record<string, unknown>>(
510
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
511
+ }
512
+
513
+ private async executeCountedListInternal(
514
+ context: UserContext,
515
+ ): Promise<SmartList<Catalog>> {
516
+ this.ensureIntent();
517
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
518
+ const service = context.requireResource<TeaQLDataService>("dataService");
519
+ const preparedQuery = context.prepareQuery(this.query);
520
+ const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined;
521
+ const countOperation = { kind: "named-count" as const,
522
+ method: this._pageCountMethod ?? "count",
523
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
524
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
525
+ preparedQuery, this._pageCountAlias, countOperation);
526
+ const pageQuery = preparedQuery.clone();
527
+ // A page count describes the full filtered set, not an aggregate-only page row.
528
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
529
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
530
+ const rows = await service.executeQuery(pageQuery);
531
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
532
+ ? context.idSetPaginationCount!
533
+ : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation));
534
+ const aggregateOnly = pageQuery.aggregateItems.length > 0;
535
+ const data = new SmartList<Catalog>(aggregateOnly ? [] : rows.map((row: unknown) =>
536
+ row instanceof Catalog
537
+ ? row
538
+ : Catalog.fromRecord(row as Record<string, unknown>, new EntityRoot())));
539
+ if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]);
540
+ data.totalCount = totalCount;
541
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
542
+ if (this.query.facets.length > 0) {
543
+ data.facets = await executeRelationFacets(
544
+ service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets);
545
+ }
546
+ return data;
547
+ }
548
+
549
+ private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<Catalog> {
550
+ this.ensureIntent();
551
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
552
+ const service = context.requireResource<TeaQLDataService>("dataService");
553
+ const preparedQuery = context.prepareQuery(this.query);
554
+ if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) {
555
+ throw new Error("Entity streams require entity rows; use a record or aggregation query");
556
+ }
557
+ // Prepare Context and capture the runtime request before returning a lazy iterator.
558
+ const chunks = service.executeForStream(preparedQuery, chunkSize);
559
+ return (async function* () {
560
+ for await (const chunk of chunks) {
561
+ for (const entity of chunk) {
562
+ yield entity instanceof Catalog
563
+ ? entity
564
+ : Catalog.fromRecord(entity as Record<string, unknown>, new EntityRoot());
565
+ }
566
+ }
567
+ })();
568
+ }
569
+
570
+ private ensureIntent(): void {
571
+ // Runtime owns validation, Unicode whitespace rules and typed diagnostics.
572
+ new QueryIntent(this._comment, this._purpose);
573
+ }
574
+
575
+ }
576
+
577
+ export class ExecutableCatalogRequest {
578
+ constructor(
579
+ private readonly execute: (context: UserContext) => Promise<SmartList<Catalog>>,
580
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
581
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<Catalog>,
582
+ private readonly limitOne: () => void,
583
+ private readonly addComment: (comment: string) => void,
584
+ private readonly ensureIntent: () => void,
585
+ ) {}
586
+
587
+ comment(c: string): this {
588
+ this.addComment(c);
589
+ return this;
590
+ }
591
+
592
+ newEntity(context: UserContext): Catalog {
593
+ this.ensureIntent();
594
+ return new Catalog();
595
+ }
596
+
597
+ executeForList(context: UserContext): Promise<SmartList<Catalog>> {
598
+ this.ensureIntent();
599
+ return this.execute(context);
600
+ }
601
+
602
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
603
+ this.ensureIntent();
604
+ return this.executeRows(context);
605
+ }
606
+
607
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<Catalog> {
608
+ this.ensureIntent();
609
+ return this.stream(context, chunkSize);
610
+ }
611
+
612
+ async executeForOne(context: UserContext): Promise<Catalog | undefined> {
613
+ this.limitOne();
614
+ return (await this.executeForList(context))[0];
615
+ }
616
+ }
source/teaql-ts/examples/natural-messages/fixture/src/generated/requests/EntryRequest.ts ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts';
2
+ import { Entry } from '../models/Entry';
3
+ import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts';
4
+ import type { Decimal, Long, LocalTime } from 'teaql-ts';
5
+ import { GENERATED_SEARCH_MODELS } from '../../generated-search-models';
6
+
7
+
8
+
9
+ export class EntryRequest {
10
+ private query: SelectQuery;
11
+ private filters: any[] = [];
12
+ private _purpose: string | undefined;
13
+ private _comment: string | undefined;
14
+ private _pageCountAlias: string | undefined;
15
+ private _pageCountMethod: "count" | "countAs" | undefined;
16
+ private _dynamicSearchWarnings: DynamicSearchWarning[] = [];
17
+
18
+ constructor(minimal = false) {
19
+ this.query = new SelectQuery("Entry");
20
+ this.filters.push({ version: { "$gte": 1 } });
21
+ if (minimal) {
22
+ this.selectId();
23
+ this.selectVersion();
24
+ }
25
+ else this.selectSelfFields();
26
+ }
27
+
28
+ comment(c: string): this {
29
+ this.query.comment(c);
30
+ this._comment = c;
31
+ return this;
32
+ }
33
+
34
+ filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this {
35
+ const base = this.query.clone();
36
+ if (this.filters.length > 0) base.filter({ "$and": this.filters });
37
+ const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn);
38
+ this.query = merged.query as SelectQuery;
39
+ this.filters = this.query.filterCondition ? [this.query.filterCondition] : [];
40
+ this._dynamicSearchWarnings.push(...merged.warnings);
41
+ return this;
42
+ }
43
+
44
+ get dynamicSearchWarnings(): readonly DynamicSearchWarning[] {
45
+ return this._dynamicSearchWarnings.map(warning => ({ ...warning }));
46
+ }
47
+
48
+ purpose(p: string): ExecutableEntryRequest {
49
+ this.query.purpose(p);
50
+ this._purpose = p;
51
+ return new ExecutableEntryRequest(
52
+ (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)),
53
+ (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)),
54
+ (context, chunkSize) => this.executeForStreamInternal(context, chunkSize),
55
+ () => this.limit(1),
56
+ (c) => this.comment(c),
57
+ () => this.ensureIntent());
58
+ }
59
+
60
+ optimizeForContinuousPageFetch(): this {
61
+ this.query.optimizeForContinuousPageFetch();
62
+ return this;
63
+ }
64
+
65
+ optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this {
66
+ this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds);
67
+ return this;
68
+ }
69
+
70
+ optimizePaginationWithIdSet(): this {
71
+ this.query.optimizePaginationWithIdSet();
72
+ return this;
73
+ }
74
+
75
+ optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this {
76
+ this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds);
77
+ return this;
78
+ }
79
+
80
+ topNProbeParentThreshold(threshold: number): this {
81
+ this.query.topNProbeParentThreshold(threshold);
82
+ return this;
83
+ }
84
+
85
+ limit(n: number): this {
86
+ this.query.limit(n);
87
+ return this;
88
+ }
89
+
90
+ offset(n: number): this {
91
+ this.query.offset(n);
92
+ return this;
93
+ }
94
+
95
+ toQuery(): SelectQuery {
96
+ if (this.filters.length > 0) {
97
+ this.query.filter({ "$and": this.filters });
98
+ }
99
+ return this.query;
100
+ }
101
+
102
+ withDeletedRows(): this {
103
+ this.query.withDeletedRows();
104
+ this.filters = this.filters.filter(filter => !("version" in filter));
105
+ return this;
106
+ }
107
+
108
+ deletedRowsOnly(): this {
109
+ this.withDeletedRows();
110
+ this.query.deletedRowsOnly();
111
+ this.filters.push({ version: { "$lte": -1 } });
112
+ return this;
113
+ }
114
+
115
+ selectSelfFields(): this {
116
+ this.query.select(["id", "catalog", "name", "bornAt", "touchedAt", "version"]);
117
+ return this;
118
+ }
119
+
120
+ selectId(): this {
121
+ this.query.select(["id"]);
122
+ return this;
123
+ }
124
+
125
+
126
+ selectName(): this {
127
+ this.query.select(["name"]);
128
+ return this;
129
+ }
130
+
131
+ selectBornAt(): this {
132
+ this.query.select(["bornAt"]);
133
+ return this;
134
+ }
135
+
136
+ selectTouchedAt(): this {
137
+ this.query.select(["touchedAt"]);
138
+ return this;
139
+ }
140
+
141
+ selectVersion(): this {
142
+ this.query.select(["version"]);
143
+ return this;
144
+ }
145
+
146
+
147
+ selectCatalogWith(request: { toQuery(): SelectQuery }): this {
148
+ this.query.select(["catalog"]);
149
+ this.query.relationQuery(
150
+ "catalog", request.toQuery(), "catalog", "id", false,
151
+ { kind: "relation-select", method: "selectCatalogWith", relation: "catalog" });
152
+ return this;
153
+ }
154
+
155
+ withCatalogMatching(request: { toQuery(): SelectQuery }): this {
156
+ this.filters.push({
157
+ "catalog": {
158
+ "$inSubquery": { query: request.toQuery(), field: "id" },
159
+ },
160
+ });
161
+ return this;
162
+ }
163
+
164
+ withoutCatalogMatching(request: { toQuery(): SelectQuery }): this {
165
+ this.filters.push({
166
+ "catalog": {
167
+ "$notInSubquery": { query: request.toQuery(), field: "id" },
168
+ },
169
+ });
170
+ return this;
171
+ }
172
+
173
+
174
+
175
+
176
+ withIdIs(val: any): this {
177
+ this.filters.push({ "id": { "$eq": val } });
178
+ return this;
179
+ }
180
+
181
+ withIdIsNot(val: any): this {
182
+ this.filters.push({ "id": { "$ne": val } });
183
+ return this;
184
+ }
185
+
186
+ withIdIn(...vals: any[]): this {
187
+ this.filters.push({ "id": { "$in": vals } });
188
+ return this;
189
+ }
190
+
191
+ withIdNotIn(...vals: any[]): this {
192
+ this.filters.push({ "id": { "$notIn": vals } });
193
+ return this;
194
+ }
195
+
196
+ withIdGreaterThan(val: any): this {
197
+ this.filters.push({ "id": { "$gt": val } });
198
+ return this;
199
+ }
200
+
201
+ withIdGreaterThanOrEqualTo(val: any): this {
202
+ this.filters.push({ "id": { "$gte": val } });
203
+ return this;
204
+ }
205
+
206
+ withIdLessThan(val: any): this {
207
+ this.filters.push({ "id": { "$lt": val } });
208
+ return this;
209
+ }
210
+
211
+ withIdLessThanOrEqualTo(val: any): this {
212
+ this.filters.push({ "id": { "$lte": val } });
213
+ return this;
214
+ }
215
+
216
+ withIdBetween(lower: any, upper: any): this {
217
+ this.filters.push({ "id": { "$between": [lower, upper] } });
218
+ return this;
219
+ }
220
+
221
+ withIdIsKnown(): this {
222
+ this.filters.push({ "id": { "$isNull": false } });
223
+ return this;
224
+ }
225
+
226
+ withIdIsUnknown(): this {
227
+ this.filters.push({ "id": { "$isNull": true } });
228
+ return this;
229
+ }
230
+
231
+ filterByCatalog(val: any): this {
232
+ this.filters.push({ "catalog": { "$eq": val } });
233
+ return this;
234
+ }
235
+
236
+ filterByCatalogIn(...vals: any[]): this {
237
+ this.filters.push({ "catalog": { "$in": vals } });
238
+ return this;
239
+ }
240
+
241
+ withCatalogIsKnown(): this {
242
+ this.filters.push({ "catalog": { "$isNull": false } });
243
+ return this;
244
+ }
245
+
246
+ withCatalogIsUnknown(): this {
247
+ this.filters.push({ "catalog": { "$isNull": true } });
248
+ return this;
249
+ }
250
+
251
+ withNameContaining(val: string): this {
252
+ this.filters.push({ "name": { "$contains": val } });
253
+ return this;
254
+ }
255
+
256
+ withNameIs(val: string): this {
257
+ this.filters.push({ "name": { "$eq": val } });
258
+ return this;
259
+ }
260
+
261
+ withNameIsNot(val: any): this {
262
+ this.filters.push({ "name": { "$ne": val } });
263
+ return this;
264
+ }
265
+
266
+ withNameIn(...vals: any[]): this {
267
+ this.filters.push({ "name": { "$in": vals } });
268
+ return this;
269
+ }
270
+
271
+ withNameNotIn(...vals: any[]): this {
272
+ this.filters.push({ "name": { "$notIn": vals } });
273
+ return this;
274
+ }
275
+
276
+ withNameGreaterThan(val: any): this {
277
+ this.filters.push({ "name": { "$gt": val } });
278
+ return this;
279
+ }
280
+
281
+ withNameGreaterThanOrEqualTo(val: any): this {
282
+ this.filters.push({ "name": { "$gte": val } });
283
+ return this;
284
+ }
285
+
286
+ withNameLessThan(val: any): this {
287
+ this.filters.push({ "name": { "$lt": val } });
288
+ return this;
289
+ }
290
+
291
+ withNameLessThanOrEqualTo(val: any): this {
292
+ this.filters.push({ "name": { "$lte": val } });
293
+ return this;
294
+ }
295
+
296
+ withNameBetween(lower: any, upper: any): this {
297
+ this.filters.push({ "name": { "$between": [lower, upper] } });
298
+ return this;
299
+ }
300
+
301
+ withNameIsKnown(): this {
302
+ this.filters.push({ "name": { "$isNull": false } });
303
+ return this;
304
+ }
305
+
306
+ withNameIsUnknown(): this {
307
+ this.filters.push({ "name": { "$isNull": true } });
308
+ return this;
309
+ }
310
+ withNameNotContaining(val: string): this {
311
+ this.filters.push({ "name": { "$notContains": val } });
312
+ return this;
313
+ }
314
+
315
+ withNameStartingWith(val: string): this {
316
+ this.filters.push({ "name": { "$startsWith": val } });
317
+ return this;
318
+ }
319
+
320
+ withNameNotStartingWith(val: string): this {
321
+ this.filters.push({ "name": { "$notStartsWith": val } });
322
+ return this;
323
+ }
324
+
325
+ withNameEndingWith(val: string): this {
326
+ this.filters.push({ "name": { "$endsWith": val } });
327
+ return this;
328
+ }
329
+
330
+ withNameNotEndingWith(val: string): this {
331
+ this.filters.push({ "name": { "$notEndsWith": val } });
332
+ return this;
333
+ }
334
+
335
+ withNameSoundingLike(val: string): this {
336
+ this.filters.push({ "name": { "$soundLike": val } });
337
+ return this;
338
+ }
339
+
340
+ withBornAtIs(val: any): this {
341
+ this.filters.push({ "bornAt": { "$eq": val } });
342
+ return this;
343
+ }
344
+
345
+ withBornAtIsNot(val: any): this {
346
+ this.filters.push({ "bornAt": { "$ne": val } });
347
+ return this;
348
+ }
349
+
350
+ withBornAtIn(...vals: any[]): this {
351
+ this.filters.push({ "bornAt": { "$in": vals } });
352
+ return this;
353
+ }
354
+
355
+ withBornAtNotIn(...vals: any[]): this {
356
+ this.filters.push({ "bornAt": { "$notIn": vals } });
357
+ return this;
358
+ }
359
+
360
+ withBornAtGreaterThan(val: any): this {
361
+ this.filters.push({ "bornAt": { "$gt": val } });
362
+ return this;
363
+ }
364
+
365
+ withBornAtGreaterThanOrEqualTo(val: any): this {
366
+ this.filters.push({ "bornAt": { "$gte": val } });
367
+ return this;
368
+ }
369
+
370
+ withBornAtLessThan(val: any): this {
371
+ this.filters.push({ "bornAt": { "$lt": val } });
372
+ return this;
373
+ }
374
+
375
+ withBornAtLessThanOrEqualTo(val: any): this {
376
+ this.filters.push({ "bornAt": { "$lte": val } });
377
+ return this;
378
+ }
379
+
380
+ withBornAtBetween(lower: any, upper: any): this {
381
+ this.filters.push({ "bornAt": { "$between": [lower, upper] } });
382
+ return this;
383
+ }
384
+
385
+ withBornAtIsKnown(): this {
386
+ this.filters.push({ "bornAt": { "$isNull": false } });
387
+ return this;
388
+ }
389
+
390
+ withBornAtIsUnknown(): this {
391
+ this.filters.push({ "bornAt": { "$isNull": true } });
392
+ return this;
393
+ }
394
+
395
+ withTouchedAtIs(val: any): this {
396
+ this.filters.push({ "touchedAt": { "$eq": val } });
397
+ return this;
398
+ }
399
+
400
+ withTouchedAtIsNot(val: any): this {
401
+ this.filters.push({ "touchedAt": { "$ne": val } });
402
+ return this;
403
+ }
404
+
405
+ withTouchedAtIn(...vals: any[]): this {
406
+ this.filters.push({ "touchedAt": { "$in": vals } });
407
+ return this;
408
+ }
409
+
410
+ withTouchedAtNotIn(...vals: any[]): this {
411
+ this.filters.push({ "touchedAt": { "$notIn": vals } });
412
+ return this;
413
+ }
414
+
415
+ withTouchedAtGreaterThan(val: any): this {
416
+ this.filters.push({ "touchedAt": { "$gt": val } });
417
+ return this;
418
+ }
419
+
420
+ withTouchedAtGreaterThanOrEqualTo(val: any): this {
421
+ this.filters.push({ "touchedAt": { "$gte": val } });
422
+ return this;
423
+ }
424
+
425
+ withTouchedAtLessThan(val: any): this {
426
+ this.filters.push({ "touchedAt": { "$lt": val } });
427
+ return this;
428
+ }
429
+
430
+ withTouchedAtLessThanOrEqualTo(val: any): this {
431
+ this.filters.push({ "touchedAt": { "$lte": val } });
432
+ return this;
433
+ }
434
+
435
+ withTouchedAtBetween(lower: any, upper: any): this {
436
+ this.filters.push({ "touchedAt": { "$between": [lower, upper] } });
437
+ return this;
438
+ }
439
+
440
+ withTouchedAtIsKnown(): this {
441
+ this.filters.push({ "touchedAt": { "$isNull": false } });
442
+ return this;
443
+ }
444
+
445
+ withTouchedAtIsUnknown(): this {
446
+ this.filters.push({ "touchedAt": { "$isNull": true } });
447
+ return this;
448
+ }
449
+
450
+ withVersionIs(val: any): this {
451
+ this.filters.push({ "version": { "$eq": val } });
452
+ return this;
453
+ }
454
+
455
+ withVersionIsNot(val: any): this {
456
+ this.filters.push({ "version": { "$ne": val } });
457
+ return this;
458
+ }
459
+
460
+ withVersionIn(...vals: any[]): this {
461
+ this.filters.push({ "version": { "$in": vals } });
462
+ return this;
463
+ }
464
+
465
+ withVersionNotIn(...vals: any[]): this {
466
+ this.filters.push({ "version": { "$notIn": vals } });
467
+ return this;
468
+ }
469
+
470
+ withVersionGreaterThan(val: any): this {
471
+ this.filters.push({ "version": { "$gt": val } });
472
+ return this;
473
+ }
474
+
475
+ withVersionGreaterThanOrEqualTo(val: any): this {
476
+ this.filters.push({ "version": { "$gte": val } });
477
+ return this;
478
+ }
479
+
480
+ withVersionLessThan(val: any): this {
481
+ this.filters.push({ "version": { "$lt": val } });
482
+ return this;
483
+ }
484
+
485
+ withVersionLessThanOrEqualTo(val: any): this {
486
+ this.filters.push({ "version": { "$lte": val } });
487
+ return this;
488
+ }
489
+
490
+ withVersionBetween(lower: any, upper: any): this {
491
+ this.filters.push({ "version": { "$between": [lower, upper] } });
492
+ return this;
493
+ }
494
+
495
+ withVersionIsKnown(): this {
496
+ this.filters.push({ "version": { "$isNull": false } });
497
+ return this;
498
+ }
499
+
500
+ withVersionIsUnknown(): this {
501
+ this.filters.push({ "version": { "$isNull": true } });
502
+ return this;
503
+ }
504
+
505
+ orderByIdAscending(): this {
506
+ this.query.orderBy("id", "asc");
507
+ return this;
508
+ }
509
+
510
+ orderByIdDescending(): this {
511
+ this.query.orderBy("id", "desc");
512
+ return this;
513
+ }
514
+
515
+
516
+ orderByNameAscending(): this {
517
+ this.query.orderBy("name", "asc");
518
+ return this;
519
+ }
520
+
521
+ orderByNameDescending(): this {
522
+ this.query.orderBy("name", "desc");
523
+ return this;
524
+ }
525
+
526
+ orderByBornAtAscending(): this {
527
+ this.query.orderBy("bornAt", "asc");
528
+ return this;
529
+ }
530
+
531
+ orderByBornAtDescending(): this {
532
+ this.query.orderBy("bornAt", "desc");
533
+ return this;
534
+ }
535
+
536
+ orderByTouchedAtAscending(): this {
537
+ this.query.orderBy("touchedAt", "asc");
538
+ return this;
539
+ }
540
+
541
+ orderByTouchedAtDescending(): this {
542
+ this.query.orderBy("touchedAt", "desc");
543
+ return this;
544
+ }
545
+
546
+ orderByVersionAscending(): this {
547
+ this.query.orderBy("version", "asc");
548
+ return this;
549
+ }
550
+
551
+ orderByVersionDescending(): this {
552
+ this.query.orderBy("version", "desc");
553
+ return this;
554
+ }
555
+
556
+
557
+ // --- Aggregations ---
558
+ count(): this {
559
+ this.query.aggregate("Count", "id", "count");
560
+ this._pageCountAlias = "count";
561
+ this._pageCountMethod = "count";
562
+ return this;
563
+ }
564
+
565
+ countAs(retName: string): this {
566
+ this.query.aggregate("Count", "id", retName);
567
+ this._pageCountAlias = retName;
568
+ this._pageCountMethod = "countAs";
569
+ return this;
570
+ }
571
+
572
+
573
+ // --- Group By ---
574
+ groupById(): this {
575
+ this.query.groupBy("id");
576
+ return this;
577
+ }
578
+
579
+ groupByIdAs(retName: string): this {
580
+ this.query.groupBy("id"); // In TS we don't alias group by yet natively
581
+ return this;
582
+ }
583
+ groupByCatalog(): this {
584
+ this.query.groupBy("catalog");
585
+ return this;
586
+ }
587
+
588
+ groupByCatalogAs(retName: string): this {
589
+ this.query.groupBy("catalog"); // In TS we don't alias group by yet natively
590
+ return this;
591
+ }
592
+ groupByName(): this {
593
+ this.query.groupBy("name");
594
+ return this;
595
+ }
596
+
597
+ groupByNameAs(retName: string): this {
598
+ this.query.groupBy("name"); // In TS we don't alias group by yet natively
599
+ return this;
600
+ }
601
+ groupByBornAt(): this {
602
+ this.query.groupBy("bornAt");
603
+ return this;
604
+ }
605
+
606
+ groupByBornAtAs(retName: string): this {
607
+ this.query.groupBy("bornAt"); // In TS we don't alias group by yet natively
608
+ return this;
609
+ }
610
+ groupByTouchedAt(): this {
611
+ this.query.groupBy("touchedAt");
612
+ return this;
613
+ }
614
+
615
+ groupByTouchedAtAs(retName: string): this {
616
+ this.query.groupBy("touchedAt"); // In TS we don't alias group by yet natively
617
+ return this;
618
+ }
619
+ groupByVersion(): this {
620
+ this.query.groupBy("version");
621
+ return this;
622
+ }
623
+
624
+ groupByVersionAs(retName: string): this {
625
+ this.query.groupBy("version"); // In TS we don't alias group by yet natively
626
+ return this;
627
+ }
628
+
629
+ // --- Facets ---
630
+ facetByCatalogAs(
631
+ facetName: string,
632
+ request: { toQuery(): SelectQuery },
633
+ includeAllFacets = true,
634
+ ): this {
635
+ this.query.facetBy(facetName, "catalog", request, includeAllFacets,
636
+ { kind: "facet", method: "facetByCatalogAs", relation: "catalog", alias: facetName });
637
+ return this;
638
+ }
639
+
640
+
641
+ private async executeForListInternal(context: UserContext): Promise<SmartList<Entry>> {
642
+ this.ensureIntent();
643
+ if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows");
644
+ if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context);
645
+ if (this.filters.length > 0) {
646
+ this.query.filter({ "$and": this.filters });
647
+ }
648
+
649
+ const service = context.requireResource<TeaQLDataService>("dataService");
650
+ const rows = await service.executeQuery(context.prepareQuery(this.query));
651
+ const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0;
652
+ const data = aggregateOnly ? [] : rows.map((row: unknown) =>
653
+ row instanceof Entry
654
+ ? row
655
+ : Entry.fromRecord(row as Record<string, unknown>, new EntityRoot()));
656
+ const result = new SmartList<Entry>(data);
657
+ if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]);
658
+
659
+ if (this.query.facets.length > 0) {
660
+ result.facets = await executeRelationFacets(
661
+ service, (query: any) => context.prepareQuery(query), this.query, this.query.facets);
662
+ }
663
+
664
+ return result;
665
+ }
666
+
667
+ private async executeForRowsInternal(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
668
+ this.ensureIntent();
669
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
670
+ const service = context.requireResource<TeaQLDataService>("dataService");
671
+ return new SmartList<Record<string, unknown>>(
672
+ await service.executeQuery(context.prepareQuery(this.query)) as Record<string, unknown>[]);
673
+ }
674
+
675
+ private async executeCountedListInternal(
676
+ context: UserContext,
677
+ ): Promise<SmartList<Entry>> {
678
+ this.ensureIntent();
679
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
680
+ const service = context.requireResource<TeaQLDataService>("dataService");
681
+ const preparedQuery = context.prepareQuery(this.query);
682
+ const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined;
683
+ const countOperation = { kind: "named-count" as const,
684
+ method: this._pageCountMethod ?? "count",
685
+ ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) };
686
+ const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount(
687
+ preparedQuery, this._pageCountAlias, countOperation);
688
+ const pageQuery = preparedQuery.clone();
689
+ // A page count describes the full filtered set, not an aggregate-only page row.
690
+ pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item =>
691
+ !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias));
692
+ const rows = await service.executeQuery(pageQuery);
693
+ const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT"
694
+ ? context.idSetPaginationCount!
695
+ : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation));
696
+ const aggregateOnly = pageQuery.aggregateItems.length > 0;
697
+ const data = new SmartList<Entry>(aggregateOnly ? [] : rows.map((row: unknown) =>
698
+ row instanceof Entry
699
+ ? row
700
+ : Entry.fromRecord(row as Record<string, unknown>, new EntityRoot())));
701
+ if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]);
702
+ data.totalCount = totalCount;
703
+ if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount;
704
+ if (this.query.facets.length > 0) {
705
+ data.facets = await executeRelationFacets(
706
+ service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets);
707
+ }
708
+ return data;
709
+ }
710
+
711
+ private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable<Entry> {
712
+ this.ensureIntent();
713
+ if (this.filters.length > 0) this.query.filter({ "$and": this.filters });
714
+ const service = context.requireResource<TeaQLDataService>("dataService");
715
+ const preparedQuery = context.prepareQuery(this.query);
716
+ if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) {
717
+ throw new Error("Entity streams require entity rows; use a record or aggregation query");
718
+ }
719
+ // Prepare Context and capture the runtime request before returning a lazy iterator.
720
+ const chunks = service.executeForStream(preparedQuery, chunkSize);
721
+ return (async function* () {
722
+ for await (const chunk of chunks) {
723
+ for (const entity of chunk) {
724
+ yield entity instanceof Entry
725
+ ? entity
726
+ : Entry.fromRecord(entity as Record<string, unknown>, new EntityRoot());
727
+ }
728
+ }
729
+ })();
730
+ }
731
+
732
+ private ensureIntent(): void {
733
+ // Runtime owns validation, Unicode whitespace rules and typed diagnostics.
734
+ new QueryIntent(this._comment, this._purpose);
735
+ }
736
+
737
+ }
738
+
739
+ export class ExecutableEntryRequest {
740
+ constructor(
741
+ private readonly execute: (context: UserContext) => Promise<SmartList<Entry>>,
742
+ private readonly executeRows: (context: UserContext) => Promise<SmartList<Record<string, unknown>>>,
743
+ private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable<Entry>,
744
+ private readonly limitOne: () => void,
745
+ private readonly addComment: (comment: string) => void,
746
+ private readonly ensureIntent: () => void,
747
+ ) {}
748
+
749
+ comment(c: string): this {
750
+ this.addComment(c);
751
+ return this;
752
+ }
753
+
754
+ newEntity(context: UserContext): Entry {
755
+ this.ensureIntent();
756
+ return new Entry();
757
+ }
758
+
759
+ executeForList(context: UserContext): Promise<SmartList<Entry>> {
760
+ this.ensureIntent();
761
+ return this.execute(context);
762
+ }
763
+
764
+ executeForRows(context: UserContext): Promise<SmartList<Record<string, unknown>>> {
765
+ this.ensureIntent();
766
+ return this.executeRows(context);
767
+ }
768
+
769
+ executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable<Entry> {
770
+ this.ensureIntent();
771
+ return this.stream(context, chunkSize);
772
+ }
773
+
774
+ async executeForOne(context: UserContext): Promise<Entry | undefined> {
775
+ this.limitOne();
776
+ return (await this.executeForList(context))[0];
777
+ }
778
+ }
source/teaql-ts/examples/natural-messages/fixture/src/runtime-module.ts ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts';
2
+ import { ContextFix, ObjectLocation, RuntimeModule } from "teaql-ts";
3
+ import { CheckerPresentationModel } from "teaql-ts";
4
+ import { ENTITY_SCHEMAS } from "./teaql-node-sql";
5
+ import { ensureGeneratedBootstrap } from "./generated-bootstrap";
6
+
7
+ /** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */
8
+ export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({
9
+ profile: "camelCase" as const,
10
+ entities: Object.freeze({
11
+ "Catalog": Object.freeze({
12
+ entityType: "Catalog",
13
+ profile: "camelCase" as const,
14
+ fields: Object.freeze({
15
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
16
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
17
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
18
+ }),
19
+ }),
20
+ "Entry": Object.freeze({
21
+ entityType: "Entry",
22
+ profile: "camelCase" as const,
23
+ fields: Object.freeze({
24
+ "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }),
25
+ "catalog": Object.freeze({ canonicalName: "catalog", wireName: "catalog", aliases: Object.freeze([] as string[]) }),
26
+ "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }),
27
+ "born_at": Object.freeze({ canonicalName: "born_at", wireName: "bornAt", aliases: Object.freeze([] as string[]) }),
28
+ "touched_at": Object.freeze({ canonicalName: "touched_at", wireName: "touchedAt", aliases: Object.freeze([] as string[]) }),
29
+ "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) })
30
+ }),
31
+ })
32
+ }),
33
+ });
34
+
35
+ /** Passive generated metadata manifest. It never modifies the database schema. */
36
+ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, {
37
+ "Catalog": {
38
+ checkAndFix(context, mutation, results) {
39
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
40
+ 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 });
41
+
42
+
43
+ },
44
+ },
45
+ "Entry": {
46
+ checkAndFix(context, mutation, results) {
47
+ if (mutation.action === "Create") {
48
+ ContextFix.apply(context, mutation, "born_at", "now", []);
49
+ }
50
+
51
+ if (mutation.action === "Create") {
52
+ ContextFix.apply(context, mutation, "touched_at", "now", []);
53
+ }
54
+ if (mutation.action === "Update") {
55
+ ContextFix.apply(context, mutation, "touched_at", "now", []);
56
+ }
57
+
58
+
59
+ if ((mutation.action === "Create" && mutation.payload["catalog"] === undefined) || mutation.payload["catalog"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("catalog") });
60
+
61
+ if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") });
62
+ 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 });
63
+
64
+ if ((mutation.action === "Create" && mutation.payload["born_at"] === undefined) || mutation.payload["born_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("born_at") });
65
+
66
+ if ((mutation.action === "Create" && mutation.payload["touched_at"] === undefined) || mutation.payload["touched_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("touched_at") });
67
+
68
+
69
+ },
70
+ }
71
+ }, { ...{
72
+ defaultDomainRoot: { entity: "Catalog", id: "1", values: { "name": "Catalog" } },
73
+ constants: []
74
+ }, 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\"]}]}}}"));
source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sql.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EntitySchema } from "teaql-ts/sql/core";
2
+
3
+ export const ENTITY_SCHEMAS: Record<string, EntitySchema> = {
4
+ "Catalog": {
5
+ table: "catalog_data",
6
+ auditMaskFields: [],
7
+ 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 }},
8
+ relations: {"entryList": { targetEntity: "Entry", localKey: "id", foreignKey: "catalog", many: true }}
9
+ },
10
+ "Entry": {
11
+ table: "entry_data",
12
+ auditMaskFields: ["name"],
13
+ 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 }},
14
+ relations: {"catalog": { targetEntity: "Catalog", localKey: "catalog", foreignKey: "id", many: false }}
15
+ }
16
+ };
source/teaql-ts/examples/natural-messages/fixture/src/teaql-node-sqlite.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ SQLiteDriver,
3
+ SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient
4
+ } from "teaql-ts/sql/sqlite";
5
+ import { GENERATED_RUNTIME_MODULE } from "./runtime-module";
6
+
7
+ export { SQLiteDriver } from "teaql-ts/sql/sqlite";
8
+
9
+ export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient {
10
+ constructor(filename: string) {
11
+ super(filename, {});
12
+ this.install(GENERATED_RUNTIME_MODULE);
13
+ }
14
+ }
source/teaql-ts/examples/natural-messages/fixture/src/teaql-ts.ts ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, ContextFix,
3
+ SelectQuery as RuntimeSelectQuery, UserContext,
4
+ GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout,
5
+ EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout,
6
+ } from "teaql-ts";
7
+ import { CheckerPresentationModel } from "teaql-ts";
8
+ import type { CheckerMessageConfiguration, CheckerValidationOrigin } from "teaql-ts";
9
+
10
+ export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts";
11
+ export { decimal, compareDecimals } from "teaql-ts";
12
+ export type { Decimal } from "teaql-ts";
13
+ export { long, compareLongs, localTime } from "teaql-ts";
14
+ export type { Long, LocalTime } from "teaql-ts";
15
+ export { entityVersion, nextEntityVersion } from "teaql-ts";
16
+ export { integer32Error } from "teaql-ts";
17
+ export type { EntityVersion } from "teaql-ts";
18
+ export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts";
19
+ export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts";
20
+ export type { EntityKey } from "teaql-ts";
21
+ export type { TeaQLPage } from "teaql-ts";
22
+ import type { QueryOperation } from "teaql-ts";
23
+ import type { EntitySchema } from "teaql-ts/sql/core";
24
+
25
+ function soundex(input: unknown): string {
26
+ const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, "");
27
+ if (!text) return "";
28
+ const code = (char: string): string => "BFPV".includes(char) ? "1"
29
+ : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3"
30
+ : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : "";
31
+ let result = text[0], previous = code(text[0]);
32
+ for (const char of text.slice(1)) {
33
+ const current = code(char);
34
+ if (current && current !== previous) result += current;
35
+ previous = current;
36
+ if (result.length === 4) break;
37
+ }
38
+ return (result + "000").slice(0, 4);
39
+ }
40
+
41
+ /** Generated naming adapter; query policy and execution remain in the formal runtime. */
42
+ export class SelectQuery extends RuntimeSelectQuery {
43
+ orderBy(field: string, direction: string): this {
44
+ return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any);
45
+ }
46
+
47
+ relationQuery(
48
+ name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true,
49
+ operation?: QueryOperation,
50
+ ): this {
51
+ return super.relationQuery(name, query, localKey, foreignKey, many, operation);
52
+ }
53
+ }
54
+
55
+ export interface TeaQLDataService {
56
+ executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T>;
57
+ preflightMutation(mutation: any): any;
58
+ afterGraphCommit(work: () => void): void;
59
+ afterGraphRollback(work: () => void): void;
60
+ executeMutation(mutation: any): Promise<any>;
61
+ executeQuery(query: any): Promise<any[]>;
62
+ executeCount(query: any, alias?: string, operation?: QueryOperation): Promise<number>;
63
+ executeForStream(query: any, chunkSize?: number): AsyncIterable<any[]>;
64
+ close?(): Promise<void>;
65
+ }
66
+
67
+ export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService {
68
+ private data: Record<string, Record<string, any>> = {};
69
+ private nextIds: Record<string, number> = {};
70
+ private readonly checkers: Record<string, EntityChecker> = {};
71
+ private readonly schemas: Record<string, EntitySchema> = {};
72
+ private userContext = new UserContext();
73
+ private checkerPresentationModel = CheckerPresentationModel.empty;
74
+ private readonly checkerPrivacyPolicy = (entity: string | undefined, field: string): "masked" | "credential" | undefined => {
75
+ const schema = entity ? this.schemas[entity] : undefined;
76
+ if (!schema) return undefined;
77
+ const native = Object.keys(schema.columns).find(name => name === field
78
+ || schema.columns[name].modelName === field || schema.columns[name].columnName === field) ?? field;
79
+ const column = schema.columns[native];
80
+ const modeled = column?.modelName ?? column?.columnName ?? native;
81
+ if (column?.logPolicy === "credential") return "credential";
82
+ if (column?.logPolicy === "masked" || schema.auditMaskFields?.includes(modeled)
83
+ || schema.auditMaskFields?.includes(native)) return "masked";
84
+ return undefined;
85
+ };
86
+ private graphSaveActive = false;
87
+ private activeGraph?: GraphMutationSession;
88
+ private graphCommitActions: Array<() => void> = [];
89
+ private graphRollbackActions: Array<() => void> = [];
90
+ private graphAuditActions: Array<() => Promise<void>> = [];
91
+ private graphSaveTail: Promise<void> = Promise.resolve();
92
+ private readonly mutationGovernanceEvents: any[] = [];
93
+ private readonly auditEvents: Readonly<Record<string, unknown>>[] = [];
94
+ private auditSink?: (event: Readonly<Record<string, unknown>>) => void | Promise<void>;
95
+
96
+ constructor(private storagePath?: string) {
97
+ super();
98
+ if (storagePath) {
99
+ const fs = require("fs");
100
+ if (fs.existsSync(storagePath)) {
101
+ const state = JSON.parse(fs.readFileSync(storagePath, "utf8"));
102
+ this.data = state.data || {};
103
+ this.nextIds = state.nextIds || {};
104
+ }
105
+ }
106
+ }
107
+
108
+ /** Installs passive generated metadata. It never mutates storage. */
109
+ install(module: RuntimeModule): this {
110
+ const presentation = this.checkerPresentationModel.merge(module.checkerPresentationModel);
111
+ this.installBootstrap(module.bootstrap);
112
+ Object.assign(this.checkers, module.checkers);
113
+ Object.assign(this.schemas, module.schemas);
114
+ this.checkerPresentationModel = presentation;
115
+ return this;
116
+ }
117
+
118
+ protected enterSchemaContext(context: UserContext): () => void {
119
+ const previous = this.userContext;
120
+ this.userContext = context;
121
+ return () => { this.userContext = previous; };
122
+ }
123
+
124
+ protected async ensurePhysicalSchema(_context: UserContext): Promise<void> {
125
+ // JSON/in-memory storage has no physical DDL. The runtime still requires
126
+ // the explicit Context invocation before running generated bootstrap.
127
+ }
128
+
129
+ private storagePayload(entity: string, payload: Record<string, any>): Record<string, any> {
130
+ const values = { ...payload };
131
+ for (const relation of Object.values(this.schemas[entity]?.relations || {})) {
132
+ if (relation.many) continue;
133
+ const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName;
134
+ const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName)
135
+ ? modelName : relation.localKey;
136
+ if (!Object.prototype.hasOwnProperty.call(values, field)) continue;
137
+ const value = values[field];
138
+ if (value === null || value === undefined || typeof value !== "object") continue;
139
+ if (value.id === null || value.id === undefined) {
140
+ throw new Error(`Unresolved relation identity: ${entity}.${field}`);
141
+ }
142
+ values[field] = String(value.id);
143
+ }
144
+ return values;
145
+ }
146
+
147
+ /** Physical/model keys stay canonical; generated entities use native TS members. */
148
+ private runtimeRecord(entity: string, record: Record<string, any>): Record<string, any> {
149
+ const columns = this.schemas[entity]?.columns;
150
+ if (!columns) return { ...record };
151
+ const result: Record<string, any> = {};
152
+ for (const [name, column] of Object.entries(columns)) {
153
+ const key = column.modelName ?? name;
154
+ result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key]
155
+ : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null;
156
+ }
157
+ if (result.version != null) result.version = entityVersion(result.version);
158
+ return result;
159
+ }
160
+
161
+ private checkedMutationVersion(mutation: any): EntityVersion | undefined {
162
+ if (mutation.action === "Create") return undefined;
163
+ if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined;
164
+ const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion);
165
+ if (mutation.version !== undefined && mutation.expectedVersion !== undefined
166
+ && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type");
167
+ nextEntityVersion(mutation.action, version);
168
+ return version;
169
+ }
170
+
171
+ private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any {
172
+ Object.defineProperties(mutation, {
173
+ version: { value: original, enumerable: true, writable: false, configurable: false },
174
+ expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false },
175
+ action: { value: mutation.action, enumerable: true, writable: false, configurable: false },
176
+ });
177
+ return mutation;
178
+ }
179
+
180
+ setUserContext(context: UserContext): this {
181
+ this.userContext = context;
182
+ return this;
183
+ }
184
+
185
+ get mutationGovernanceTrace(): readonly any[] {
186
+ return [...this.mutationGovernanceEvents];
187
+ }
188
+
189
+ get auditTrace(): ReadonlyArray<Readonly<Record<string, unknown>>> { return [...this.auditEvents]; }
190
+ setAuditSink(sink: (event: Readonly<Record<string, unknown>>) => void | Promise<void>): this {
191
+ this.auditSink = sink;
192
+ return this;
193
+ }
194
+
195
+ private persist() {
196
+ if (!this.storagePath) return;
197
+ const fs = require("fs");
198
+ const path = require("path");
199
+ fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true });
200
+ const temporaryPath = `${this.storagePath}.tmp`;
201
+ fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds }));
202
+ fs.renameSync(temporaryPath, this.storagePath);
203
+ }
204
+
205
+ async executeGraphSave<T>(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise<T>, prepare?: (graph: GraphMutationSession) => void | Promise<void>, admit?: (graph: GraphMutationSession) => boolean): Promise<T> {
206
+ const graph = new GraphMutationSession(intent);
207
+ const executionContext = this.userContext;
208
+ graph.bindExecutionReference(() => this.userContext);
209
+ graph.bindExecutionReference(() => this.checkerPresentationModel);
210
+ graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()}));
211
+ for (const name of Object.keys(this.checkers)) {
212
+ graph.bindExecutionReference(() => this.checkers[name]);
213
+ graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix);
214
+ }
215
+ const predecessor = this.graphSaveTail;
216
+ let release!: () => void;
217
+ this.graphSaveTail = new Promise<void>(resolve => { release = resolve; });
218
+ await predecessor;
219
+ const dataSnapshot = JSON.parse(JSON.stringify(this.data));
220
+ const nextIdsSnapshot = { ...this.nextIds };
221
+ let fixEvidenceStarted = false;
222
+ let mutationPolicyGraphStarted = false;
223
+ let committed = false;
224
+ let checkerConfig: CheckerMessageConfiguration | undefined;
225
+ let checkerOrigin: CheckerValidationOrigin | undefined;
226
+ try {
227
+ graph.validatePreparedSources();
228
+ this.graphSaveActive = true;
229
+ this.activeGraph = graph;
230
+ this.graphCommitActions = [];
231
+ this.graphRollbackActions = [];
232
+ this.graphAuditActions = [];
233
+ const pending = admit?.(graph);
234
+ if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED");
235
+ checkerConfig = executionContext.captureCheckerMessages(this.checkerPresentationModel);
236
+ if (graph.preparedRootEntity) checkerOrigin = Object.freeze({model: checkerConfig.model, entity: graph.preparedRootEntity});
237
+ graph.captureInputSources();
238
+ if (pending === false) { graph.sealPreparedGraph(); return await work(graph); }
239
+ executionContext.insertResource("fixTime", executionContext.businessTime());
240
+ executionContext.beginFixEvidence();
241
+ fixEvidenceStarted = true;
242
+ executionContext.beginMutationPolicyGraph();
243
+ mutationPolicyGraphStarted = true;
244
+ await prepare?.(graph);
245
+ if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph();
246
+ executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity);
247
+ graph.validatePreparedSources();
248
+ const result = await work(graph);
249
+ graph.requirePreparedComplete();
250
+ executionContext.ensureMutationPolicyGraphComplete();
251
+ if (!graph.isPreparedEmpty) this.persist();
252
+ committed = true;
253
+ let failure: unknown;
254
+ let failed = false;
255
+ for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) {
256
+ try { await action(); } catch (error) { if (!failed) failure = error; failed = true; }
257
+ }
258
+ if (failed) throw new GraphCommittedError(failure);
259
+ return result;
260
+ } catch (error) {
261
+ if (!committed) {
262
+ this.data = dataSnapshot;
263
+ this.nextIds = nextIdsSnapshot;
264
+ for (const action of [...this.graphRollbackActions].reverse()) {
265
+ try { action(); } catch { /* retain the original failure */ }
266
+ }
267
+ }
268
+ if (error instanceof CheckException && checkerOrigin && checkerConfig) {
269
+ error.refreshPresentation(executionContext.renderCheckerGraphResults(error.violations, checkerConfig, checkerOrigin));
270
+ }
271
+ throw error;
272
+ } finally {
273
+ this.graphSaveActive = false;
274
+ this.activeGraph = undefined;
275
+ this.graphCommitActions = [];
276
+ this.graphRollbackActions = [];
277
+ this.graphAuditActions = [];
278
+ if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph();
279
+ if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence();
280
+ release();
281
+ }
282
+ }
283
+
284
+ afterGraphCommit(work: () => void): void {
285
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
286
+ this.graphCommitActions.push(work);
287
+ }
288
+
289
+ afterGraphRollback(work: () => void): void {
290
+ if (!this.graphSaveActive) throw new Error("No graph save is active");
291
+ this.graphRollbackActions.push(work);
292
+ }
293
+
294
+ preflightMutation(mutation: any): any {
295
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
296
+ mutation = this.checkAndFixMutation(request);
297
+ const normalized = request.graphSession?.normalizePreparedMutation(mutation);
298
+ if (normalized?.restore) {
299
+ this.afterGraphCommit(normalized.restore);
300
+ this.afterGraphRollback(normalized.restore);
301
+ }
302
+ if (normalized?.empty) return mutation;
303
+ request.graphSession?.recordPreparedMutation();
304
+ if (request.graphSession) {
305
+ const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())];
306
+ request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated",
307
+ parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) });
308
+ }
309
+ const schema = this.schemas[mutation.entity];
310
+ const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many)
311
+ .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity]));
312
+ const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation;
313
+ this.userContext.recordMutationPolicyPreflight(policyMutation);
314
+ return mutation;
315
+ }
316
+
317
+ private checkAndFixMutation(mutation: any): any {
318
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
319
+ if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) {
320
+ throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability");
321
+ }
322
+ const prepared = request.graphSession?.replayPreparedMutation(request);
323
+ if (prepared) return prepared;
324
+ mutation = request.mutation;
325
+ const schema = this.schemas[String(mutation.entity)];
326
+ if (schema) {
327
+ const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name));
328
+ fields.validate(mutation.payload ?? {}, mutation.action === "Update");
329
+ if (mutation.ledgerKey && mutation.ledgerRoot) {
330
+ if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");
331
+ fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update");
332
+ }
333
+ }
334
+ const originalVersion = this.checkedMutationVersion(mutation);
335
+ mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } };
336
+ request.bindCheckerLoadedValues(mutation);
337
+ Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true });
338
+ const declaringEntityType = String(mutation.entity);
339
+ const width = new ModeledInteger32Layout(declaringEntityType, schema);
340
+ const checker = this.checkers[declaringEntityType];
341
+ if (!checker) {
342
+ const violations = width.checkMutation(mutation.payload || {});
343
+ if (violations.length) throw new CheckException(violations);
344
+ return this.sealMutationVersion(mutation, originalVersion);
345
+ }
346
+ const results: any[] = [];
347
+ const ownsFixTime = this.userContext.getResource("fixTime") === undefined;
348
+ if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence();
349
+ try {
350
+ ContextFix.run(this.userContext, mutation, schema, () => checker.checkAndFix(this.userContext, mutation, results));
351
+ if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion)
352
+ throw new MutationVersionError("invalid_type");
353
+ width.checkMutation(mutation.payload || {}, results);
354
+ this.userContext.translateCheckResultsFrom(declaringEntityType, results, {
355
+ defaultModel: this.checkerPresentationModel, privacyPolicy: this.checkerPrivacyPolicy,
356
+ checkedValues: [request.loadedValues(), request.mutation.payload ?? {}, mutation.payload ?? {}],
357
+ });
358
+ if (results.length) throw new CheckException(results);
359
+ if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) {
360
+ const undo = ContextFix.captureUndo(mutation, schema);
361
+ if (request.graphSession && undo) this.graphRollbackActions.push(undo);
362
+ for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value);
363
+ }
364
+ return this.sealMutationVersion(mutation, originalVersion);
365
+ } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); }
366
+ }
367
+
368
+ async executeMutation(mutation: any): Promise<any> {
369
+ const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation);
370
+ request.graphSession?.requireMutationAllowed();
371
+ mutation = this.checkAndFixMutation(request);
372
+ const nextVersion = nextEntityVersion(mutation.action, mutation.version);
373
+ const mutationGovernance = this.userContext.enterMutationPolicy(mutation);
374
+ const table = this.data[mutation.entity] ||= {};
375
+ const payload = this.storagePayload(mutation.entity, mutation.payload);
376
+ if (mutation.action === "Create") {
377
+ const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1);
378
+ if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`);
379
+ this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1);
380
+ const record = { ...payload, id: String(id), version: nextVersion };
381
+ table[String(id)] = record;
382
+ if (!this.graphSaveActive) this.persist();
383
+ return this.finishMutation(request, mutation, mutationGovernance,
384
+ { success: true, id: String(id), version: record.version, persistedRecord: { ...record } });
385
+ }
386
+ if (["Update", "Delete", "Recover"].includes(mutation.action)) {
387
+ const id = String(mutation.id);
388
+ if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`);
389
+ const expectedVersion = entityVersion(mutation.version);
390
+ const currentVersion = entityVersion(table[id].version);
391
+ if (expectedVersion !== currentVersion) {
392
+ throw new Error(
393
+ `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`);
394
+ }
395
+ table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion };
396
+ if (!this.graphSaveActive) this.persist();
397
+ return this.finishMutation(request, mutation, mutationGovernance,
398
+ { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } });
399
+ }
400
+ throw new Error(`Unsupported mutation action: ${mutation.action}`);
401
+ }
402
+ private async finishMutation(request: MutationRequest<any>, mutation: any,
403
+ mutationGovernance: unknown, result: any): Promise<any> {
404
+ request.graphSession?.recordPreparedResult(request, result);
405
+ const event = Object.freeze({ entity: mutation.entity, action: mutation.action,
406
+ id: result.id, version: result.version,
407
+ ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload),
408
+ changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()),
409
+ mutationGovernance,
410
+ actor: this.userContext.getResource("bootstrapActor"),
411
+ category: this.userContext.getResource("bootstrapCategory"),
412
+ recordedAt: (this.userContext.getResource<Date>("fixTime") ?? new Date()).toISOString() });
413
+ const publish = async () => {
414
+ this.mutationGovernanceEvents.push(mutationGovernance);
415
+ this.auditEvents.push(event);
416
+ await this.auditSink?.(event);
417
+ };
418
+ if (request.graphSession) this.graphAuditActions.push(publish);
419
+ else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } }
420
+ return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) };
421
+ }
422
+ async query(context: any, req: any): Promise<any> {
423
+ return { rows: [] };
424
+ }
425
+ async executeQuery(query: any): Promise<any> {
426
+ const request = query instanceof QueryRequest ? query : new QueryRequest(query);
427
+ query = request.query;
428
+ if (!(query instanceof RuntimeSelectQuery)) {
429
+ throw new Error("TeaQL list execution requires the formal runtime SelectQuery");
430
+ }
431
+ query.prepareForList();
432
+ const visibility = query.deletionVisibility ?? "live";
433
+ if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY");
434
+ let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row));
435
+ if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row =>
436
+ compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1));
437
+ const matches = (row: any, expression: any): boolean => {
438
+ if (expression?.$and) return expression.$and.every((item: any) => matches(row, item));
439
+ return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => {
440
+ const compare = (value: any): number => field === "version" && value != null && row[field] != null
441
+ ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value)))
442
+ : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1;
443
+ const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value);
444
+ if (predicate?.$eq !== undefined) return equal(predicate.$eq);
445
+ if (predicate?.$ne !== undefined) return !equal(predicate.$ne);
446
+ if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains));
447
+ if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains));
448
+ if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith));
449
+ if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith));
450
+ if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith));
451
+ if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith));
452
+ if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike);
453
+ if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value));
454
+ if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value));
455
+ if (predicate?.$between !== undefined) return field === "version"
456
+ ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0
457
+ : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1];
458
+ if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined;
459
+ if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined;
460
+ if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt;
461
+ if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte;
462
+ if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt;
463
+ if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte;
464
+ return true;
465
+ });
466
+ };
467
+ if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition));
468
+ if (query.aggregateItems?.length) {
469
+ return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => {
470
+ if (String(aggregate.function).toLowerCase() !== "count") {
471
+ throw new Error(`Unsupported local aggregate: ${aggregate.function}`);
472
+ }
473
+ return [aggregate.alias, rows.length];
474
+ }))];
475
+ }
476
+ for (const order of [...query.orderItems].reverse()) {
477
+ rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version))
478
+ : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1));
479
+ }
480
+ const start = query.offsetValue || 0;
481
+ rows = rows.slice(start, start + query.limitValue);
482
+ for (const relation of (query.relations || []) as any[]) {
483
+ for (const row of rows) {
484
+ // Scope before ordering/offset/limit. A nested bound belongs to
485
+ // each parent, not to unrelated children from earlier saves.
486
+ const childQuery = relation.query.clone();
487
+ childQuery.filter({$and: [childQuery.filterCondition ?? {},
488
+ {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]});
489
+ const matches = await this.executeQuery(request.derive(childQuery, relation.name));
490
+ row[relation.name] = relation.many === false ? matches[0] : matches;
491
+ }
492
+ }
493
+ if (query.selectItems.length > 0) {
494
+ const selections = new Set(query.selectItems);
495
+ for (const relation of (query.relations || []) as any[]) selections.add(relation.name);
496
+ rows = rows.map((row: any) => Object.fromEntries(
497
+ Object.entries(row).filter(([field]) => selections.has(field))));
498
+ }
499
+ const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]);
500
+ for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]);
501
+ return rows;
502
+ }
503
+ async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise<number> {
504
+ if (typeof query?.forExactCount !== "function") {
505
+ throw new Error("TeaQL exact count requires the formal runtime SelectQuery");
506
+ }
507
+ const alias = countAlias ?? "__teaql_total";
508
+ const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? {
509
+ kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) });
510
+ const rows = await this.executeQuery(request.query);
511
+ const value = rows[0]?.[alias];
512
+ if (typeof value !== "number" || !Number.isFinite(value)) {
513
+ throw new Error(`TeaQL provider did not return exact count alias ${alias}`);
514
+ }
515
+ return value;
516
+ }
517
+ async *executeForStream(query: any, chunkSize = 1000): AsyncIterable<any[]> {
518
+ query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query;
519
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer");
520
+ const rows = await this.executeQuery(query);
521
+ for (let offset = 0; offset < rows.length; offset += chunkSize) {
522
+ yield rows.slice(offset, offset + chunkSize);
523
+ }
524
+ }
525
+ }
526
+
527
+ declare const require: any;
528
+
529
+ export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; }
530
+ export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; }
source/teaql-ts/examples/natural-messages/fixture/teaql-i18n.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "teaql.i18n/v1",
3
+ "defaultLocale": "en",
4
+ "locales": {
5
+ "de": {
6
+ "vocabulary": {
7
+ },
8
+ "messages": {
9
+ }
10
+ },
11
+ "ko": {
12
+ "vocabulary": {
13
+ },
14
+ "messages": {
15
+ }
16
+ },
17
+ "pt": {
18
+ "vocabulary": {
19
+ },
20
+ "messages": {
21
+ }
22
+ },
23
+ "zh-TW": {
24
+ "vocabulary": {
25
+ },
26
+ "messages": {
27
+ }
28
+ },
29
+ "fil": {
30
+ "vocabulary": {
31
+ },
32
+ "messages": {
33
+ }
34
+ },
35
+ "en": {
36
+ "vocabulary": {
37
+ "entity.catalog": "Catalog",
38
+ "property.entry.name": "Name",
39
+ "property.catalog.id": "Id",
40
+ "property.entry.touchedAt": "Touched At",
41
+ "property.entry.id": "Id",
42
+ "property.catalog.name": "Name",
43
+ "property.catalog.version": "Version",
44
+ "property.entry.version": "Version",
45
+ "entity.entry": "Entry",
46
+ "property.entry.bornAt": "Born At",
47
+ "property.entry.catalog": "Catalog"
48
+ },
49
+ "messages": {
50
+ }
51
+ },
52
+ "fr": {
53
+ "vocabulary": {
54
+ },
55
+ "messages": {
56
+ }
57
+ },
58
+ "zh-CN": {
59
+ "vocabulary": {
60
+ "entity.catalog": "目录",
61
+ "property.entry.name": "名称",
62
+ "property.catalog.name": "名称",
63
+ "entity.entry": "明细",
64
+ "property.entry.catalog": "目录"
65
+ },
66
+ "messages": {
67
+ }
68
+ },
69
+ "es": {
70
+ "vocabulary": {
71
+ },
72
+ "messages": {
73
+ }
74
+ },
75
+ "ar": {
76
+ "vocabulary": {
77
+ },
78
+ "messages": {
79
+ }
80
+ },
81
+ "vi": {
82
+ "vocabulary": {
83
+ },
84
+ "messages": {
85
+ }
86
+ },
87
+ "th": {
88
+ "vocabulary": {
89
+ },
90
+ "messages": {
91
+ }
92
+ },
93
+ "uk": {
94
+ "vocabulary": {
95
+ },
96
+ "messages": {
97
+ }
98
+ },
99
+ "ja": {
100
+ "vocabulary": {
101
+ },
102
+ "messages": {
103
+ }
104
+ },
105
+ "id": {
106
+ "vocabulary": {
107
+ },
108
+ "messages": {
109
+ }
110
+ }
111
+ }
112
+ }
source/teaql-ts/examples/natural-messages/fixture/teaql/checker-model.json ADDED
@@ -0,0 +1 @@
 
 
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"]}]}}}
source/teaql-ts/examples/natural-messages/fixture/teaql/model-provenance.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"schemaVersion":1,"modelUuid":null,"revisionHash":"sha256:86937993c820d848cd5e8e24dcdf3c9152a47c5c518339c4ea6beb2bc22cb8a5","generatorVersion":"unknown"}
source/teaql-ts/examples/natural-messages/fixture/tsconfig.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022",
4
+ "module": "commonjs",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "skipLibCheck": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "declaration": true
10
+ },
11
+ "include": ["src/**/*", "*.d.ts"]
12
+ }
source/teaql-ts/examples/natural-messages/verify.test.ts ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'node:fs';
2
+ import {CheckException, CheckerPresentationModel, UserContext, checkResultToWire,
3
+ standardCheckerMessageRenderer} from '../../src';
4
+ import {Q} from 'natural-generated/generated/Q';
5
+ import {E} from 'natural-generated/generated/E';
6
+ import {SQLiteTeaQLClient} from 'natural-generated/teaql-node-sqlite';
7
+ import {TeaQLClient as FileTeaQLClient} from 'natural-generated/teaql-ts';
8
+ import {GENERATED_RUNTIME_MODULE} from 'natural-generated/runtime-module';
9
+
10
+ // 101 Unicode scalars, 102 UTF-16 units. Actual generated bound is 100 scalars.
11
+ const SECRET='密钥🔑'+'a'.repeat(98);
12
+
13
+ test.each(['sqlite','file'] as const)('generated %s graph uses automatic metadata and protects relocated diagnostics',async provider=>{
14
+ expect(require.resolve('teaql-ts')).toBe(process.env.TEAQL_EXPECTED_RUNTIME_ENTRY);
15
+ const sqlite=process.env.TEAQL_NATURAL_MESSAGES_DB,file=process.env.TEAQL_NATURAL_MESSAGES_FILE;
16
+ if(!sqlite||!file)throw new Error('Use scripts/verify-natural-messages.cjs --example');
17
+ const context=new UserContext().installCheckerMessageWarning(()=>{});
18
+ const client=provider==='sqlite'?new SQLiteTeaQLClient(sqlite).setDiagnosticSQLLogSink(undefined):new FileTeaQLClient(file);
19
+ client.setUserContext(context).install(GENERATED_RUNTIME_MODULE);context.insertResource('dataService',client);
20
+ // The generated module owns descriptors and the actual Checker. There is no
21
+ // manually installed presentation model, custom bounds rule or seed SQL.
22
+ expect(context.checkerPresentationModel).toBe(CheckerPresentationModel.empty);
23
+ expect(GENERATED_RUNTIME_MODULE.checkerPresentationModel).not.toBe(CheckerPresentationModel.empty);
24
+ const responses:unknown[]=[];
25
+ async function rejected(work:()=>Promise<unknown>,expected:string):Promise<void>{
26
+ let failure:unknown;try{await work();}catch(error){failure=error;}
27
+ expect(failure).toBeInstanceOf(CheckException);
28
+ const error=failure as CheckException,response={provider,violations:error.violations.map(result=>checkResultToWire(result))};
29
+ const target=response.violations.find(result=>result.instancePath==='/entryList/1/name');
30
+ expect(target).toBeDefined();expect(target!.entityType).toBe('Entry');expect(target!.message).toBe(expected);
31
+ expect(error.message).toContain(expected);expect(JSON.stringify(response)).not.toContain(SECRET);
32
+ expect(String(error)).not.toContain(SECRET);responses.push(response);
33
+ process.stdout.write('TS_NATURAL_RESPONSE='+JSON.stringify(response)+'\n');
34
+ }
35
+ try{
36
+ await context.ensureSchema();await context.ensureSchema();
37
+ const make=(name:string)=>Q.entries().comment('Prepare an example child')
38
+ .purpose('Verify generated audited mutation and natural errors').newEntity(context).updateName(name).updateCatalog('1');
39
+ let first=make('first'),second=make('second');
40
+ await first.auditAs('Create the first valid child').save(context);
41
+ await second.auditAs('Create the second valid child').save(context);
42
+ const load=async(id:string)=>{
43
+ const rows=await Q.entries().withIdIs(id).limit(1).comment('Reload complete child')
44
+ .purpose('Verify actual stored values through E').executeForList(context);expect(rows).toHaveLength(1);return rows[0];
45
+ };
46
+ first=await load(first.id!);second=await load(second.id!);
47
+ expect(E.entry(second).name().eval()).toBe('second');const secondId=second.id!,version=second.version;
48
+ const parents=await Q.catalogs().withIdIs('1').limit(1).comment('Load unchanged graph owner')
49
+ .purpose('Verify an indexed child failure without editing the parent').executeForList(context);
50
+ const parent=parents[0],parentVersion=parent.version;parent.entryList().push(first,second);
51
+ const execute=jest.spyOn(client,'executeMutation');
52
+ const query=provider==='sqlite'?jest.spyOn((client as any).driver,'query'):undefined;
53
+ const transaction=provider==='sqlite'?jest.spyOn((client as any).driver,'transaction'):undefined;
54
+ const auditBefore=client.auditTrace.length,originalFile=provider==='file'?fs.readFileSync(file):undefined;
55
+ const reset=()=>{execute.mockClear();query?.mockClear();transaction?.mockClear();};
56
+ const unchanged=()=>{
57
+ expect(execute).not.toHaveBeenCalled();if(query)expect(query).not.toHaveBeenCalled();if(transaction)expect(transaction).not.toHaveBeenCalled();
58
+ expect(client.auditTrace).toHaveLength(auditBefore);expect(parent.version).toBe(parentVersion);
59
+ if(originalFile)expect(fs.readFileSync(file)).toEqual(originalFile);
60
+ };
61
+ // The unchanged parent is not a writable view; the first writable child is
62
+ // not the origin. The failure must still identify the second child.
63
+ first.updateName('changed');
64
+ for(const [locale,expected] of [['en','The name of the 2nd entry is required.'],['zh-CN','请填写第2项明细的名称。']] as const){
65
+ context.setLocaleCode(locale);second.updateName(null as unknown as string);reset();
66
+ await rejected(()=>parent.auditAs('Reject the second null child before provider work').save(context),expected);unchanged();
67
+ }
68
+ context.setLocaleCode('en');second.updateName(SECRET);reset();
69
+ await rejected(()=>parent.auditAs('Reject a private scalar-length violation').save(context),
70
+ 'The name of the 2nd entry must not exceed 100 Unicode scalar values; its current length is 101.');unchanged();
71
+ expect(second.name).toBe(SECRET);expect(second.version).toBe(version);
72
+ // Relocation reuses a safe literal from the customer renderer. It must not
73
+ // invoke customer code a second time after the original privacy scope ends.
74
+ let rendererCalls=0;
75
+ context.installCheckerMessageRenderer(request=>{
76
+ rendererCalls++;expect(request.arguments.input).not.toBe(SECRET);expect(request.arguments.input_len).toBe('101');
77
+ return {message:`Custom response ${SECRET}`,warnings:[]};
78
+ });reset();
79
+ await rejected(()=>parent.auditAs('Verify one customer rendering per error').save(context),'Custom response [REDACTED]');
80
+ expect(rendererCalls).toBe(1);unchanged();context.installCheckerMessageRenderer(standardCheckerMessageRenderer);
81
+ first.updateName('first');second.updateName('renamed');
82
+ await parent.auditAs('Persist only the corrected second child').save(context);
83
+ expect(client.auditTrace).toHaveLength(auditBefore+1);expect(parent.version).toBe(parentVersion);
84
+ const stored=await load(secondId);expect(E.entry(stored).name().eval()).toBe('renamed');expect(stored.version).toBe(Number(version)+1);
85
+ expect(context.checkerPresentationModel).toBe(CheckerPresentationModel.empty);
86
+ execute.mockRestore();query?.mockRestore();transaction?.mockRestore();
87
+ process.stdout.write('TS_NATURAL_SQLITE_PASS='+JSON.stringify({passed:true,provider,child:secondId,first:first.id,version:stored.version,
88
+ responses:responses.length,providerCallsOnRejection:0,transactionCallsOnRejection:0,updatedAudits:1,rendererCalls,
89
+ automaticMetadata:true,unchangedParent:true,localSource:require.resolve('teaql-ts')})+'\n');
90
+ }finally{if(client instanceof SQLiteTeaQLClient)await client.close();}
91
+ },30000);
source/teaql-ts/examples/order-management/model.xml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <root name="order-management-service" org="teaql" data_service="sqlite">
3
+ <commerce_platform name="Northwind Demo" create_time="createTime()" update_time="updateTime()"/>
4
+ <customer name="Acme Retail" email="customer@example.com" commerce_platform="commerce_platform()" create_time="createTime()" update_time="updateTime()" _audit_mask_fields="email"/>
5
+ <order_status id="id()" name="string()" code="string()" color="string()?" display_order="number()?" commerce_platform="commerce_platform()" _constant="true" _identifier="code">
6
+ <_value id="1001" name="Pending" code="PENDING" color="#F59E0B" display_order="1" commerce_platform="1"/>
7
+ <_value id="1002" name="Confirmed" code="CONFIRMED" color="#10B981" display_order="2" commerce_platform="1"/>
8
+ </order_status>
9
+ <customer_order order_number="WEB-2026-001" order_date="2026-08-12" total_amount="129.95" status="order_status()" customer="customer()" commerce_platform="commerce_platform()" create_time="createTime()" update_time="updateTime()"/>
10
+ <product name="Tea" sku="TEA-001" image_url="https://example.com/tea.png?" commerce_platform="commerce_platform()" create_time="createTime()" update_time="updateTime()"/>
11
+ <order_line customer_order="customer_order()" product="product()" product_name="Tea" sku="TEA-001" quantity="1" commerce_platform="commerce_platform()" create_time="createTime()"/>
12
+ <order_search_preset name="Pending web orders" filter_json="{}" request_id="quick-start-pending-orders" owner_user_id="operator-1" commerce_platform="commerce_platform()" create_time="createTime()" update_time="updateTime()"/>
13
+ </root>
source/teaql-ts/examples/order-management/package-lock.json CHANGED
@@ -8,11 +8,14 @@
8
  "workspaces": [
9
  "typescript-node-lib-core",
10
  "typescript-app-console"
11
- ]
 
 
 
12
  },
13
  "../..": {
14
  "name": "@teaql/teaql",
15
- "version": "0.3.1",
16
  "license": "Apache-2.0",
17
  "dependencies": {
18
  "node-fetch": "^2.7.0"
@@ -36,7 +39,7 @@
36
  "@types/jest": "^29.5.0",
37
  "@types/node-fetch": "^2.6.13",
38
  "@types/pg": "^8.11.0",
39
- "better-sqlite3": "^12.10.0",
40
  "esbuild": "^0.28.2",
41
  "jest": "^29.5.0",
42
  "jest-util": "^29.7.0",
@@ -63,7 +66,7 @@
63
  "@opentelemetry/sdk-metrics": "^2.10.0",
64
  "@opentelemetry/sdk-trace-base": "^2.10.0",
65
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
66
- "better-sqlite3": "^12.10.0",
67
  "expo-sqlite": "*",
68
  "mysql2": "^3.11.0",
69
  "pg": "^8.12.0",
@@ -242,126 +245,25 @@
242
  "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
243
  "license": "MIT"
244
  },
245
- "node_modules/base64-js": {
246
- "version": "1.5.1",
247
- "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
248
- "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
249
- "funding": [
250
- {
251
- "type": "github",
252
- "url": "https://github.com/sponsors/feross"
253
- },
254
- {
255
- "type": "patreon",
256
- "url": "https://www.patreon.com/feross"
257
- },
258
- {
259
- "type": "consulting",
260
- "url": "https://feross.org/support"
261
- }
262
- ],
263
- "license": "MIT"
264
- },
265
  "node_modules/better-sqlite3": {
266
- "version": "11.10.0",
267
- "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
268
- "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
269
  "hasInstallScript": true,
270
  "license": "MIT",
271
  "dependencies": {
272
- "bindings": "^1.5.0",
273
- "prebuild-install": "^7.1.1"
274
- }
275
- },
276
- "node_modules/bindings": {
277
- "version": "1.5.0",
278
- "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
279
- "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
280
- "license": "MIT",
281
- "dependencies": {
282
- "file-uri-to-path": "1.0.0"
283
- }
284
- },
285
- "node_modules/bl": {
286
- "version": "4.1.0",
287
- "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
288
- "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
289
- "license": "MIT",
290
- "dependencies": {
291
- "buffer": "^5.5.0",
292
- "inherits": "^2.0.4",
293
- "readable-stream": "^3.4.0"
294
- }
295
- },
296
- "node_modules/buffer": {
297
- "version": "5.7.1",
298
- "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
299
- "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
300
- "funding": [
301
- {
302
- "type": "github",
303
- "url": "https://github.com/sponsors/feross"
304
- },
305
- {
306
- "type": "patreon",
307
- "url": "https://www.patreon.com/feross"
308
- },
309
- {
310
- "type": "consulting",
311
- "url": "https://feross.org/support"
312
- }
313
- ],
314
- "license": "MIT",
315
- "dependencies": {
316
- "base64-js": "^1.3.1",
317
- "ieee754": "^1.1.13"
318
  }
319
  },
320
- "node_modules/chownr": {
321
- "version": "1.1.4",
322
- "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
323
- "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
324
- "license": "ISC"
325
- },
326
  "node_modules/create-require": {
327
  "version": "1.1.1",
328
  "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
329
  "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
330
  "license": "MIT"
331
  },
332
- "node_modules/decompress-response": {
333
- "version": "6.0.0",
334
- "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
335
- "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
336
- "license": "MIT",
337
- "dependencies": {
338
- "mimic-response": "^3.1.0"
339
- },
340
- "engines": {
341
- "node": ">=10"
342
- },
343
- "funding": {
344
- "url": "https://github.com/sponsors/sindresorhus"
345
- }
346
- },
347
- "node_modules/deep-extend": {
348
- "version": "0.6.0",
349
- "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
350
- "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
351
- "license": "MIT",
352
- "engines": {
353
- "node": ">=4.0.0"
354
- }
355
- },
356
- "node_modules/detect-libc": {
357
- "version": "2.1.2",
358
- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
359
- "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
360
- "license": "Apache-2.0",
361
- "engines": {
362
- "node": ">=8"
363
- }
364
- },
365
  "node_modules/diff": {
366
  "version": "4.0.4",
367
  "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",
@@ -371,132 +273,19 @@
371
  "node": ">=0.3.1"
372
  }
373
  },
374
- "node_modules/end-of-stream": {
375
- "version": "1.4.5",
376
- "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
377
- "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
378
- "license": "MIT",
379
- "dependencies": {
380
- "once": "^1.4.0"
381
- }
382
- },
383
- "node_modules/expand-template": {
384
- "version": "2.0.3",
385
- "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
386
- "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
387
- "license": "(MIT OR WTFPL)",
388
- "engines": {
389
- "node": ">=6"
390
- }
391
- },
392
- "node_modules/file-uri-to-path": {
393
- "version": "1.0.0",
394
- "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
395
- "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
396
- "license": "MIT"
397
- },
398
- "node_modules/fs-constants": {
399
- "version": "1.0.0",
400
- "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
401
- "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
402
- "license": "MIT"
403
- },
404
- "node_modules/github-from-package": {
405
- "version": "0.0.0",
406
- "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
407
- "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
408
- "license": "MIT"
409
- },
410
- "node_modules/ieee754": {
411
- "version": "1.2.1",
412
- "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
413
- "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
414
- "funding": [
415
- {
416
- "type": "github",
417
- "url": "https://github.com/sponsors/feross"
418
- },
419
- {
420
- "type": "patreon",
421
- "url": "https://www.patreon.com/feross"
422
- },
423
- {
424
- "type": "consulting",
425
- "url": "https://feross.org/support"
426
- }
427
- ],
428
- "license": "BSD-3-Clause"
429
- },
430
- "node_modules/inherits": {
431
- "version": "2.0.4",
432
- "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
433
- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
434
- "license": "ISC"
435
- },
436
- "node_modules/ini": {
437
- "version": "1.3.8",
438
- "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
439
- "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
440
- "license": "ISC"
441
- },
442
  "node_modules/make-error": {
443
  "version": "1.3.6",
444
  "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
445
  "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
446
  "license": "ISC"
447
  },
448
- "node_modules/mimic-response": {
449
- "version": "3.1.0",
450
- "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
451
- "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
452
- "license": "MIT",
453
- "engines": {
454
- "node": ">=10"
455
- },
456
- "funding": {
457
- "url": "https://github.com/sponsors/sindresorhus"
458
- }
459
- },
460
- "node_modules/minimist": {
461
- "version": "1.2.8",
462
- "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
463
- "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
464
- "license": "MIT",
465
- "funding": {
466
- "url": "https://github.com/sponsors/ljharb"
467
- }
468
- },
469
- "node_modules/mkdirp-classic": {
470
- "version": "0.5.3",
471
- "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
472
- "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
473
- "license": "MIT"
474
- },
475
- "node_modules/napi-build-utils": {
476
- "version": "2.0.0",
477
- "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
478
- "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
479
- "license": "MIT"
480
- },
481
- "node_modules/node-abi": {
482
- "version": "3.94.0",
483
- "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",
484
- "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",
485
  "license": "MIT",
486
- "dependencies": {
487
- "semver": "^7.3.5"
488
- },
489
  "engines": {
490
- "node": ">=10"
491
- }
492
- },
493
- "node_modules/once": {
494
- "version": "1.4.0",
495
- "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
496
- "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
497
- "license": "ISC",
498
- "dependencies": {
499
- "wrappy": "1"
500
  }
501
  },
502
  "node_modules/order-management-example": {
@@ -507,195 +296,6 @@
507
  "resolved": "typescript-node-lib-core",
508
  "link": true
509
  },
510
- "node_modules/prebuild-install": {
511
- "version": "7.1.3",
512
- "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
513
- "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
514
- "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
515
- "license": "MIT",
516
- "dependencies": {
517
- "detect-libc": "^2.0.0",
518
- "expand-template": "^2.0.3",
519
- "github-from-package": "0.0.0",
520
- "minimist": "^1.2.3",
521
- "mkdirp-classic": "^0.5.3",
522
- "napi-build-utils": "^2.0.0",
523
- "node-abi": "^3.3.0",
524
- "pump": "^3.0.0",
525
- "rc": "^1.2.7",
526
- "simple-get": "^4.0.0",
527
- "tar-fs": "^2.0.0",
528
- "tunnel-agent": "^0.6.0"
529
- },
530
- "bin": {
531
- "prebuild-install": "bin.js"
532
- },
533
- "engines": {
534
- "node": ">=10"
535
- }
536
- },
537
- "node_modules/pump": {
538
- "version": "3.0.4",
539
- "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
540
- "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
541
- "license": "MIT",
542
- "dependencies": {
543
- "end-of-stream": "^1.1.0",
544
- "once": "^1.3.1"
545
- }
546
- },
547
- "node_modules/rc": {
548
- "version": "1.2.8",
549
- "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
550
- "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
551
- "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
552
- "dependencies": {
553
- "deep-extend": "^0.6.0",
554
- "ini": "~1.3.0",
555
- "minimist": "^1.2.0",
556
- "strip-json-comments": "~2.0.1"
557
- },
558
- "bin": {
559
- "rc": "cli.js"
560
- }
561
- },
562
- "node_modules/readable-stream": {
563
- "version": "3.6.2",
564
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
565
- "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
566
- "license": "MIT",
567
- "dependencies": {
568
- "inherits": "^2.0.3",
569
- "string_decoder": "^1.1.1",
570
- "util-deprecate": "^1.0.1"
571
- },
572
- "engines": {
573
- "node": ">= 6"
574
- }
575
- },
576
- "node_modules/safe-buffer": {
577
- "version": "5.2.1",
578
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
579
- "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
580
- "funding": [
581
- {
582
- "type": "github",
583
- "url": "https://github.com/sponsors/feross"
584
- },
585
- {
586
- "type": "patreon",
587
- "url": "https://www.patreon.com/feross"
588
- },
589
- {
590
- "type": "consulting",
591
- "url": "https://feross.org/support"
592
- }
593
- ],
594
- "license": "MIT"
595
- },
596
- "node_modules/semver": {
597
- "version": "7.8.5",
598
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
599
- "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
600
- "license": "ISC",
601
- "bin": {
602
- "semver": "bin/semver.js"
603
- },
604
- "engines": {
605
- "node": ">=10"
606
- }
607
- },
608
- "node_modules/simple-concat": {
609
- "version": "1.0.1",
610
- "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
611
- "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
612
- "funding": [
613
- {
614
- "type": "github",
615
- "url": "https://github.com/sponsors/feross"
616
- },
617
- {
618
- "type": "patreon",
619
- "url": "https://www.patreon.com/feross"
620
- },
621
- {
622
- "type": "consulting",
623
- "url": "https://feross.org/support"
624
- }
625
- ],
626
- "license": "MIT"
627
- },
628
- "node_modules/simple-get": {
629
- "version": "4.0.1",
630
- "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
631
- "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
632
- "funding": [
633
- {
634
- "type": "github",
635
- "url": "https://github.com/sponsors/feross"
636
- },
637
- {
638
- "type": "patreon",
639
- "url": "https://www.patreon.com/feross"
640
- },
641
- {
642
- "type": "consulting",
643
- "url": "https://feross.org/support"
644
- }
645
- ],
646
- "license": "MIT",
647
- "dependencies": {
648
- "decompress-response": "^6.0.0",
649
- "once": "^1.3.1",
650
- "simple-concat": "^1.0.0"
651
- }
652
- },
653
- "node_modules/string_decoder": {
654
- "version": "1.3.0",
655
- "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
656
- "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
657
- "license": "MIT",
658
- "dependencies": {
659
- "safe-buffer": "~5.2.0"
660
- }
661
- },
662
- "node_modules/strip-json-comments": {
663
- "version": "2.0.1",
664
- "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
665
- "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
666
- "license": "MIT",
667
- "engines": {
668
- "node": ">=0.10.0"
669
- }
670
- },
671
- "node_modules/tar-fs": {
672
- "version": "2.1.5",
673
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
674
- "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
675
- "license": "MIT",
676
- "dependencies": {
677
- "chownr": "^1.1.1",
678
- "mkdirp-classic": "^0.5.2",
679
- "pump": "^3.0.0",
680
- "tar-stream": "^2.1.4"
681
- }
682
- },
683
- "node_modules/tar-stream": {
684
- "version": "2.2.0",
685
- "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
686
- "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
687
- "license": "MIT",
688
- "dependencies": {
689
- "bl": "^4.0.3",
690
- "end-of-stream": "^1.4.1",
691
- "fs-constants": "^1.0.0",
692
- "inherits": "^2.0.3",
693
- "readable-stream": "^3.1.1"
694
- },
695
- "engines": {
696
- "node": ">=6"
697
- }
698
- },
699
  "node_modules/ts-node": {
700
  "version": "10.9.2",
701
  "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
@@ -739,18 +339,6 @@
739
  }
740
  }
741
  },
742
- "node_modules/tunnel-agent": {
743
- "version": "0.6.0",
744
- "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
745
- "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
746
- "license": "Apache-2.0",
747
- "dependencies": {
748
- "safe-buffer": "^5.0.1"
749
- },
750
- "engines": {
751
- "node": "*"
752
- }
753
- },
754
  "node_modules/typescript": {
755
  "version": "5.9.3",
756
  "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -770,24 +358,12 @@
770
  "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
771
  "license": "MIT"
772
  },
773
- "node_modules/util-deprecate": {
774
- "version": "1.0.2",
775
- "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
776
- "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
777
- "license": "MIT"
778
- },
779
  "node_modules/v8-compile-cache-lib": {
780
  "version": "3.0.1",
781
  "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
782
  "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
783
  "license": "MIT"
784
  },
785
- "node_modules/wrappy": {
786
- "version": "1.0.2",
787
- "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
788
- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
789
- "license": "ISC"
790
- },
791
  "node_modules/yn": {
792
  "version": "3.1.1",
793
  "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
@@ -818,7 +394,7 @@
818
  "name": "order-management-service-lib",
819
  "version": "1.0.0",
820
  "dependencies": {
821
- "better-sqlite3": "^11.7.0",
822
  "teaql-ts": "file:../../.."
823
  },
824
  "devDependencies": {
@@ -826,6 +402,9 @@
826
  "@types/node": "^22.0.0",
827
  "ts-node": "^10.9.2",
828
  "typescript": "^5.0.0"
 
 
 
829
  }
830
  },
831
  "typescript-node-lib-core/node_modules/teaql-ts": {
 
8
  "workspaces": [
9
  "typescript-node-lib-core",
10
  "typescript-app-console"
11
+ ],
12
+ "engines": {
13
+ "node": ">=22"
14
+ }
15
  },
16
  "../..": {
17
  "name": "@teaql/teaql",
18
+ "version": "0.5.0",
19
  "license": "Apache-2.0",
20
  "dependencies": {
21
  "node-fetch": "^2.7.0"
 
39
  "@types/jest": "^29.5.0",
40
  "@types/node-fetch": "^2.6.13",
41
  "@types/pg": "^8.11.0",
42
+ "better-sqlite3": "^13.0.3",
43
  "esbuild": "^0.28.2",
44
  "jest": "^29.5.0",
45
  "jest-util": "^29.7.0",
 
66
  "@opentelemetry/sdk-metrics": "^2.10.0",
67
  "@opentelemetry/sdk-trace-base": "^2.10.0",
68
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
69
+ "better-sqlite3": "^13.0.3",
70
  "expo-sqlite": "*",
71
  "mysql2": "^3.11.0",
72
  "pg": "^8.12.0",
 
245
  "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
246
  "license": "MIT"
247
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  "node_modules/better-sqlite3": {
249
+ "version": "13.0.3",
250
+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz",
251
+ "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==",
252
  "hasInstallScript": true,
253
  "license": "MIT",
254
  "dependencies": {
255
+ "node-addon-api": "^8.0.0"
256
+ },
257
+ "engines": {
258
+ "node": ">=22"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  }
260
  },
 
 
 
 
 
 
261
  "node_modules/create-require": {
262
  "version": "1.1.1",
263
  "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
264
  "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
265
  "license": "MIT"
266
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  "node_modules/diff": {
268
  "version": "4.0.4",
269
  "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",
 
273
  "node": ">=0.3.1"
274
  }
275
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  "node_modules/make-error": {
277
  "version": "1.3.6",
278
  "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
279
  "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
280
  "license": "ISC"
281
  },
282
+ "node_modules/node-addon-api": {
283
+ "version": "8.9.2",
284
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
285
+ "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  "license": "MIT",
 
 
 
287
  "engines": {
288
+ "node": "^18 || ^20 || >= 21"
 
 
 
 
 
 
 
 
 
289
  }
290
  },
291
  "node_modules/order-management-example": {
 
296
  "resolved": "typescript-node-lib-core",
297
  "link": true
298
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  "node_modules/ts-node": {
300
  "version": "10.9.2",
301
  "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
 
339
  }
340
  }
341
  },
 
 
 
 
 
 
 
 
 
 
 
 
342
  "node_modules/typescript": {
343
  "version": "5.9.3",
344
  "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
 
358
  "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
359
  "license": "MIT"
360
  },
 
 
 
 
 
 
361
  "node_modules/v8-compile-cache-lib": {
362
  "version": "3.0.1",
363
  "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
364
  "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
365
  "license": "MIT"
366
  },
 
 
 
 
 
 
367
  "node_modules/yn": {
368
  "version": "3.1.1",
369
  "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
 
394
  "name": "order-management-service-lib",
395
  "version": "1.0.0",
396
  "dependencies": {
397
+ "better-sqlite3": "^13.0.3",
398
  "teaql-ts": "file:../../.."
399
  },
400
  "devDependencies": {
 
402
  "@types/node": "^22.0.0",
403
  "ts-node": "^10.9.2",
404
  "typescript": "^5.0.0"
405
+ },
406
+ "engines": {
407
+ "node": ">=22"
408
  }
409
  },
410
  "typescript-node-lib-core/node_modules/teaql-ts": {
source/teaql-ts/examples/order-management/package.json CHANGED
@@ -1,10 +1,14 @@
1
  {
2
  "name": "teaql-order-management-example",
3
  "private": true,
 
4
  "workspaces": [
5
  "typescript-node-lib-core",
6
  "typescript-app-console"
7
  ],
 
 
 
8
  "scripts": {
9
  "build": "npm run build --workspace order-management-example",
10
  "start": "npm start --workspace order-management-example"
 
1
  {
2
  "name": "teaql-order-management-example",
3
  "private": true,
4
+ "engines": { "node": ">=22" },
5
  "workspaces": [
6
  "typescript-node-lib-core",
7
  "typescript-app-console"
8
  ],
9
+ "overrides": {
10
+ "better-sqlite3": "^13.0.3"
11
+ },
12
  "scripts": {
13
  "build": "npm run build --workspace order-management-example",
14
  "start": "npm start --workspace order-management-example"