diff --git a/generator/src/main/resources/generator/dotnet-lib-core/model/index.stg b/generator/src/main/resources/generator/dotnet-lib-core/model/index.stg index 24df23f3..c02e96c1 100644 --- a/generator/src/main/resources/generator/dotnet-lib-core/model/index.stg +++ b/generator/src/main/resources/generator/dotnet-lib-core/model/index.stg @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using TeaQL.Core; +using TeaQL.Runtime; namespace Generated.Models { @@ -109,18 +110,18 @@ namespace Generated.Models public async Task\<\> SaveAsync(UserContext context) { - return await context.ExecuteGraphSaveAsync(async () => + return await context.ExecuteGraphSaveAsync(_comment!, async session => { if (!Id.HasValue || _teaqlForceCreate) { } - TeaqlPreflightGraph(context); - return await TeaqlSaveWithinGraphAsync(context); + TeaqlPreflightGraph(context, session); + return await TeaqlSaveWithinGraphAsync(context, session); }); } - internal void TeaqlPreflightGraph(UserContext context) + internal void TeaqlPreflightGraph(UserContext context, GraphMutationSession session) { if (string.IsNullOrWhiteSpace(_comment)) throw new Exception("Security audit failure: AuditAs() must be called before SaveAsync()"); @@ -136,11 +137,11 @@ namespace Generated.Models ((UpdateCommand)command).Values = _entityRoot.Change(TeaqlEntityKey()); if (Version.HasValue) ((UpdateCommand)command).Values["version"] = new Value.I64Value(Version.Value); } - context.PreflightMutation(TeaqlMutationRequest(command)); + session.Preflight(TeaqlMutationRequest(command)); } - internal async Task\<\> TeaqlSaveWithinGraphAsync(UserContext context) + internal async Task\<\> TeaqlSaveWithinGraphAsync(UserContext context, GraphMutationSession session) { var teaqlOriginalKey = TeaqlEntityKey(); var teaqlOriginalLedgerId = _ledgerId; @@ -149,7 +150,7 @@ namespace Generated.Models var teaqlOriginalFullyLoaded = _fullyLoaded; var teaqlOriginalLoadedFields = new HashSet\(_loadedFields, StringComparer.OrdinalIgnoreCase); - context.AfterGraphRollback(() => + session.AfterRollback(() => { var currentKey = TeaqlEntityKey(); @@ -160,10 +161,10 @@ namespace Generated.Models _loadedFields = teaqlOriginalLoadedFields; _entityRoot.Rekey(currentKey, teaqlOriginalKey); }); - context.AfterGraphCommit(() => + session.AfterCommit(() => { _entityRoot.ClearEntity(TeaqlEntityKey()); - if (Version.HasValue) _entityRoot.SetOriginalVersion(TeaqlEntityKey(), Version.Value); + if (Version.HasValue) _entityRoot.AcceptCommittedVersion(TeaqlEntityKey(), Version.Value); }); if (string.IsNullOrWhiteSpace(_comment)) { @@ -180,7 +181,7 @@ namespace Generated.Models if (Version.HasValue) ((UpdateCommand)cmd).Values["version"] = new Value.I64Value(Version.Value); } var req = TeaqlMutationRequest(cmd); - var mutationResult = await context.RequireResource\().MutateAsync(req); + var mutationResult = await session.MutateAsync(req); if (mutationResult.PersistedRecord == null) throw new InvalidOperationException("Mutation provider did not return authoritative persisted state for "); var saved = FromRecord(mutationResult.PersistedRecord); @@ -307,7 +308,7 @@ for (var index = 0; index \< .Count; index++) child.AttachRoot(_entityRoot); child.UpdateId(Id); child.AuditAs(_comment!); - try { await child.TeaqlSaveWithinGraphAsync(context); } + try { await child.TeaqlSaveWithinGraphAsync(context, session); } catch (CheckException error) { var prefix = ObjectLocation.Property("").Index(index); @@ -324,7 +325,7 @@ for (var index = 0; index \< .Count; index++) child.AttachRoot(_entityRoot); child.UpdateId(Id ?? _ledgerId); child.AuditAs(_comment!); - try { child.TeaqlPreflightGraph(context); } + try { child.TeaqlPreflightGraph(context, session); } catch (CheckException error) { var prefix = ObjectLocation.Property("").Index(index); diff --git a/generator/src/main/resources/generator/golang-lib-core/entity/struct.go.stg b/generator/src/main/resources/generator/golang-lib-core/entity/struct.go.stg index dfddced9..cc3bf9f8 100644 --- a/generator/src/main/resources/generator/golang-lib-core/entity/struct.go.stg +++ b/generator/src/main/resources/generator/golang-lib-core/entity/struct.go.stg @@ -219,7 +219,9 @@ func (e *) IntoJson() any { func (e *) Save(context *runtime.UserContext) (*, error) { var saved * - err := context.ExecutePreparedGraphSave(func() (*runtime.MutationPlan, error) { + intent, err := core.NewMutationIntent(e.comment) + if err != nil { return nil, err } + err = context.ExecutePreparedGraphSave(intent, func() (*runtime.MutationPlan, error) { if preflightErr := e.TeaqlPreflightGraph(context); preflightErr != nil { return nil, preflightErr } auditReason := "" if e.comment != nil { auditReason = *e.comment } @@ -360,7 +362,9 @@ func (e *) TeaqlSaveWithinGraph(context *runt if e.comment != nil { cmd.TraceChain = append(cmd.TraceChain, &core.TraceNode{Comment: *e.comment}) } - res, err := ds.Mutate(context, &data_service.InsertMutation{Cmd: cmd}) + request, err := data_service.NewMutationRequest(&data_service.InsertMutation{Cmd: cmd}, *e.comment) + if err != nil { return nil, err } + res, err := ds.Mutate(context, request) if err == nil { e.isNew = false e.dirtyFields = make(map[string]bool) @@ -392,7 +396,9 @@ func (e *) TeaqlSaveWithinGraph(context *runt if e.comment != nil { cmd.TraceChain = append(cmd.TraceChain, &core.TraceNode{Comment: *e.comment}) } - res, err := ds.Mutate(context, &data_service.DeleteMutation{Cmd: cmd}) + request, err := data_service.NewMutationRequest(&data_service.DeleteMutation{Cmd: cmd}, *e.comment) + if err != nil { return nil, err } + res, err := ds.Mutate(context, request) if err != nil { return nil, err } if res.AffectedRows == 0 { return nil, fmt.Errorf("optimistic lock failed for %s(%d) at version %d", e.EntityName(), e.base.Id, expectedVersion) @@ -423,7 +429,9 @@ func (e *) TeaqlSaveWithinGraph(context *runt if e.comment != nil { cmd.TraceChain = append(cmd.TraceChain, &core.TraceNode{Comment: *e.comment}) } - res, err := ds.Mutate(context, &data_service.UpdateMutation{Cmd: cmd}) + request, err := data_service.NewMutationRequest(&data_service.UpdateMutation{Cmd: cmd}, *e.comment) + if err != nil { return nil, err } + res, err := ds.Mutate(context, request) if err == nil { if res.AffectedRows == 0 { return nil, fmt.Errorf("optimistic lock failed for %s(%d) at version %d", e.EntityName(), e.base.Id, expectedVersion) diff --git a/generator/src/main/resources/generator/python-lib-core/model/index.stg b/generator/src/main/resources/generator/python-lib-core/model/index.stg index 8e15e90c..780d09a5 100644 --- a/generator/src/main/resources/generator/python-lib-core/model/index.stg +++ b/generator/src/main/resources/generator/python-lib-core/model/index.stg @@ -92,7 +92,7 @@ class : # reviewed graph plan and in the commands eventually sent to SQL. await self._teaql_reserve_graph_ids(context, set()) await self._teaql_ensure_business_ids(context) - return await context.execute_graph_save(lambda: self._teaql_preflight_and_save(context)) + return await context.execute_graph_save(lambda graph: self._teaql_preflight_and_save(graph), comment=self._comment) async def _teaql_ensure_business_ids(self, context): if self._action != "Create": @@ -120,9 +120,10 @@ class : self._entity_root.set(new_key, "id", Value.I64(self.id)) - async def _teaql_preflight_and_save(self, context): - self._teaql_preflight_graph(context) - return await self._teaql_save_within_graph(context) + async def _teaql_preflight_and_save(self, graph): + context = graph.context + self._teaql_preflight_graph(context, graph) + return await self._teaql_save_within_graph(context, graph) def _teaql_build_command(self): payload = {} @@ -141,7 +142,7 @@ class : cmd = DeleteCommand("", Value.from_any(getattr(self, "id", None)), getattr(self, "version", None)) return action, cmd - def _teaql_preflight_graph(self, context): + def _teaql_preflight_graph(self, context, graph): if not self._comment or not self._comment.strip(): raise Exception("Security audit failure: audit_as() must be called before save()") if self._action == "Update": @@ -155,7 +156,7 @@ class : self._entity_root.set(self._teaql_entity_key(), field, value) - async def _teaql_save_within_graph(self, context): + async def _teaql_save_within_graph(self, context, graph, parent_scope=None): if not self._comment or not self._comment.strip(): raise Exception("Security audit failure: audit_as() must be called before save()") @@ -163,9 +164,8 @@ class : action, cmd = self._teaql_build_command() - req = MutationRequest(cmd) - if self._comment: - req.comment = self._comment + scope = graph.scope(self._teaql_entity_key(), parent_scope, self._comment) + req = graph.request(cmd, scope, self._entity_root, self._teaql_entity_key()) try: context.check_and_fix_mutation(cmd) @@ -199,7 +199,7 @@ class : self._loaded_fields = rollback_loaded_fields if old_key != new_key: self._entity_root.rekey(new_key, old_key) - context.after_graph_rollback(rollback_entity) + graph.after_rollback(rollback_entity) if action != "Delete": self._action = "Update" @@ -212,7 +212,7 @@ class : getattr(child, updater)(self) child.audit_as(self._comment) try: - await child._teaql_save_within_graph(context) + await child._teaql_save_within_graph(context, graph, scope) except CheckException as error: prefix = ObjectLocation().property(relation_name).index(index) raise CheckException([ @@ -228,8 +228,8 @@ class : def commit_entity(): self._entity_root.clear_entity(new_key) if getattr(self, "version", None) is not None: - self._entity_root.set_original_version(new_key, int(self.version)) - context.after_graph_commit(commit_entity) + self._entity_root.accept_committed_version(new_key, int(self.version)) + graph.after_commit(commit_entity) return self @@ -323,7 +323,7 @@ for index, child in enumerate(self._): child.update_(self) child.audit_as(self._comment) try: - child._teaql_preflight_graph(context) + child._teaql_preflight_graph(context, graph) except CheckException as error: prefix = ObjectLocation().property("").index(index) raise CheckException([ diff --git a/generator/src/main/resources/generator/typescript-assist-query/field.md.stg b/generator/src/main/resources/generator/typescript-assist-query/field.md.stg index f467633b..bf3fd87e 100644 --- a/generator/src/main/resources/generator/typescript-assist-query/field.md.stg +++ b/generator/src/main/resources/generator/typescript-assist-query/field.md.stg @@ -11,7 +11,7 @@ Type: `` | Select | `selectWith(request)`select()` | | Filter true | `()` | | Filter false | `()` | -| Filter identity | `Is(id)`, `In(ids)` | +| Filter identity | `filterBy(id)`, `filterByIn(...ids)` | | Filter nested request | `withMatching(request)`, `withoutMatching(request)` | Is()` | }>| Equality/set | `Is(value)`, `IsNot(value)`, `In(values)`, `NotIn(values)` | diff --git a/generator/src/main/resources/generator/typescript-lib-core/model/index.stg b/generator/src/main/resources/generator/typescript-lib-core/model/index.stg index 67034e2e..a30b36cb 100644 --- a/generator/src/main/resources/generator/typescript-lib-core/model/index.stg +++ b/generator/src/main/resources/generator/typescript-lib-core/model/index.stg @@ -1,5 +1,5 @@ index(domain, naming, objectDescriptor) ::= << -import { CheckException, EntityKey, EntityRoot, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, EntityKey, EntityRoot, GraphMutationSession, MutationIntent, ObjectLocation, TeaQLDataService, UserContext } from '../../teaql-ts'; @@ -79,14 +79,14 @@ export class { async save(context: UserContext): Promise\<\> { const service = context.requireResource\("dataService"); - return service.executeGraphSave(async () => { - this.teaqlPreflightGraph(context, service); - return this.teaqlSaveWithinGraph(context, service); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async graph => { + this.teaqlPreflightGraph(context, service, graph); + return this.teaqlSaveWithinGraph(context, service, graph); }); } /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession): void { if (!(this as any)._comment?.trim()) { throw new Error("Security audit failure: auditAs() must be called before save()"); } @@ -102,7 +102,7 @@ export class { }]); } } - service.preflightMutation({ + service.preflightMutation(graph.request({ entity: "", action, payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) @@ -110,12 +110,12 @@ export class { id: (this as any).id, version: (this as any).version, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, - }); + })); } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService): Promise\<\> { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession): Promise\<\> { if (!(this as any)._comment?.trim()) { throw new Error("Security audit failure: auditAs() must be called before save()"); } @@ -131,7 +131,7 @@ export class { ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root }; - const result = await service.executeMutation(mutation); + const result = await service.executeMutation(graph.request(mutation)); for (const [field, value] of Object.entries(mutation.payload as Record\)) { if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); } @@ -164,7 +164,7 @@ export class { service.afterGraphCommit(() => { (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); }); return this; } @@ -188,7 +188,7 @@ mutation_field(field) ::= << >> update_method(field) ::= << -update(value: ): this { +update(value: | null): this { this. = value; this.markLoaded(""); (this as any)._root.set(this.teaqlEntityKey(), "", value); @@ -265,7 +265,7 @@ for (const [index, child] of (this as any)._.entries()) { child.teaqlAttachRoot((this as any)._root); child.update(this); child.auditAs((this as any)._comment); - try { await child.teaqlSaveWithinGraph(context, context.requireResource\("dataService")); } + try { await child.teaqlSaveWithinGraph(context, service, graph); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("").index(index); @@ -281,7 +281,7 @@ for (const [index, child] of (this as any)._.entries()) { child.teaqlAttachRoot((this as any)._root); child.update(this); child.auditAs((this as any)._comment); - try { child.teaqlPreflightGraph(context, service); } + try { child.teaqlPreflightGraph(context, service, graph); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("").index(index); @@ -293,7 +293,7 @@ for (const [index, child] of (this as any)._.entries()) { >> prop(field) ::= << - ?: ; + ?: | null; >> tsType(field) ::= << diff --git a/generator/src/main/resources/generator/typescript-lib-core/workspace/teaql-ts.ts.stg b/generator/src/main/resources/generator/typescript-lib-core/workspace/teaql-ts.ts.stg index 242d0fab..201dc99c 100644 --- a/generator/src/main/resources/generator/typescript-lib-core/workspace/teaql-ts.ts.stg +++ b/generator/src/main/resources/generator/typescript-lib-core/workspace/teaql-ts.ts.stg @@ -1,11 +1,11 @@ index(domain) ::= << import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, GraphMutationSession, MutationIntent, MutationRequest, RuntimeModule, SelectQuery as RuntimeSelectQuery, UserContext, executeRelationFacets, } from "teaql-ts"; -export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets } from "teaql-ts"; +export { CheckException, GraphMutationSession, MutationIntent, MutationRequest, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; @@ -40,7 +40,7 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave\(work: () =\> Promise\): Promise\; + executeGraphSave\(intent: MutationIntent, work: (graph: GraphMutationSession) =\> Promise\): Promise\; preflightMutation(mutation: any): any; afterGraphCommit(work: () =\> void): void; afterGraphRollback(work: () =\> void): void; @@ -98,7 +98,7 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave\(work: () =\> Promise\): Promise\ { + async executeGraphSave\(intent: MutationIntent, work: (graph: GraphMutationSession) =\> Promise\): Promise\ { const predecessor = this.graphSaveTail; let release!: () =\> void; this.graphSaveTail = new Promise\(resolve =\> { release = resolve; }); @@ -116,7 +116,7 @@ export class TeaQLClient implements TeaQLDataService { fixEvidenceStarted = true; this.userContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; - const result = await work(); + const result = await work(new GraphMutationSession(intent)); this.userContext.ensureMutationPolicyGraphComplete(); this.persist(); for (const action of this.graphCommitActions) action(); @@ -154,6 +154,7 @@ export class TeaQLClient implements TeaQLDataService { } private checkAndFixMutation(mutation: any): any { + if (mutation instanceof MutationRequest) mutation = mutation.mutation; if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; const checker = this.checkers[String(mutation.entity)];