-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathSqlMetadataProvider.cs
More file actions
2294 lines (2053 loc) · 113 KB
/
SqlMetadataProvider.cs
File metadata and controls
2294 lines (2053 loc) · 113 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.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Azure.DataApiBuilder.Config.DatabasePrimitives;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
using Azure.DataApiBuilder.Core.Parsers;
using Azure.DataApiBuilder.Core.Resolvers;
using Azure.DataApiBuilder.Core.Resolvers.Factories;
using Azure.DataApiBuilder.Service.Exceptions;
using HotChocolate.Language;
using Microsoft.Extensions.Logging;
using static Azure.DataApiBuilder.Service.GraphQLBuilder.GraphQLNaming;
using KeyNotFoundException = System.Collections.Generic.KeyNotFoundException;
[assembly: InternalsVisibleTo("Azure.DataApiBuilder.Service.Tests")]
namespace Azure.DataApiBuilder.Core.Services
{
/// <summary>
/// Reads schema information from the database to make it
/// available for the GraphQL/REST services.
/// </summary>
public abstract class SqlMetadataProvider<ConnectionT, DataAdapterT, CommandT> : ISqlMetadataProvider
where ConnectionT : DbConnection, new()
where DataAdapterT : DbDataAdapter, new()
where CommandT : DbCommand, new()
{
private ODataParser _oDataParser = new();
private readonly DatabaseType _databaseType;
// Represents the linking entities created by DAB to support multiple mutations for entities having an M:N relationship between them.
protected Dictionary<string, Entity> _linkingEntities = new();
protected readonly string _dataSourceName;
// Represents the entities exposed in the runtime config.
private IReadOnlyDictionary<string, Entity> Entities => new ReadOnlyDictionary<string, Entity>(_runtimeConfigProvider.GetConfig().Entities.Where(x => string.Equals(_runtimeConfigProvider.GetConfig().GetDataSourceNameFromEntityName(x.Key), _dataSourceName, StringComparison.OrdinalIgnoreCase)).ToDictionary(x => x.Key, x => x.Value));
// Represents the autoentities exposed in the runtime config.
private IReadOnlyDictionary<string, Autoentity> Autoentities => new ReadOnlyDictionary<string, Autoentity>(_runtimeConfigProvider.GetConfig().Autoentities.Where(x => string.Equals(_runtimeConfigProvider.GetConfig().GetDataSourceNameFromAutoentityName(x.Key), _dataSourceName, StringComparison.OrdinalIgnoreCase)).ToDictionary(x => x.Key, x => x.Value));
// Dictionary containing mapping of graphQL stored procedure exposed query/mutation name
// to their corresponding entity names defined in the config.
public Dictionary<string, string> GraphQLStoredProcedureExposedNameToEntityNameMap { get; set; } = new();
// Contains all the referencing and referenced columns for each pair
// of referencing and referenced tables.
public Dictionary<RelationShipPair, ForeignKeyDefinition>? PairToFkDefinition { get; set; }
/// <summary>
/// Maps {entityName, relationshipName} to the ForeignKeyDefinition defined for the relationship.
/// The ForeignKeyDefinition denotes referencing/referenced fields and whether the referencing/referenced fields
/// apply to the target or source entity as defined in the relationship in the config file.
/// </summary>
public Dictionary<EntityRelationshipKey, ForeignKeyDefinition> RelationshipToFkDefinition { get; set; } = new();
protected IQueryExecutor QueryExecutor { get; }
protected const int NUMBER_OF_RESTRICTIONS = 4;
protected string ConnectionString { get; init; }
protected IQueryBuilder SqlQueryBuilder { get; init; }
protected DataSet EntitiesDataSet { get; init; }
private RuntimeConfigProvider _runtimeConfigProvider;
private RuntimeConfigValidator _runtimeConfigValidator;
private Dictionary<string, Dictionary<string, string>> EntityBackingColumnsToExposedNames { get; } = new();
private Dictionary<string, Dictionary<string, string>> EntityExposedNamesToBackingColumnNames { get; } = new();
protected IAbstractQueryManagerFactory QueryManagerFactory { get; init; }
/// <summary>
/// Maps an entity name to a DatabaseObject.
/// </summary>
public virtual Dictionary<string, DatabaseObject> EntityToDatabaseObject { get; set; } =
new(StringComparer.InvariantCulture);
protected readonly ILogger<ISqlMetadataProvider> _logger;
public readonly bool _isValidateOnly;
public List<Exception> SqlMetadataExceptions { get; private set; } = new();
private void HandleOrRecordException(Exception e)
{
if (_isValidateOnly)
{
SqlMetadataExceptions.Add(e);
}
else
{
throw e;
}
}
public SqlMetadataProvider(
RuntimeConfigProvider runtimeConfigProvider,
RuntimeConfigValidator runtimeConfigValidator,
IAbstractQueryManagerFactory engineFactory,
ILogger<ISqlMetadataProvider> logger,
string dataSourceName,
bool isValidateOnly = false)
{
RuntimeConfig runtimeConfig = runtimeConfigProvider.GetConfig();
_runtimeConfigProvider = runtimeConfigProvider;
_runtimeConfigValidator = runtimeConfigValidator;
_dataSourceName = dataSourceName;
_databaseType = runtimeConfig.GetDataSourceFromDataSourceName(dataSourceName).DatabaseType;
_logger = logger;
_isValidateOnly = isValidateOnly;
foreach ((string entityName, Entity entityMetatdata) in Entities)
{
if (runtimeConfig.IsRestEnabled)
{
string restPath = entityMetatdata.Rest?.Path ?? entityName;
_logger.LogInformation("[{entity}] REST path: {globalRestPath}/{entityRestPath}", entityName, runtimeConfig.RestPath, restPath);
}
else
{
_logger.LogInformation(message: "REST calls are disabled for the entity: {entity}", entityName);
}
}
ConnectionString = runtimeConfig.GetDataSourceFromDataSourceName(dataSourceName).ConnectionString;
EntitiesDataSet = new();
QueryManagerFactory = engineFactory;
SqlQueryBuilder = QueryManagerFactory.GetQueryBuilder(_databaseType);
QueryExecutor = QueryManagerFactory.GetQueryExecutor(_databaseType);
}
/// <inheritdoc />
public ODataParser GetODataParser()
{
return _oDataParser;
}
/// <inheritdoc />
public DatabaseType GetDatabaseType()
{
return _databaseType;
}
/// <summary>
/// Obtains the underlying query builder.
/// </summary>
/// <returns></returns>
public IQueryBuilder GetQueryBuilder()
{
return SqlQueryBuilder;
}
/// <inheritdoc />
public virtual string GetSchemaName(string entityName)
{
if (!EntityToDatabaseObject.TryGetValue(entityName, out DatabaseObject? databaseObject))
{
throw new DataApiBuilderException(message: $"Table Definition for {entityName} has not been inferred.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
return databaseObject!.SchemaName;
}
/// <summary>
/// Gets the database name. This method is only relevant for MySql where the terms schema and database are used interchangeably.
/// </summary>
public virtual string GetDatabaseName() => string.Empty;
/// <inheritdoc />
public string GetDatabaseObjectName(string entityName)
{
if (!EntityToDatabaseObject.TryGetValue(entityName, out DatabaseObject? databaseObject))
{
throw new DataApiBuilderException(message: $"Table Definition for {entityName} has not been inferred.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
return databaseObject!.Name;
}
/// <inheritdoc />
public SourceDefinition GetSourceDefinition(string entityName)
{
if (!EntityToDatabaseObject.TryGetValue(entityName, out DatabaseObject? databaseObject))
{
throw new DataApiBuilderException(message: $"Table Definition for {entityName} has not been inferred.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
return databaseObject.SourceDefinition;
}
/// <inheritdoc />
public StoredProcedureDefinition GetStoredProcedureDefinition(string entityName)
{
if (!EntityToDatabaseObject.TryGetValue(entityName, out DatabaseObject? databaseObject))
{
throw new DataApiBuilderException(message: $"Stored Procedure Definition for {entityName} has not been inferred.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
return ((DatabaseStoredProcedure)databaseObject).StoredProcedureDefinition;
}
/// <inheritdoc />
public bool TryGetExposedColumnName(string entityName, string backingFieldName, [NotNullWhen(true)] out string? name)
{
if (!EntityBackingColumnsToExposedNames.TryGetValue(entityName, out Dictionary<string, string>? backingToExposed))
{
throw new KeyNotFoundException($"Initialization of metadata incomplete for entity: {entityName}");
}
if (backingToExposed.TryGetValue(backingFieldName, out name))
{
return true;
}
if (Entities.TryGetValue(entityName, out Entity? entityDefinition) && entityDefinition.Fields is not null)
{
// Find the field by backing name and use its Alias if present.
FieldMetadata? matched = entityDefinition
.Fields
.FirstOrDefault(f => f.Name.Equals(backingFieldName, StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrEmpty(f.Alias));
if (matched is not null)
{
name = matched.Alias!;
return true;
}
}
name = null;
return false;
}
/// <inheritdoc />
public bool TryGetBackingColumn(string entityName, string field, [NotNullWhen(true)] out string? name)
{
Dictionary<string, string>? exposedNamesToBackingColumnsMap;
if (!EntityExposedNamesToBackingColumnNames.TryGetValue(entityName, out exposedNamesToBackingColumnsMap))
{
throw new KeyNotFoundException($"Initialization of metadata incomplete for entity: {entityName}");
}
if (exposedNamesToBackingColumnsMap.TryGetValue(field, out name))
{
return true;
}
if (Entities.TryGetValue(entityName, out Entity? entityDefinition) && entityDefinition.Fields is not null)
{
FieldMetadata? matchedField = entityDefinition.Fields.FirstOrDefault(f =>
f.Alias != null && f.Alias.Equals(field, StringComparison.OrdinalIgnoreCase));
if (matchedField is not null)
{
name = matchedField.Name;
return true;
}
}
return exposedNamesToBackingColumnsMap.TryGetValue(field, out name);
}
/// <inheritdoc />
public IReadOnlyDictionary<string, DatabaseObject> GetEntityNamesAndDbObjects()
{
return EntityToDatabaseObject;
}
/// <inheritdoc />
public string GetEntityName(string graphQLType)
{
if (Entities.ContainsKey(graphQLType))
{
return graphQLType;
}
foreach ((string entityName, Entity entity) in Entities)
{
if (entity.GraphQL.Singular == graphQLType)
{
return entityName;
}
}
throw new DataApiBuilderException(
"GraphQL type doesn't match any entity name or singular type in the runtime config.",
HttpStatusCode.BadRequest,
DataApiBuilderException.SubStatusCodes.BadRequest);
}
/// <inheritdoc />
public async Task InitializeAsync()
{
System.Diagnostics.Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
if (_isValidateOnly)
{
// Currently Validate mode only support single datasource,
// so using the below validation we can check connection once instead of checking for each entity.
// To enable to check for multiple data-sources just remove this validation and each entity will have its own connection check.
try
{
await ValidateDatabaseConnection();
}
catch (DataApiBuilderException e)
{
HandleOrRecordException(e);
return;
}
}
if (GetDatabaseType() == DatabaseType.MSSQL)
{
await GenerateAutoentitiesIntoEntities(Autoentities);
}
// Running these entity validations only in development mode to ensure
// fast startup of engine in production mode.
RuntimeConfig runtimeConfig = _runtimeConfigProvider.GetConfig();
_runtimeConfigValidator.ValidateEntityAndAutoentityConfigurations(runtimeConfig);
GenerateDatabaseObjectForEntities();
await PopulateObjectDefinitionForEntities();
GenerateExposedToBackingColumnMapsForEntities();
// When IsLateConfigured is true we are in a hosted scenario and do not reveal primary key information.
if (!_runtimeConfigProvider.IsLateConfigured)
{
LogPrimaryKeys();
}
GenerateRestPathToEntityMap();
InitODataParser();
if (_isValidateOnly)
{
RemoveGeneratedAutoentities();
}
timer.Stop();
_logger.LogTrace($"Done inferring Sql database schema in {timer.ElapsedMilliseconds}ms.");
}
/// <inheritdoc />
public void InitializeAsync(
Dictionary<string, DatabaseObject> entityToDatabaseObject,
Dictionary<string, string> graphQLStoredProcedureExposedNameToEntityNameMap)
{
EntityToDatabaseObject = entityToDatabaseObject ?? EntityToDatabaseObject;
GraphQLStoredProcedureExposedNameToEntityNameMap = graphQLStoredProcedureExposedNameToEntityNameMap ?? GraphQLStoredProcedureExposedNameToEntityNameMap;
GenerateExposedToBackingColumnMapsForEntities();
}
/// <inheritdoc/>
public bool TryGetExposedFieldToBackingFieldMap(string entityName, [NotNullWhen(true)] out IReadOnlyDictionary<string, string>? mappings)
{
Dictionary<string, string>? entityToColumnMappings;
mappings = null;
if (EntityExposedNamesToBackingColumnNames.TryGetValue(entityName, out entityToColumnMappings))
{
mappings = entityToColumnMappings;
return true;
}
return false;
}
/// <inheritdoc/>
public bool TryGetBackingFieldToExposedFieldMap(string entityName, [NotNullWhen(true)] out IReadOnlyDictionary<string, string>? mappings)
{
Dictionary<string, string>? columntoEntityMappings;
mappings = null;
if (EntityBackingColumnsToExposedNames.TryGetValue(entityName, out columntoEntityMappings))
{
mappings = columntoEntityMappings;
return true;
}
return false;
}
/// <summary>
/// Log Primary key information. Function only called when not
/// in a hosted scenario. Log relevant information about Primary keys
/// including backing and exposed names, type, isNullable, and isAutoGenerated.
/// </summary>
private void LogPrimaryKeys()
{
ColumnDefinition column;
foreach ((string entityName, Entity _) in Entities)
{
try
{
SourceDefinition sourceDefinition = GetSourceDefinition(entityName);
_logger.LogDebug("Logging primary key information for entity: {entityName}.", entityName);
foreach (string pK in sourceDefinition.PrimaryKey)
{
column = sourceDefinition.Columns[pK];
if (TryGetExposedColumnName(entityName, pK, out string? exposedPKeyName))
{
_logger.LogDebug(
message: "Primary key column name: {pK}\n" +
" Primary key mapped name: {exposedPKeyName}\n" +
" Type: {column.SystemType.Name}\n" +
" IsNullable: {column.IsNullable}\n" +
" IsAutoGenerated: {column.IsAutoGenerated}",
pK,
exposedPKeyName,
column.SystemType.Name,
column.IsNullable,
column.IsAutoGenerated);
}
}
}
catch (Exception ex)
{
HandleOrRecordException(new DataApiBuilderException(
message: $"Failed to log primary key information for entity: {entityName} due to: {ex.Message}",
innerException: ex,
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization));
}
}
}
/// <summary>
/// Verify that the stored procedure exists in the database schema, then populate its database object parameters accordingly
/// </summary>
protected virtual async Task FillSchemaForStoredProcedureAsync(
Entity procedureEntity,
string entityName,
string schemaName,
string storedProcedureSourceName,
StoredProcedureDefinition storedProcedureDefinition)
{
using ConnectionT conn = new();
conn.ConnectionString = ConnectionString;
DataTable procedureMetadata;
string[] procedureRestrictions = new string[NUMBER_OF_RESTRICTIONS];
try
{
await QueryExecutor.SetManagedIdentityAccessTokenIfAnyAsync(conn, _dataSourceName);
await conn.OpenAsync();
// To restrict the parameters for the current stored procedure, specify its name
procedureRestrictions[0] = conn.Database;
procedureRestrictions[1] = schemaName;
procedureRestrictions[2] = storedProcedureSourceName;
procedureMetadata = await conn.GetSchemaAsync(collectionName: "Procedures", restrictionValues: procedureRestrictions);
}
catch (Exception ex)
{
string message = $"Cannot obtain Schema for entity {entityName} " +
$"with underlying database object source: {schemaName}.{storedProcedureSourceName} " +
$"due to: {ex.Message}";
throw new DataApiBuilderException(
message: message,
innerException: ex,
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
// Stored procedure does not exist in DB schema
if (procedureMetadata.Rows.Count == 0)
{
throw new DataApiBuilderException(
message: $"No stored procedure definition found for the given database object {storedProcedureSourceName}",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
// Each row in the procedureParams DataTable corresponds to a single parameter
DataTable parameterMetadata = await conn.GetSchemaAsync(collectionName: "ProcedureParameters", restrictionValues: procedureRestrictions);
// For each row/parameter, add an entry to StoredProcedureDefinition.Parameters dictionary
foreach (DataRow row in parameterMetadata.Rows)
{
// row["DATA_TYPE"] has value type string so a direct cast to System.Type is not supported.
// See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings
string sqlType = (string)row["DATA_TYPE"];
Type systemType = SqlToCLRType(sqlType);
ParameterDefinition paramDefinition = new()
{
SystemType = systemType,
DbType = TypeHelper.GetDbTypeFromSystemType(systemType)
};
// Add to parameters dictionary without the leading @ sign
storedProcedureDefinition.Parameters.TryAdd(((string)row["PARAMETER_NAME"])[1..], paramDefinition);
}
// Loop through parameters specified in config, throw error if not found in schema
// else set runtime config defined default values.
// Note: we defer type checking of parameters specified in config until request time
List<ParameterMetadata>? configParameters = procedureEntity.Source.Parameters;
if (configParameters is not null)
{
foreach (ParameterMetadata paramMeta in configParameters)
{
string configParamKey = paramMeta.Name;
if (!storedProcedureDefinition.Parameters.TryGetValue(configParamKey, out ParameterDefinition? parameterDefinition))
{
HandleOrRecordException(new DataApiBuilderException(
message: $"Could not find parameter \"{configParamKey}\" specified in config for procedure \"{schemaName}.{storedProcedureSourceName}\"",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization));
}
else
{
// Map all metadata from config
parameterDefinition.Description = paramMeta.Description;
parameterDefinition.Required = paramMeta.Required;
parameterDefinition.Default = paramMeta.Default;
parameterDefinition.HasConfigDefault = paramMeta.Default is not null;
parameterDefinition.ConfigDefaultValue = paramMeta.Default?.ToString();
}
}
}
// Generating exposed stored-procedure query/mutation name and adding to the dictionary mapping it to its entity name.
GraphQLStoredProcedureExposedNameToEntityNameMap.TryAdd(GenerateStoredProcedureGraphQLFieldName(entityName, procedureEntity), entityName);
}
/// <summary>
/// Takes a string version of a sql data type and returns its .NET common language runtime (CLR) counterpart
/// </summary>
public abstract Type SqlToCLRType(string sqlType);
/// <summary>
/// Updates a table's SourceDefinition object's metadata with whether any enabled insert/update DML triggers exist for the table.
/// This method is only called for tables in MsSql.
/// </summary>
/// <param name="entityName">Name of the entity.</param>
/// <param name="schemaName">Name of the schema in which the table is present.</param>
/// <param name="tableName">Name of the table.</param>
/// <param name="sourceDefinition">Table definition to update.</param>
public virtual Task PopulateTriggerMetadataForTable(string entityName, string schemaName, string tableName, SourceDefinition sourceDefinition)
{
throw new NotImplementedException();
}
/// <summary>
/// Generates the map used to find a given entity based
/// on the path that will be used for that entity.
/// </summary>
private void GenerateRestPathToEntityMap()
{
RuntimeConfig runtimeConfig = _runtimeConfigProvider.GetConfig();
string graphQLGlobalPath = runtimeConfig.GraphQLPath;
foreach ((string entityName, Entity entity) in Entities)
{
try
{
string path = GetEntityPath(entity, entityName).TrimStart('/');
ValidateEntityAndGraphQLPathUniqueness(path, graphQLGlobalPath);
if (!string.IsNullOrEmpty(path))
{
// add the entity path name to the entity name mapping to the runtime config for multi-db resolution.
runtimeConfig.TryAddEntityPathNameToEntityName(path, entityName);
}
}
catch (Exception e)
{
HandleOrRecordException(e);
}
}
}
/// <summary>
/// Validate that an Entity's REST path does not conflict with the developer configured
/// or the internal default GraphQL path (/graphql).
/// </summary>
/// <param name="path">Entity's calculated REST path.</param>
/// <param name="graphQLGlobalPath">Developer configured GraphQL Path</param>
/// <exception cref="DataApiBuilderException"></exception>
public void ValidateEntityAndGraphQLPathUniqueness(string path, string graphQLGlobalPath)
{
// Handle case when path does not have forward slash (/) prefix
// by adding one if not present or ignoring an existing slash.
// entityName -> /entityName
// /entityName -> /entityName (no change)
if (!string.IsNullOrWhiteSpace(path) && path[0] != '/')
{
path = '/' + path;
}
if (string.Equals(path, graphQLGlobalPath, StringComparison.OrdinalIgnoreCase) ||
string.Equals(path, GraphQLRuntimeOptions.DEFAULT_PATH, StringComparison.OrdinalIgnoreCase))
{
HandleOrRecordException(new DataApiBuilderException(
message: "Entity's REST path conflicts with GraphQL reserved paths.",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError));
}
}
/// <summary>
/// Deserialize and return the entity's path.
/// </summary>
/// <param name="entity">Entity object to get the path of.</param>
/// <param name="entityName">name of the entity</param>
/// <returns>route for the given Entity.</returns>
private static string GetEntityPath(Entity entity, string entityName)
{
// if entity.Rest is null or it's enabled without a custom path, return the entity name
if (entity.Rest is null || (entity.Rest.Enabled && string.IsNullOrEmpty(entity.Rest.Path)))
{
return entityName;
}
// for false return empty string so we know not to add in caller
if (!entity.Rest.Enabled)
{
return string.Empty;
}
// otherwise return the custom path
return entity.Rest.Path!;
}
/// <summary>
/// Returns the default schema name. Throws exception here since
/// each derived class should override this method.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public virtual string GetDefaultSchemaName()
{
throw new NotSupportedException($"Cannot get default schema " +
$"name for database type {_databaseType}");
}
/// <summary>
/// Creates a Database object with the given schema and table names.
/// </summary>
protected virtual DatabaseTable GenerateDbTable(string schemaName, string tableName)
{
return new(schemaName, tableName);
}
/// <summary>
/// Builds the dictionary of parameters and their values required for the
/// foreign key query.
/// </summary>
/// <param name="schemaNames"></param>
/// <param name="tableNames"></param>
/// <returns>The dictionary populated with parameters.</returns>
protected virtual Dictionary<string, DbConnectionParam>
GetForeignKeyQueryParams(
string[] schemaNames,
string[] tableNames)
{
Dictionary<string, DbConnectionParam> parameters = new();
string[] schemaNameParams =
BaseSqlQueryBuilder.CreateParams(
kindOfParam: BaseSqlQueryBuilder.SCHEMA_NAME_PARAM,
schemaNames.Count());
string[] tableNameParams =
BaseSqlQueryBuilder.CreateParams(
kindOfParam: BaseSqlQueryBuilder.TABLE_NAME_PARAM,
tableNames.Count());
for (int i = 0; i < schemaNames.Count(); ++i)
{
parameters.Add(schemaNameParams[i], new(schemaNames[i], DbType.String));
}
for (int i = 0; i < tableNames.Count(); ++i)
{
parameters.Add(tableNameParams[i], new(tableNames[i], DbType.String));
}
return parameters;
}
/// <summary>
/// Create a DatabaseObject for all the exposed entities.
/// </summary>
private void GenerateDatabaseObjectForEntities()
{
Dictionary<string, DatabaseObject> sourceObjects = new();
foreach ((string entityName, Entity entity) in Entities)
{
PopulateDatabaseObjectForEntity(entity, entityName, sourceObjects);
}
}
/// <summary>
/// Creates entities for each table that is found, based on the autoentity configuration.
/// This method is only called for tables in MsSql.
/// </summary>
protected virtual Task GenerateAutoentitiesIntoEntities(IReadOnlyDictionary<string, Autoentity>? autoentities)
{
throw new NotSupportedException($"{GetType().Name} does not support autoentities yet.");
}
/// <summary>
/// Removes the entities that were generated from the autoentities property.
/// This should only be done when we only want to validate the entities.
/// </summary>
private void RemoveGeneratedAutoentities()
{
_runtimeConfigProvider.RemoveGeneratedAutoentitiesFromConfig();
}
protected void PopulateDatabaseObjectForEntity(
Entity entity,
string entityName,
Dictionary<string, DatabaseObject> sourceObjects)
{
try
{
EntitySourceType sourceType = GetEntitySourceType(entityName, entity);
if (!EntityToDatabaseObject.ContainsKey(entityName))
{
if (entity.Source.Object is null)
{
throw new DataApiBuilderException(
message: $"The entity {entityName} does not have a valid source object.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError);
}
// Reuse the same Database object for multiple entities if they share the same source.
if (!sourceObjects.TryGetValue(entity.Source.Object, out DatabaseObject? sourceObject))
{
// parse source name into a tuple of (schemaName, databaseObjectName)
(string schemaName, string dbObjectName) = ParseSchemaAndDbTableName(entity.Source.Object)!;
// if specified as stored procedure in config,
// initialize DatabaseObject as DatabaseStoredProcedure,
// else with DatabaseTable (for tables) / DatabaseView (for views).
if (sourceType is EntitySourceType.StoredProcedure)
{
sourceObject = new DatabaseStoredProcedure(schemaName, dbObjectName)
{
SourceType = sourceType,
StoredProcedureDefinition = new()
};
}
else if (sourceType is EntitySourceType.Table)
{
sourceObject = new DatabaseTable()
{
SchemaName = schemaName,
Name = dbObjectName,
SourceType = sourceType,
TableDefinition = new()
};
}
else
{
sourceObject = new DatabaseView(schemaName, dbObjectName)
{
SchemaName = schemaName,
Name = dbObjectName,
SourceType = sourceType,
ViewDefinition = new()
};
}
sourceObjects.Add(entity.Source.Object, sourceObject);
}
EntityToDatabaseObject.Add(entityName, sourceObject);
if (entity.Relationships is not null && entity.Source.Type is EntitySourceType.Table)
{
ProcessRelationships(entityName, entity, (DatabaseTable)sourceObject, sourceObjects);
}
}
}
catch (Exception e)
{
HandleOrRecordException(e);
}
}
/// <summary>
/// Get the EntitySourceType for the given entity or throw an exception if it is null.
/// </summary>
/// <param name="entityName">Name of the entity, used to provide info if an error is raised.</param>
/// <param name="entity">Entity to get the source type from.</param>
/// <returns>The non-nullable EntitySourceType.</returns>
/// <exception cref="DataApiBuilderException">If the EntitySourceType is null raise an exception as it is required for a SQL entity.</exception>
private static EntitySourceType GetEntitySourceType(string entityName, Entity entity)
{
return entity.Source.Type ??
throw new DataApiBuilderException(
$"The entity {entityName} does not have a source type. A null source type is only valid if the database type is CosmosDB_NoSQL.",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError);
}
/// <summary>
/// Adds a foreign key definition for each of the nested entities
/// specified in the relationships section of this entity
/// to gather the referencing and referenced columns from the database at a later stage.
/// Sets the referencing and referenced tables based on the kind of relationship.
/// A linking object encountered is used as the referencing table
/// for the foreign key definition.
/// When no foreign key is defined in the database for the relationship,
/// the relationship.source.fields and relationship.target.fields are mandatory.
/// Initializing a FKDefinition indicates to find the foreign key
/// between the referencing and referenced tables.
/// </summary>
/// <param name="entityName"></param>
/// <param name="entity"></param>
/// <param name="databaseTable"></param>
/// <exception cref="InvalidOperationException"></exception>
private void ProcessRelationships(
string entityName,
Entity entity,
DatabaseTable databaseTable,
Dictionary<string, DatabaseObject> sourceObjects)
{
SourceDefinition sourceDefinition = GetSourceDefinition(entityName);
if (!sourceDefinition.SourceEntityRelationshipMap
.TryGetValue(entityName, out RelationshipMetadata? relationshipData))
{
relationshipData = new();
sourceDefinition.SourceEntityRelationshipMap.Add(entityName, relationshipData);
}
string targetSchemaName, targetDbTableName, linkingTableSchema, linkingTableName;
foreach ((string relationshipName, EntityRelationship relationship) in entity.Relationships!)
{
string targetEntityName = relationship.TargetEntity;
if (!Entities.TryGetValue(targetEntityName, out Entity? targetEntity))
{
throw new InvalidOperationException($"Target Entity {targetEntityName} should be one of the exposed entities.");
}
if (targetEntity.Source.Object is null)
{
throw new DataApiBuilderException(
message: $"Target entity {entityName} does not have a valid source object.",
statusCode: HttpStatusCode.InternalServerError,
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError);
}
(targetSchemaName, targetDbTableName) = ParseSchemaAndDbTableName(targetEntity.Source.Object)!;
DatabaseTable targetDbTable = new(targetSchemaName, targetDbTableName);
// If a linking object is specified,
// give that higher preference and add two foreign keys for this targetEntity.
if (relationship.LinkingObject is not null)
{
(linkingTableSchema, linkingTableName) = ParseSchemaAndDbTableName(relationship.LinkingObject)!;
DatabaseTable linkingDbTable = new(linkingTableSchema, linkingTableName);
AddForeignKeyForTargetEntity(
sourceEntityName: entityName,
relationshipName: relationshipName,
targetEntityName: targetEntityName,
referencingDbTable: linkingDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.LinkingSourceFields,
referencedColumns: relationship.SourceFields,
referencingEntityRole: RelationshipRole.Linking,
referencedEntityRole: RelationshipRole.Source,
relationshipData: relationshipData);
AddForeignKeyForTargetEntity(
sourceEntityName: entityName,
relationshipName: relationshipName,
targetEntityName: targetEntityName,
referencingDbTable: linkingDbTable,
referencedDbTable: targetDbTable,
referencingColumns: relationship.LinkingTargetFields,
referencedColumns: relationship.TargetFields,
referencingEntityRole: RelationshipRole.Linking,
referencedEntityRole: RelationshipRole.Target,
relationshipData: relationshipData);
RuntimeConfig runtimeConfig = _runtimeConfigProvider.GetConfig();
// Populating metadata for linking object is only required when multiple create operation is enabled and those database types that support multiple create operation.
if (runtimeConfig.IsMultipleCreateOperationEnabled())
{
// When a linking object is encountered for a database table, we will create a linking entity for the object.
// Subsequently, we will also populate the Database object for the linking entity. This is used to infer
// metadata about linking object needed to create GQL schema for multiple insertions.
if (entity.Source.Type is EntitySourceType.Table)
{
PopulateMetadataForLinkingObject(
entityName: entityName,
targetEntityName: targetEntityName,
linkingObject: relationship.LinkingObject,
sourceObjects: sourceObjects);
}
}
}
else if (relationship.Cardinality == Cardinality.One)
{
// Example: books(Many) - publisher(One)
// where books.publisher_id is referencing publisher.id
// For Many-One OR One-One Relationships, DAB optimistically
// creates two ForeignKeyDefinitions to represent the relationship:
//
// #1
// Referencing Entity | Referenced Entity
// -------------------|-------------------
// Source Entity | Target Entity
//
// #2
// Referencing Entity | Referenced Entity
// -------------------|-------------------
// Target Entity | Source Entity
//
// One of the created ForeignKeyDefinitions correctly matches foreign key
// metadata in the database and DAB will later identify the correct
// ForeignKeyDefinition object when processing database schema metadata.
//
// When the runtime config doesn't specify how to relate these entities
// (via source/target fields), DAB expects to identity that one of
// the ForeignKeyDefinition objects will match foreign key metadata in the database.
// Create ForeignKeyDefinition #1
AddForeignKeyForTargetEntity(
sourceEntityName: entityName,
relationshipName: relationshipName,
targetEntityName,
referencingDbTable: databaseTable,
referencedDbTable: targetDbTable,
referencingColumns: relationship.SourceFields,
referencedColumns: relationship.TargetFields,
referencingEntityRole: RelationshipRole.Source,
referencedEntityRole: RelationshipRole.Target,
relationshipData);
// Create ForeignKeyDefinition #2
// when target and source entities differ (NOT self-referencing)
// because one ForeignKeyDefintion is sufficient to represent a self-joining relationship.
if (targetEntityName != entityName)
{
AddForeignKeyForTargetEntity(
sourceEntityName: entityName,
relationshipName: relationshipName,
targetEntityName,
referencingDbTable: targetDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.TargetFields,
referencedColumns: relationship.SourceFields,
referencingEntityRole: RelationshipRole.Target,
referencedEntityRole: RelationshipRole.Source,
relationshipData);
}
}
else if (relationship.Cardinality is Cardinality.Many)
{
// Example: publisher(One)-books(Many)
// where publisher.id is referenced by books.publisher_id
// For Many-Many relationships, DAB creates one
// ForeignKeyDefinition to represent the relationship:
//
// #1
// Referencing Entity | Referenced Entity
// -------------------|-------------------
// Target Entity | Source Entity
AddForeignKeyForTargetEntity(
sourceEntityName: entityName,
relationshipName: relationshipName,
targetEntityName,
referencingDbTable: targetDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.TargetFields,
referencedColumns: relationship.SourceFields,
referencingEntityRole: RelationshipRole.Target,
referencedEntityRole: RelationshipRole.Source,
relationshipData);
}
}
}
/// <summary>