-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathSqlMutationEngine.cs
More file actions
2413 lines (2217 loc) · 141 KB
/
SqlMutationEngine.cs
File metadata and controls
2413 lines (2217 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Data;
using System.Data.Common;
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Transactions;
using Azure.DataApiBuilder.Auth;
using Azure.DataApiBuilder.Config.DatabasePrimitives;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
using Azure.DataApiBuilder.Core.Resolvers.Factories;
using Azure.DataApiBuilder.Core.Resolvers.Sql_Query_Structures;
using Azure.DataApiBuilder.Core.Services;
using Azure.DataApiBuilder.Core.Services.MetadataProviders;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.GraphQLBuilder;
using Azure.DataApiBuilder.Service.GraphQLBuilder.Mutations;
using Azure.DataApiBuilder.Service.Services;
using HotChocolate.Language;
using HotChocolate.Resolvers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
namespace Azure.DataApiBuilder.Core.Resolvers
{
/// <summary>
/// Implements the mutation engine interface for mutations against Sql like databases.
/// </summary>
public class SqlMutationEngine : IMutationEngine
{
private readonly IAbstractQueryManagerFactory _queryManagerFactory;
private readonly IMetadataProviderFactory _sqlMetadataProviderFactory;
private readonly IQueryEngineFactory _queryEngineFactory;
private readonly IAuthorizationResolver _authorizationResolver;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly GQLFilterParser _gQLFilterParser;
private readonly RuntimeConfigProvider _runtimeConfigProvider;
public const string IS_UPDATE_RESULT_SET = "IsUpdateResultSet";
private const string TRANSACTION_EXCEPTION_ERROR_MSG = "An unexpected error occurred during the transaction execution";
public const string SINGLE_INPUT_ARGUEMENT_NAME = "item";
public const string MULTIPLE_INPUT_ARGUEMENT_NAME = "items";
private static DataApiBuilderException _dabExceptionWithTransactionErrorMessage = new(message: TRANSACTION_EXCEPTION_ERROR_MSG,
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
/// <summary>
/// Constructor
/// </summary>
public SqlMutationEngine(
IAbstractQueryManagerFactory queryManagerFactory,
IMetadataProviderFactory sqlMetadataProviderFactory,
IQueryEngineFactory queryEngineFactory,
IAuthorizationResolver authorizationResolver,
GQLFilterParser gQLFilterParser,
IHttpContextAccessor httpContextAccessor,
RuntimeConfigProvider runtimeConfigProvider)
{
_queryManagerFactory = queryManagerFactory;
_sqlMetadataProviderFactory = sqlMetadataProviderFactory;
_queryEngineFactory = queryEngineFactory;
_authorizationResolver = authorizationResolver;
_httpContextAccessor = httpContextAccessor;
_gQLFilterParser = gQLFilterParser;
_runtimeConfigProvider = runtimeConfigProvider;
}
/// <summary>
/// Executes the GraphQL mutation query and returns result as JSON object asynchronously.
/// </summary>
/// <param name="context">context of graphql mutation</param>
/// <param name="parameters">parameters in the mutation query.</param>
/// <param name="dataSourceName">dataSourceName to execute against.</param>
/// <returns>JSON object result and its related pagination metadata</returns>
public async Task<Tuple<JsonDocument?, IMetadata?>> ExecuteAsync(IMiddlewareContext context, IDictionary<string, object?> parameters, string dataSourceName = "")
{
if (context.Selection.Type.IsListType())
{
throw new NotSupportedException("Returning list types from mutations not supported");
}
dataSourceName = GetValidatedDataSourceName(dataSourceName);
string graphqlMutationName = context.Selection.Field.Name;
string entityName = GraphQLUtils.GetEntityNameFromContext(context);
ISqlMetadataProvider sqlMetadataProvider = _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName);
IQueryEngine queryEngine = _queryEngineFactory.GetQueryEngine(sqlMetadataProvider.GetDatabaseType());
Tuple<JsonDocument?, IMetadata?>? result = null;
EntityActionOperation mutationOperation = MutationBuilder.DetermineMutationOperationTypeBasedOnInputType(graphqlMutationName);
string roleName = AuthorizationResolver.GetRoleOfGraphQLRequest(context);
// If authorization fails, an exception will be thrown and request execution halts.
AuthorizeMutation(context, parameters, entityName, mutationOperation);
string inputArgumentName = IsPointMutation(context) ? MutationBuilder.ITEM_INPUT_ARGUMENT_NAME : MutationBuilder.ARRAY_INPUT_ARGUMENT_NAME;
if (_runtimeConfigProvider.GetConfig().IsMultipleCreateOperationEnabled() &&
parameters.TryGetValue(inputArgumentName, out object? param) &&
mutationOperation is EntityActionOperation.Create)
{
// Multiple create mutation request is validated to ensure that the request is valid semantically.
IInputValueDefinition schemaForArgument = context.Selection.Field.Arguments[inputArgumentName];
MultipleMutationEntityInputValidationContext multipleMutationEntityInputValidationContext = new(
entityName: entityName,
parentEntityName: string.Empty,
columnsDerivedFromParentEntity: new(),
columnsToBeDerivedFromEntity: new());
MultipleMutationInputValidator multipleMutationInputValidator = new(sqlMetadataProviderFactory: _sqlMetadataProviderFactory, runtimeConfigProvider: _runtimeConfigProvider);
multipleMutationInputValidator.ValidateGraphQLValueNode(
schema: schemaForArgument,
context: context,
parameters: param,
nestingLevel: 0,
multipleMutationEntityInputValidationContext: multipleMutationEntityInputValidationContext);
}
// The presence of READ permission is checked in the current role (with which the request is executed) as well as Anonymous role. This is because, for GraphQL requests,
// READ permission is inherited by other roles from Anonymous role when present.
bool isReadPermissionConfigured = _authorizationResolver.AreRoleAndOperationDefinedForEntity(entityName, roleName, EntityActionOperation.Read)
|| _authorizationResolver.AreRoleAndOperationDefinedForEntity(entityName, AuthorizationType.Anonymous.ToString(), EntityActionOperation.Read);
try
{
// Creating an implicit transaction
using (TransactionScope transactionScope = ConstructTransactionScopeBasedOnDbType(sqlMetadataProvider))
{
if (mutationOperation is EntityActionOperation.Delete)
{
// When read permission is not configured, an error response is returned. So, the mutation result needs to
// be computed only when the read permission is configured.
if (isReadPermissionConfigured)
{
// For cases we only require a result summarizing the operation (DBOperationResult),
// we can skip getting the impacted records.
if (context.Selection.Type.TypeName() != GraphQLUtils.DB_OPERATION_RESULT_TYPE)
{
// compute the mutation result before removing the element,
// since typical GraphQL delete mutations return the metadata of the deleted item.
result = await queryEngine.ExecuteAsync(
context,
GetBackingColumnsFromCollection(entityName: entityName, parameters: parameters, sqlMetadataProvider: sqlMetadataProvider),
dataSourceName);
}
}
Dictionary<string, object>? resultProperties =
await PerformDeleteOperation(
entityName,
parameters,
sqlMetadataProvider);
// If the number of records affected by DELETE were zero,
if (resultProperties is not null
&& resultProperties.TryGetValue(nameof(DbDataReader.RecordsAffected), out object? value)
&& Convert.ToInt32(value) == 0)
{
// the result was not null previously, it indicates this DELETE lost
// a concurrent request race. Hence, empty the non-null result.
if (result is not null && result.Item1 is not null)
{
result = new Tuple<JsonDocument?, IMetadata?>(
default(JsonDocument),
PaginationMetadata.MakeEmptyPaginationMetadata());
}
else if (context.Selection.Type.TypeName() == GraphQLUtils.DB_OPERATION_RESULT_TYPE)
{
// no record affected but db call ran successfully.
result = GetDbOperationResultJsonDocument("item not found");
}
}
else if (context.Selection.Type.TypeName() == GraphQLUtils.DB_OPERATION_RESULT_TYPE)
{
result = GetDbOperationResultJsonDocument("success");
}
}
// This code block contains logic for handling multiple create mutation operations.
else if (mutationOperation is EntityActionOperation.Create && _runtimeConfigProvider.GetConfig().IsMultipleCreateOperationEnabled())
{
bool isPointMutation = IsPointMutation(context);
List<IDictionary<string, object?>> primaryKeysOfCreatedItems = PerformMultipleCreateOperation(
entityName,
context,
parameters,
sqlMetadataProvider,
!isPointMutation);
// For point create multiple mutation operation, a single item is created in the
// table backing the top level entity. So, the PK of the created item is fetched and
// used when calling the query engine to process the selection set.
// For many type multiple create operation, one or more than one item are created
// in the table backing the top level entity. So, the PKs of the created items are
// fetched and used when calling the query engine to process the selection set.
// Point multiple create mutation and many type multiple create mutation are calling different
// overloaded method ("ExecuteAsync") of the query engine to process the selection set.
if (isPointMutation)
{
result = await queryEngine.ExecuteAsync(
context,
primaryKeysOfCreatedItems[0],
dataSourceName);
}
else
{
result = await queryEngine.ExecuteMultipleCreateFollowUpQueryAsync(
context,
primaryKeysOfCreatedItems,
dataSourceName);
}
}
else
{
DbResultSetRow? mutationResultRow =
await PerformMutationOperation(
entityName,
mutationOperation,
parameters,
sqlMetadataProvider,
context);
// When read permission is not configured, an error response is returned. So, the mutation result needs to
// be computed only when the read permission is configured.
if (isReadPermissionConfigured)
{
if (mutationResultRow is not null && mutationResultRow.Columns.Count > 0
&& !context.Selection.Type.IsScalarType())
{
// Because the GraphQL mutation result set columns were exposed (mapped) column names,
// the column names must be converted to backing (source) column names so the
// PrimaryKeyPredicates created in the SqlQueryStructure created by the query engine
// represent database column names.
result = await queryEngine.ExecuteAsync(
context,
GetBackingColumnsFromCollection(entityName: entityName, parameters: mutationResultRow.Columns, sqlMetadataProvider: sqlMetadataProvider),
dataSourceName);
}
else if (context.Selection.Type.TypeName() == GraphQLUtils.DB_OPERATION_RESULT_TYPE)
{
result = GetDbOperationResultJsonDocument("success");
}
}
}
transactionScope.Complete();
}
}
// All the exceptions that can be thrown by .Complete() and .Dispose() methods of transactionScope
// derive from TransactionException. Hence, TransactionException acts as a catch-all.
// When an exception related to Transactions is encountered, the mutation is deemed unsuccessful and
// a DataApiBuilderException is thrown
catch (TransactionException)
{
throw _dabExceptionWithTransactionErrorMessage;
}
if (!isReadPermissionConfigured)
{
throw new DataApiBuilderException(message: $"The mutation operation {context.Selection.Field.Name} was successful but the current user is unauthorized to view the response due to lack of read permissions",
statusCode: HttpStatusCode.Forbidden,
subStatusCode: DataApiBuilderException.SubStatusCodes.AuthorizationCheckFailed);
}
if (result is null)
{
throw new DataApiBuilderException(message: "Failed to resolve any query based on the current configuration.",
statusCode: HttpStatusCode.BadRequest,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
}
return result;
}
/// <summary>
/// Helper method to determine whether a mutation is a mutate one or mutate many operation (eg. createBook/createBooks).
/// </summary>
/// <param name="context">GraphQL request context.</param>
private static bool IsPointMutation(IMiddlewareContext context)
{
IOutputType outputType = context.Selection.Field.Type;
if (outputType.TypeName().Equals(GraphQLUtils.DB_OPERATION_RESULT_TYPE))
{
// Hit when the database type is DwSql. We don't support multiple mutation for DwSql yet.
return true;
}
ObjectType underlyingFieldType = outputType.NamedType<ObjectType>();
bool isPointMutation;
if (GraphQLUtils.TryExtractGraphQLFieldModelName(underlyingFieldType.Directives, out string? _))
{
isPointMutation = true;
}
else
{
// Model directive is not added to the output type of 'mutate many' mutations.
// Thus, absence of model directive here indicates that we are dealing with a 'mutate many'
// mutation like createBooks.
isPointMutation = false;
}
return isPointMutation;
}
/// <summary>
/// Converts exposed column names from the parameters provided to backing column names.
/// parameters.Value is not modified.
/// </summary>
/// <param name="entityName">Name of Entity</param>
/// <param name="parameters">Key/Value collection where only the key is converted.</param>
/// <returns>Dictionary where the keys now represent backing column names.</returns>
public static Dictionary<string, object?> GetBackingColumnsFromCollection(string entityName, IDictionary<string, object?> parameters, ISqlMetadataProvider sqlMetadataProvider)
{
Dictionary<string, object?> backingRowParams = new();
foreach (KeyValuePair<string, object?> resultEntry in parameters)
{
sqlMetadataProvider.TryGetBackingColumn(entityName, resultEntry.Key, out string? name);
if (!string.IsNullOrWhiteSpace(name))
{
backingRowParams.Add(name, resultEntry.Value);
}
else
{
backingRowParams.Add(resultEntry.Key, resultEntry.Value);
}
}
return backingRowParams;
}
/// <summary>
/// Executes the REST mutation query and returns IActionResult asynchronously.
/// Result error cases differ for Stored Procedure requests than normal mutation requests
/// QueryStructure built does not depend on Operation enum, thus not useful to use
/// PerformMutationOperation method.
/// </summary>
public async Task<IActionResult?> ExecuteAsync(StoredProcedureRequestContext context, string dataSourceName = "")
{
dataSourceName = GetValidatedDataSourceName(dataSourceName);
ISqlMetadataProvider sqlMetadataProvider = _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName);
IQueryBuilder queryBuilder = _queryManagerFactory.GetQueryBuilder(sqlMetadataProvider.GetDatabaseType());
IQueryExecutor queryExecutor = _queryManagerFactory.GetQueryExecutor(sqlMetadataProvider.GetDatabaseType());
SqlExecuteStructure executeQueryStructure = new(
context.EntityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
context.ResolvedParameters);
string queryText = queryBuilder.Build(executeQueryStructure);
JsonArray? resultArray = null;
try
{
// Creating an implicit transaction
using (TransactionScope transactionScope = ConstructTransactionScopeBasedOnDbType(sqlMetadataProvider))
{
resultArray =
await queryExecutor.ExecuteQueryAsync(
queryText,
executeQueryStructure.Parameters,
queryExecutor.GetJsonArrayAsync,
dataSourceName,
GetHttpContext());
transactionScope.Complete();
}
}
// All the exceptions that can be thrown by .Complete() and .Dispose() methods of transactionScope
// derive from TransactionException. Hence, TransactionException acts as a catch-all.
// When an exception related to Transactions is encountered, the mutation is deemed unsuccessful and
// a DataApiBuilderException is thrown
catch (TransactionException)
{
throw _dabExceptionWithTransactionErrorMessage;
}
// A note on returning stored procedure results:
// We can't infer what the stored procedure actually did beyond the HasRows and RecordsAffected attributes
// of the DbDataReader. For example, we can't enforce that an UPDATE command outputs a result set using an OUTPUT
// clause. As such, for this iteration we are just returning the success condition of the operation type that maps
// to each action, with data always from the first result set, as there may be arbitrarily many.
switch (context.OperationType)
{
case EntityActionOperation.Delete:
// Returns a 204 No Content so long as the stored procedure executes without error
return new NoContentResult();
case EntityActionOperation.Insert:
HttpContext httpContext = GetHttpContext();
// Use scheme/host from X-Forwarded-* headers if present, else fallback to request values
string scheme = SqlPaginationUtil.ResolveRequestScheme(httpContext.Request);
string host = SqlPaginationUtil.ResolveRequestHost(httpContext.Request);
string locationHeaderURL = UriHelper.BuildAbsolute(
scheme: scheme,
host: new HostString(host),
pathBase: GetBaseRouteFromConfig(_runtimeConfigProvider.GetConfig()),
path: httpContext.Request.Path);
// Returns a 201 Created with whatever the first result set is returned from the procedure
// A "correctly" configured stored procedure would INSERT INTO ... OUTPUT ... VALUES as the result set
if (resultArray is not null && resultArray.Count > 0)
{
using (JsonDocument jsonDocument = JsonDocument.Parse(resultArray.ToJsonString()))
{
// The final location header for stored procedures should be of the form ../api/<SP-Entity-Name>
// Location header is constructed using the base URL, base-route and the set location value.
return new CreatedResult(location: locationHeaderURL, SqlResponseHelpers.OkMutationResponse(jsonDocument.RootElement.Clone()).Value);
}
}
else
{ // If no result set returned, just return a 201 Created with empty array instead of array with single null value
return new CreatedResult(
location: locationHeaderURL,
value: new
{
value = JsonDocument.Parse("[]").RootElement.Clone()
}
);
}
case EntityActionOperation.Update:
case EntityActionOperation.UpdateIncremental:
case EntityActionOperation.Upsert:
case EntityActionOperation.UpsertIncremental:
// Since we cannot check if anything was created, just return a 200 Ok response with first result set output
// A "correctly" configured stored procedure would UPDATE ... SET ... OUTPUT as the result set
if (resultArray is not null && resultArray.Count > 0)
{
using (JsonDocument jsonDocument = JsonDocument.Parse(resultArray.ToJsonString()))
{
return SqlResponseHelpers.OkMutationResponse(jsonDocument.RootElement.Clone());
}
}
else
{
// If no result set returned, return 200 Ok response with empty array instead of array with single null value
return new OkObjectResult(
value: new
{
value = JsonDocument.Parse("[]").RootElement.Clone()
}
);
}
default:
throw new DataApiBuilderException(
message: "Unsupported operation.",
statusCode: HttpStatusCode.BadRequest,
subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest);
}
}
/// <summary>
/// Executes the REST mutation query and returns IActionResult asynchronously.
/// </summary>
/// <param name="context">context of REST mutation request.</param>
/// <returns>IActionResult</returns>
public async Task<IActionResult?> ExecuteAsync(RestRequestContext context)
{
// for REST API scenarios, use the default datasource
string dataSourceName = _runtimeConfigProvider.GetConfig().DefaultDataSourceName;
Dictionary<string, object?> parameters = PrepareParameters(context);
ISqlMetadataProvider sqlMetadataProvider = _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName);
if (context.OperationType is EntityActionOperation.Delete)
{
Dictionary<string, object>? resultProperties = null;
try
{
// Creating an implicit transaction
using (TransactionScope transactionScope = ConstructTransactionScopeBasedOnDbType(sqlMetadataProvider))
{
resultProperties = await PerformDeleteOperation(
entityName: context.EntityName,
parameters: parameters,
sqlMetadataProvider: sqlMetadataProvider);
transactionScope.Complete();
}
}
// All the exceptions that can be thrown by .Complete() and .Dispose() methods of transactionScope
// derive from TransactionException. Hence, TransactionException acts as a catch-all.
// When an exception related to Transactions is encountered, the mutation is deemed unsuccessful and
// a DataApiBuilderException is thrown
catch (TransactionException)
{
throw _dabExceptionWithTransactionErrorMessage;
}
// Records affected tells us that item was successfully deleted.
// No records affected happens for a DELETE request on nonexistent object
if (resultProperties is not null
&& resultProperties.TryGetValue(nameof(DbDataReader.RecordsAffected), out object? value))
{
// DbDataReader.RecordsAffected contains the number of rows changed deleted. 0 if no records were deleted.
// When the flow reaches this code block and the number of records affected is 0, then it means that no failure occurred at the database layer
// and that the item identified by the specified PK was not found.
if (Convert.ToInt32(value) == 0)
{
string prettyPrintPk = "<" + string.Join(", ", context.PrimaryKeyValuePairs.Select(kv_pair => $"{kv_pair.Key}: {kv_pair.Value}")) + ">";
throw new DataApiBuilderException(
message: $"Could not find item with {prettyPrintPk}",
statusCode: HttpStatusCode.NotFound,
subStatusCode: DataApiBuilderException.SubStatusCodes.ItemNotFound);
}
return new NoContentResult();
}
}
else
{
if (!GetHttpContext().Request.Headers.TryGetValue(AuthorizationResolver.CLIENT_ROLE_HEADER, out StringValues headerValues) && headerValues.Count != 1)
{
throw new DataApiBuilderException(
message: $"No role found.",
statusCode: HttpStatusCode.Forbidden,
subStatusCode: DataApiBuilderException.SubStatusCodes.AuthorizationCheckFailed);
}
string roleName = headerValues.ToString();
bool isReadPermissionConfiguredForRole = _authorizationResolver.AreRoleAndOperationDefinedForEntity(context.EntityName, roleName, EntityActionOperation.Read);
bool isDatabasePolicyDefinedForReadAction = false;
JsonDocument? selectOperationResponse = null;
if (isReadPermissionConfiguredForRole)
{
isDatabasePolicyDefinedForReadAction = !string.IsNullOrWhiteSpace(_authorizationResolver.GetDBPolicyForRequest(context.EntityName, roleName, EntityActionOperation.Read));
}
try
{
if (context.OperationType is EntityActionOperation.Upsert || context.OperationType is EntityActionOperation.UpsertIncremental)
{
DbResultSet? upsertOperationResult;
DbResultSetRow upsertOperationResultSetRow;
// This variable indicates whether the upsert resulted in an update operation. If true, then the upsert resulted in an update operation.
// If false, the upsert resulted in an insert operation.
bool hasPerformedUpdate = false;
try
{
// Creating an implicit transaction
using (TransactionScope transactionScope = ConstructTransactionScopeBasedOnDbType(sqlMetadataProvider))
{
upsertOperationResult = await PerformUpsertOperation(
parameters: parameters,
context: context,
sqlMetadataProvider: sqlMetadataProvider);
if (upsertOperationResult is null)
{
// Ideally this case should not happen, however may occur due to unexpected reasons,
// like the DbDataReader being null. We throw an exception
// which will be returned as an InternalServerError with UnexpectedError substatus code.
throw new DataApiBuilderException(
message: "An unexpected error occurred while trying to execute the query.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
}
upsertOperationResultSetRow = upsertOperationResult.Rows.FirstOrDefault() ?? new();
if (upsertOperationResultSetRow.Columns.Count > 0 &&
upsertOperationResult.ResultProperties.TryGetValue(IS_UPDATE_RESULT_SET, out object? isUpdateResultSetValue))
{
hasPerformedUpdate = Convert.ToBoolean(isUpdateResultSetValue);
}
// The role with which the REST request is executed can have a database policy defined for the read action.
// In such a case, to get the results back, a select query which honors the database policy is executed.
if (isDatabasePolicyDefinedForReadAction)
{
FindRequestContext findRequestContext = ConstructFindRequestContext(context, upsertOperationResultSetRow, roleName, sqlMetadataProvider);
IQueryEngine queryEngine = _queryEngineFactory.GetQueryEngine(sqlMetadataProvider.GetDatabaseType());
selectOperationResponse = await queryEngine.ExecuteAsync(findRequestContext);
}
transactionScope.Complete();
}
}
// All the exceptions that can be thrown by .Complete() and .Dispose() methods of transactionScope
// derive from TransactionException. Hence, TransactionException acts as a catch-all.
// When an exception related to Transactions is encountered, the mutation is deemed unsuccessful and
// a DataApiBuilderException is thrown
catch (TransactionException)
{
throw _dabExceptionWithTransactionErrorMessage;
}
Dictionary<string, object?> resultRow = upsertOperationResultSetRow.Columns;
// For all SQL database types, when an upsert operation results in an update operation, an entry <IsUpdateResultSet,true> is added to the result set dictionary.
// For MsSQL and MySQL database types, the "IsUpdateResultSet" field is sufficient to determine whether the resultant operation was an insert or an update.
// For PostgreSQL, the result set dictionary will always contain the entry <IsUpdateResultSet,true> irrespective of the upsert resulting in an insert/update operation.
// PostgreSQL result sets will contain a field "___upsert_op___" that indicates whether the resultant operation was an update or an insert. So, the value present in this field
// is used to determine whether the upsert resulted in an update/insert.
if (sqlMetadataProvider.GetDatabaseType() is DatabaseType.PostgreSQL)
{
hasPerformedUpdate = !PostgresQueryBuilder.IsInsert(resultRow);
}
// When read permissions is configured without database policy, a subsequent select query will not be executed.
// However, the read action could have include and exclude fields configured. To honor that configuration setup,
// any additional fields that are present in the response are removed.
if (isReadPermissionConfiguredForRole && !isDatabasePolicyDefinedForReadAction)
{
IEnumerable<string> allowedExposedColumns = _authorizationResolver.GetAllowedExposedColumns(context.EntityName, roleName, EntityActionOperation.Read);
foreach (string columnInResponse in resultRow.Keys)
{
if (!allowedExposedColumns.Contains(columnInResponse))
{
resultRow.Remove(columnInResponse);
}
}
}
// When the upsert operation results in the creation of a new record, an HTTP 201 CreatedResult response is returned.
if (!hasPerformedUpdate)
{
// Location Header is made up of the Base URL of the request and the primary key of the item created.
// However, for PATCH and PUT requests, the primary key would be present in the request URL. For POST request, however, the primary key
// would not be available in the URL and needs to be appended. Since, this is a PUT or PATCH request that has resulted in the creation of
// a new item, the URL already contains the primary key and hence, an empty string is passed as the primary key route.
return SqlResponseHelpers.ConstructCreatedResultResponse(resultRow, selectOperationResponse, primaryKeyRoute: string.Empty, isReadPermissionConfiguredForRole, isDatabasePolicyDefinedForReadAction, context.OperationType, GetBaseRouteFromConfig(_runtimeConfigProvider.GetConfig()), GetHttpContext());
}
// When the upsert operation results in the update of an existing record, an HTTP 200 OK response is returned.
return SqlResponseHelpers.ConstructOkMutationResponse(resultRow, selectOperationResponse, isReadPermissionConfiguredForRole, isDatabasePolicyDefinedForReadAction);
}
else
{
// This code block gets executed when the operation type is one among Insert, Update or UpdateIncremental.
DbResultSetRow? mutationResultRow = null;
try
{
// Creating an implicit transaction
using (TransactionScope transactionScope = ConstructTransactionScopeBasedOnDbType(sqlMetadataProvider))
{
mutationResultRow =
await PerformMutationOperation(
entityName: context.EntityName,
operationType: context.OperationType,
parameters: parameters,
sqlMetadataProvider: sqlMetadataProvider);
if (mutationResultRow is null || mutationResultRow.Columns.Count == 0)
{
if (context.OperationType is EntityActionOperation.Insert)
{
if (mutationResultRow is null)
{
// Ideally this case should not happen, however may occur due to unexpected reasons,
// like the DbDataReader being null. We throw an exception
// which will be returned as an UnexpectedError.
throw new DataApiBuilderException(
message: "An unexpected error occurred while trying to execute the query.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
}
if (mutationResultRow.Columns.Count == 0)
{
throw new DataApiBuilderException(
message: "Could not insert row with given values.",
statusCode: HttpStatusCode.Forbidden,
subStatusCode: DataApiBuilderException.SubStatusCodes.DatabasePolicyFailure
);
}
}
else
{
if (mutationResultRow is null)
{
// Ideally this case should not happen, however may occur due to unexpected reasons,
// like the DbDataReader being null. We throw an exception
// which will be returned as an UnexpectedError
throw new DataApiBuilderException(message: "An unexpected error occurred while trying to execute the query.",
statusCode: HttpStatusCode.NotFound,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
}
if (mutationResultRow.Columns.Count == 0)
{
// This code block is reached when Update or UpdateIncremental operation does not successfully find the record to
// update. An exception is thrown which will be returned as a 404 NotFound response.
throw new DataApiBuilderException(message: "No Update could be performed, record not found",
statusCode: HttpStatusCode.NotFound,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
}
}
// The role with which the REST request is executed can have database policies defined for the read action.
// When the database policy is defined for the read action, a select query that honors the database policy
// is executed to fetch the results.
if (isDatabasePolicyDefinedForReadAction)
{
FindRequestContext findRequestContext = ConstructFindRequestContext(context, mutationResultRow, roleName, sqlMetadataProvider);
IQueryEngine queryEngine = _queryEngineFactory.GetQueryEngine(sqlMetadataProvider.GetDatabaseType());
selectOperationResponse = await queryEngine.ExecuteAsync(findRequestContext);
}
transactionScope.Complete();
}
}
// All the exceptions that can be thrown by .Complete() and .Dispose() methods of transactionScope
// derive from TransactionException. Hence, TransactionException acts as a catch-all.
// When an exception related to Transactions is encountered, the mutation is deemed unsuccessful and
// a DataApiBuilderException is thrown
catch (TransactionException)
{
throw _dabExceptionWithTransactionErrorMessage;
}
// When read permission is configured without a database policy, a subsequent select query will not be executed.
// So, if the read action has include/exclude fields configured, additional fields present in the response
// need to be removed.
if (isReadPermissionConfiguredForRole && !isDatabasePolicyDefinedForReadAction)
{
IEnumerable<string> allowedExposedColumns = _authorizationResolver.GetAllowedExposedColumns(context.EntityName, roleName, EntityActionOperation.Read);
foreach (string columnInResponse in mutationResultRow!.Columns.Keys)
{
if (!allowedExposedColumns.Contains(columnInResponse))
{
mutationResultRow!.Columns.Remove(columnInResponse);
}
}
}
string primaryKeyRouteForLocationHeader = isReadPermissionConfiguredForRole ? SqlResponseHelpers.ConstructPrimaryKeyRoute(context, mutationResultRow!.Columns, sqlMetadataProvider)
: string.Empty;
if (context.OperationType is EntityActionOperation.Insert)
{
// Location Header is made up of the Base URL of the request and the primary key of the item created.
// For POST requests, the primary key info would not be available in the URL and needs to be appended. So, the primary key of the newly created item
// which is stored in the primaryKeyRoute is used to construct the Location Header.
return SqlResponseHelpers.ConstructCreatedResultResponse(mutationResultRow!.Columns, selectOperationResponse, primaryKeyRouteForLocationHeader, isReadPermissionConfiguredForRole, isDatabasePolicyDefinedForReadAction, context.OperationType, GetBaseRouteFromConfig(_runtimeConfigProvider.GetConfig()), GetHttpContext());
}
if (context.OperationType is EntityActionOperation.Update || context.OperationType is EntityActionOperation.UpdateIncremental)
{
return SqlResponseHelpers.ConstructOkMutationResponse(mutationResultRow!.Columns, selectOperationResponse, isReadPermissionConfiguredForRole, isDatabasePolicyDefinedForReadAction);
}
}
}
finally
{
if (selectOperationResponse is not null)
{
selectOperationResponse.Dispose();
}
}
}
// if we have not yet returned, record is null
return null;
}
/// <summary>
/// Constructs a FindRequestContext from the Insert/Upsert RequestContext and the results of insert/upsert database operation.
/// For REST POST, PUT AND PATCH API requests, when there are database policies defined for the read action,
/// a subsequent select query that honors the database policy is executed to fetch the results.
/// </summary>
/// <param name="context">Insert/Upsert Request context for the REST POST, PUT and PATCH request</param>
/// <param name="mutationResultRow">Result of the insert/upsert database operation</param>
/// <param name="roleName">Role with which the API request is executed</param>
/// <param name="sqlMetadataProvider">SqlMetadataProvider object - provides helper method to get the exposed column name for a given column name</param>
/// <returns>Returns a FindRequestContext object constructed from the existing context and create/upsert operation results.</returns>
private FindRequestContext ConstructFindRequestContext(RestRequestContext context, DbResultSetRow mutationResultRow, string roleName, ISqlMetadataProvider sqlMetadataProvider)
{
FindRequestContext findRequestContext = new(entityName: context.EntityName, dbo: context.DatabaseObject, isList: false);
// PrimaryKeyValuePairs in the context is populated using the primary key values from the
// results of the insert/update database operation.
foreach (string primarykey in context.DatabaseObject.SourceDefinition.PrimaryKey)
{
// The primary keys can have a mapping defined. mutationResultRow contains the mapped column names as keys.
// So, the mapped field names are used to look up and fetch the values from mutationResultRow.
// TryGetExposedColumnName method populates the the mapped column name (if configured) or the original column name into exposedColumnName.
// It returns false if the primary key does not exist.
if (sqlMetadataProvider.TryGetExposedColumnName(context.EntityName, primarykey, out string? exposedColumnName))
{
findRequestContext.PrimaryKeyValuePairs.Add(exposedColumnName, mutationResultRow.Columns[exposedColumnName]!);
}
else
{
// This code block should never be reached because the information about primary keys gets populated during the startup.
throw new DataApiBuilderException(
message: "Insert/Upsert operation was successful but unexpected error when constructing the response",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
}
}
// READ action for the given role can have include and exclude fields configured. Populating UpdateReturnFields
// ensures that the select query retrieves only those fields that are allowed for the given role.
findRequestContext.UpdateReturnFields(_authorizationResolver.GetAllowedExposedColumns(context.EntityName, roleName, EntityActionOperation.Read));
return findRequestContext;
}
/// <summary>
/// Performs the given REST and GraphQL mutation operation of type
/// Insert, Create, Update, UpdateIncremental, UpdateGraphQL
/// on the source backing the given entity.
/// </summary>
/// <param name="entityName">The name of the entity on which mutation is to be performed.</param>
/// <param name="operationType">The type of mutation operation.
/// This cannot be Delete, Upsert or UpsertIncremental since those operations have dedicated functions.</param>
/// <param name="parameters">The parameters of the mutation query.</param>
/// <param name="context">In the case of GraphQL, the HotChocolate library's middleware context.</param>
/// <returns>Single row read from DbDataReader.</returns>
private async Task<DbResultSetRow?>
PerformMutationOperation(
string entityName,
EntityActionOperation operationType,
IDictionary<string, object?> parameters,
ISqlMetadataProvider sqlMetadataProvider,
IMiddlewareContext? context = null)
{
IQueryBuilder queryBuilder = _queryManagerFactory.GetQueryBuilder(sqlMetadataProvider.GetDatabaseType());
IQueryExecutor queryExecutor = _queryManagerFactory.GetQueryExecutor(sqlMetadataProvider.GetDatabaseType());
string dataSourceName = _runtimeConfigProvider.GetConfig().GetDataSourceNameFromEntityName(entityName);
string queryString;
Dictionary<string, DbConnectionParam> queryParameters;
switch (operationType)
{
case EntityActionOperation.Insert:
case EntityActionOperation.Create:
SqlInsertStructure insertQueryStruct = context is null
? new(
entityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
parameters,
GetHttpContext())
: new(
context,
entityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
parameters,
GetHttpContext());
queryString = queryBuilder.Build(insertQueryStruct);
queryParameters = insertQueryStruct.Parameters;
break;
case EntityActionOperation.Update:
SqlUpdateStructure updateStructure = new(
entityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
parameters,
GetHttpContext(),
isIncrementalUpdate: false);
queryString = queryBuilder.Build(updateStructure);
queryParameters = updateStructure.Parameters;
break;
case EntityActionOperation.UpdateIncremental:
SqlUpdateStructure updateIncrementalStructure = new(
entityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
parameters,
GetHttpContext(),
isIncrementalUpdate: true);
queryString = queryBuilder.Build(updateIncrementalStructure);
queryParameters = updateIncrementalStructure.Parameters;
break;
case EntityActionOperation.UpdateGraphQL:
if (context is null)
{
throw new ArgumentNullException("Context should not be null for a GraphQL operation.");
}
SqlUpdateStructure updateGraphQLStructure = new(
context,
entityName,
sqlMetadataProvider,
_authorizationResolver,
_gQLFilterParser,
parameters,
GetHttpContext());
queryString = queryBuilder.Build(updateGraphQLStructure);
queryParameters = updateGraphQLStructure.Parameters;
break;
default:
throw new NotSupportedException($"Unexpected mutation operation \" {operationType}\" requested.");
}
DbResultSet? dbResultSet;
DbResultSetRow? dbResultSetRow;
if (context is not null && !context.Selection.Type.IsScalarType())
{
SourceDefinition sourceDefinition = sqlMetadataProvider.GetSourceDefinition(entityName);
// To support GraphQL field mappings (DB column aliases), convert the sourceDefinition
// primary key column names (backing columns) to the exposed (mapped) column names to
// identify primary key column names in the mutation result set.
List<string> primaryKeyExposedColumnNames = new();
foreach (string primaryKey in sourceDefinition.PrimaryKey)
{
if (sqlMetadataProvider.TryGetExposedColumnName(entityName, primaryKey, out string? name) && !string.IsNullOrWhiteSpace(name))
{
primaryKeyExposedColumnNames.Add(name);
}
}
// Only extract pk columns since non pk columns can be null
// and the subsequent query would search with:
// nullParamName = NULL
// which would fail to get the mutated entry from the db
// When no exposed column names were resolved, it is safe to provide
// backing column names (sourceDefinition.Primary) as a list of arguments.
dbResultSet =
await queryExecutor.ExecuteQueryAsync(
queryString,
queryParameters,
queryExecutor.ExtractResultSetFromDbDataReaderAsync,
dataSourceName,
GetHttpContext(),
primaryKeyExposedColumnNames.Count > 0 ? primaryKeyExposedColumnNames : sourceDefinition.PrimaryKey);
dbResultSetRow = dbResultSet is not null ?
(dbResultSet.Rows.FirstOrDefault() ?? new DbResultSetRow()) : null;
if (dbResultSetRow is not null && dbResultSetRow.Columns.Count == 0 && dbResultSet!.ResultProperties.TryGetValue("RecordsAffected", out object? recordsAffected) && (int)recordsAffected <= 0)
{
// For GraphQL, insert operation corresponds to Create action.
if (operationType is EntityActionOperation.Create)
{
throw new DataApiBuilderException(
message: "Could not insert row with given values.",
statusCode: HttpStatusCode.Forbidden,
subStatusCode: DataApiBuilderException.SubStatusCodes.DatabasePolicyFailure
);
}
string searchedPK;
if (primaryKeyExposedColumnNames.Count > 0)
{
searchedPK = '<' + string.Join(", ", primaryKeyExposedColumnNames.Select(pk => $"{pk}: {parameters[pk]}")) + '>';
}
else
{
searchedPK = '<' + string.Join(", ", sourceDefinition.PrimaryKey.Select(pk => $"{pk}: {parameters[pk]}")) + '>';
}
throw new DataApiBuilderException(
message: $"Could not find item with {searchedPK}",
statusCode: HttpStatusCode.NotFound,
subStatusCode: DataApiBuilderException.SubStatusCodes.ItemNotFound);
}
}
else
{
// This is the scenario for all REST mutation operations covered by this function
// and the case when the Selection Type is a scalar for GraphQL.
dbResultSet =
await queryExecutor.ExecuteQueryAsync(
sqltext: queryString,
parameters: queryParameters,
dataReaderHandler: queryExecutor.ExtractResultSetFromDbDataReaderAsync,
httpContext: GetHttpContext(),
dataSourceName: dataSourceName);
dbResultSetRow = dbResultSet is not null ? (dbResultSet.Rows.FirstOrDefault() ?? new()) : null;
}
return dbResultSetRow;
}
/// <summary>
/// Performs the given GraphQL create mutation operation.