-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathSqlMetadataProvider.cs
More file actions
1515 lines (1361 loc) · 70.5 KB
/
SqlMetadataProvider.cs
File metadata and controls
1515 lines (1361 loc) · 70.5 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;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Service.Configurations;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.Models;
using Azure.DataApiBuilder.Service.Parsers;
using Azure.DataApiBuilder.Service.Resolvers;
using Microsoft.Extensions.Logging;
using static Azure.DataApiBuilder.Service.GraphQLBuilder.GraphQLNaming;
namespace Azure.DataApiBuilder.Service.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;
private readonly Dictionary<string, Entity> _entities;
// Dictionary mapping singular graphql types to entity name keys in the configuration
private readonly Dictionary<string, string> _graphQLSingularTypeToEntityNameMap = new();
// 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; }
protected IQueryExecutor QueryExecutor { get; }
private 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 Dictionary<string, Dictionary<string, string>> EntityBackingColumnsToExposedNames { get; } = new();
private Dictionary<string, Dictionary<string, string>> EntityExposedNamesToBackingColumnNames { get; } = new();
private Dictionary<string, string> EntityPathToEntityName { get; } = new();
/// <summary>
/// Maps an entity name to a DatabaseObject.
/// </summary>
public Dictionary<string, DatabaseObject> EntityToDatabaseObject { get; set; } =
new(StringComparer.InvariantCulture);
private readonly ILogger<ISqlMetadataProvider> _logger;
public SqlMetadataProvider(
RuntimeConfigProvider runtimeConfigProvider,
IQueryExecutor queryExecutor,
IQueryBuilder queryBuilder,
ILogger<ISqlMetadataProvider> logger)
{
RuntimeConfig runtimeConfig = runtimeConfigProvider.GetRuntimeConfiguration();
_runtimeConfigProvider = runtimeConfigProvider;
_databaseType = runtimeConfig.DatabaseType;
_entities = runtimeConfig.Entities;
_graphQLSingularTypeToEntityNameMap = runtimeConfig.GraphQLSingularTypeToEntityNameMap;
_logger = logger;
foreach (KeyValuePair<string, Entity> entity in _entities)
{
entity.Value.TryPopulateSourceFields();
if (runtimeConfigProvider.GetRuntimeConfiguration().RestGlobalSettings.Enabled)
{
_logger.LogInformation($"{entity.Key} path: {runtimeConfigProvider.RestPath}/{entity.Key}");
}
else
{
_logger.LogInformation($"REST calls are disabled for Entity: {entity.Key}");
}
}
ConnectionString = runtimeConfig.ConnectionString;
EntitiesDataSet = new();
SqlQueryBuilder = queryBuilder;
QueryExecutor = queryExecutor;
}
/// <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;
}
/// <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, out string? name)
{
return EntityBackingColumnsToExposedNames[entityName].TryGetValue(backingFieldName, out name);
}
/// <inheritdoc />
public bool TryGetBackingColumn(string entityName, string field, [NotNullWhen(true)] out string? name)
{
return EntityExposedNamesToBackingColumnNames[entityName].TryGetValue(field, out name);
}
/// <inheritdoc />
public virtual bool TryGetEntityNameFromPath(string entityPathName, [NotNullWhen(true)] out string? entityName)
{
return EntityPathToEntityName.TryGetValue(entityPathName, out entityName);
}
/// <inheritdoc />
public IDictionary<string, DatabaseObject> GetEntityNamesAndDbObjects()
{
return EntityToDatabaseObject;
}
/// <inheritdoc />
public string GetEntityName(string graphQLType)
{
if (_entities.ContainsKey(graphQLType))
{
return graphQLType;
}
if (!_graphQLSingularTypeToEntityNameMap.TryGetValue(graphQLType, out string? entityName))
{
throw new DataApiBuilderException(
"GraphQL type doesn't match any entity name or singular type in the runtime config.",
System.Net.HttpStatusCode.BadRequest,
DataApiBuilderException.SubStatusCodes.BadRequest);
}
return entityName!;
}
/// <inheritdoc />
public async Task InitializeAsync()
{
System.Diagnostics.Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
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();
timer.Stop();
_logger.LogTrace($"Done inferring Sql database schema in {timer.ElapsedMilliseconds}ms.");
}
/// <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 in _entities.Keys)
{
SourceDefinition sourceDefinition = GetSourceDefinition(entityName);
_logger.LogDebug($"Logging primary key information for entity: {entityName}.");
foreach (string pK in sourceDefinition.PrimaryKey)
{
string? exposedPKeyName;
column = sourceDefinition.Columns[pK];
if (TryGetExposedColumnName(entityName, pK, out exposedPKeyName))
{
_logger.LogDebug($"Primary key column name: {pK}\n" +
$" Primary key mapped name: {exposedPKeyName}\n" +
$" Type: {column.SystemType.Name}\n" +
$" IsNullable: {column.IsNullable}\n" +
$" IsAutoGenerated: {column.IsAutoGenerated}");
}
}
}
}
/// <summary>
/// Verify that the stored procedure exists in the database schema, then populate its database object parameters accordingly
/// </summary>
private async Task FillSchemaForStoredProcedureAsync(
Entity procedureEntity,
string entityName,
string schemaName,
string storedProcedureSourceName,
StoredProcedureDefinition storedProcedureDefinition)
{
using ConnectionT conn = new();
conn.ConnectionString = ConnectionString;
await QueryExecutor.SetManagedIdentityAccessTokenIfAnyAsync(conn);
await conn.OpenAsync();
string tablePrefix = GetTablePrefix(conn.Database, schemaName);
string[] procedureRestrictions = new string[NUMBER_OF_RESTRICTIONS];
// To restrict the parameters for the current stored procedure, specify its name
procedureRestrictions[0] = conn.Database;
procedureRestrictions[1] = schemaName;
procedureRestrictions[2] = storedProcedureSourceName;
DataTable procedureMetadata = await conn.GetSchemaAsync(collectionName: "Procedures", restrictionValues: procedureRestrictions);
// 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.
Type systemType = SqlToCLRType((string)row["DATA_TYPE"]);
// Add to parameters dictionary without the leading @ sign
storedProcedureDefinition.Parameters.TryAdd(((string)row["PARAMETER_NAME"])[1..],
new()
{
SystemType = systemType,
DbType = TypeHelper.GetDbTypeFromSystemType(systemType)
}
);
}
// 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
Dictionary<string, object>? configParameters = procedureEntity.Parameters;
if (configParameters is not null)
{
foreach ((string configParamKey, object configParamValue) in configParameters)
{
if (!storedProcedureDefinition.Parameters.TryGetValue(configParamKey, out ParameterDefinition? parameterDefinition))
{
throw new DataApiBuilderException(
message: $"Could not find parameter \"{configParamKey}\" specified in config for procedure \"{schemaName}.{storedProcedureSourceName}\"",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
else
{
parameterDefinition.HasConfigDefault = true;
parameterDefinition.ConfigDefaultValue = configParamValue is null ? null : configParamValue.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>
/// 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.GetRuntimeConfiguration();
string graphQLGlobalPath = runtimeConfig.GraphQLGlobalSettings.Path;
foreach (string entityName in _entities.Keys)
{
Entity entity = _entities[entityName];
string path = GetEntityPath(entity, entityName).TrimStart('/');
ValidateEntityAndGraphQLPathUniqueness(path, graphQLGlobalPath);
if (!string.IsNullOrEmpty(path))
{
EntityPathToEntityName[path] = entityName;
}
}
}
/// <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 static 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, GlobalSettings.GRAPHQL_DEFAULT_PATH, StringComparison.OrdinalIgnoreCase))
{
throw 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 true we just use entity name
if (entity.Rest is null || ((JsonElement)entity.Rest).ValueKind is JsonValueKind.True)
{
return entityName;
}
// for false return empty string so we know not to add in caller
if (((JsonElement)entity.Rest).ValueKind is JsonValueKind.False)
{
return string.Empty;
}
// otherwise we have to convert each part of the Rest property we want into correct objects
// they are json element so this means deserializing at each step with case insensitivity
JsonSerializerOptions options = RuntimeConfig.SerializerOptions;
JsonElement restConfigElement = (JsonElement)entity.Rest;
if (entity.ObjectType is SourceType.StoredProcedure)
{
if (restConfigElement.TryGetProperty("path", out JsonElement path))
{
if (path.ValueKind is JsonValueKind.True || path.ValueKind is JsonValueKind.False)
{
bool restEnabled = JsonSerializer.Deserialize<bool>(path, options)!;
if (restEnabled)
{
return entityName;
}
else
{
return string.Empty;
}
}
else
{
return JsonSerializer.Deserialize<string>(path, options)!;
}
}
else
{
return entityName;
}
}
else
{
RestEntitySettings rest = JsonSerializer.Deserialize<RestEntitySettings>((JsonElement)restConfigElement, options)!;
if (rest.Path is not null)
{
return JsonSerializer.Deserialize<string>((JsonElement)rest.Path, options)!;
}
else
{
return entityName;
}
}
}
/// <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()
{
string schemaName, dbObjectName;
Dictionary<string, DatabaseObject> sourceObjects = new();
foreach ((string entityName, Entity entity)
in _entities)
{
if (!EntityToDatabaseObject.ContainsKey(entityName))
{
// Reuse the same Database object for multiple entities if they share the same source.
if (!sourceObjects.TryGetValue(entity.SourceName, out DatabaseObject? sourceObject))
{
// parse source name into a tuple of (schemaName, databaseObjectName)
(schemaName, dbObjectName) = ParseSchemaAndDbTableName(entity.SourceName)!;
// if specified as stored procedure in config,
// initialize DatabaseObject as DatabaseStoredProcedure,
// else with DatabaseTable (for tables) / DatabaseView (for views).
if (entity.ObjectType is SourceType.StoredProcedure)
{
sourceObject = new DatabaseStoredProcedure(schemaName, dbObjectName)
{
SourceType = entity.ObjectType,
StoredProcedureDefinition = new()
};
}
else if (entity.ObjectType is SourceType.Table)
{
sourceObject = new DatabaseTable()
{
SchemaName = schemaName,
Name = dbObjectName,
SourceType = entity.ObjectType,
TableDefinition = new()
};
}
else
{
sourceObject = new DatabaseView(schemaName, dbObjectName)
{
SchemaName = schemaName,
Name = dbObjectName,
SourceType = entity.ObjectType,
ViewDefinition = new()
};
}
sourceObjects.Add(entity.SourceName, sourceObject);
}
EntityToDatabaseObject.Add(entityName, sourceObject);
if (entity.Relationships is not null && entity.ObjectType is SourceType.Table)
{
AddForeignKeysForRelationships(entityName, entity, (DatabaseTable)sourceObject);
}
}
}
}
/// <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.
/// If encounter a linking object, use that as the referencing table
/// for the foreign key definition.
/// There may not be a foreign key defined on the backend in which case
/// the relationship.source.fields and relationship.target fields are mandatory.
/// Initializing a definition here is an indication 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 AddForeignKeysForRelationships(
string entityName,
Entity entity,
DatabaseTable databaseTable)
{
RelationshipMetadata? relationshipData;
SourceDefinition sourceDefinition = GetSourceDefinition(entityName);
if (!sourceDefinition.SourceEntityRelationshipMap
.TryGetValue(entityName, out relationshipData))
{
relationshipData = new();
sourceDefinition.SourceEntityRelationshipMap.Add(entityName, relationshipData);
}
string targetSchemaName, targetDbTableName, linkingTableSchema, linkingTableName;
foreach (Relationship relationship in entity.Relationships!.Values)
{
string targetEntityName = relationship.TargetEntity;
if (!_entities.TryGetValue(targetEntityName, out Entity? targetEntity))
{
throw new InvalidOperationException($"Target Entity {targetEntityName} should be one of the exposed entities.");
}
(targetSchemaName, targetDbTableName) = ParseSchemaAndDbTableName(targetEntity.SourceName)!;
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(
targetEntityName,
referencingDbTable: linkingDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.LinkingSourceFields,
referencedColumns: relationship.SourceFields,
relationshipData);
AddForeignKeyForTargetEntity(
targetEntityName,
referencingDbTable: linkingDbTable,
referencedDbTable: targetDbTable,
referencingColumns: relationship.LinkingTargetFields,
referencedColumns: relationship.TargetFields,
relationshipData);
}
else if (relationship.Cardinality == Cardinality.One)
{
// For Many-One OR One-One Relationships, optimistically
// add foreign keys from either sides in the hopes of finding their metadata
// at a later stage when we query the database about foreign keys.
// Both or either of these may be present if its a One-One relationship,
// The second fk would not be present if its a Many-One relationship.
// When the configuration file doesn't specify how to relate these entities,
// at least 1 of the following foreign keys should be present.
// Adding this foreign key in the hopes of finding a foreign key
// in the underlying database object of the source entity referencing
// the target entity.
// This foreign key may NOT exist for either of the following reasons:
// a. this source entity is related to the target entity in an One-to-One relationship
// but the foreign key was added to the target entity's underlying source
// This is covered by the foreign key below.
// OR
// b. no foreign keys were defined at all.
AddForeignKeyForTargetEntity(
targetEntityName,
referencingDbTable: databaseTable,
referencedDbTable: targetDbTable,
referencingColumns: relationship.SourceFields,
referencedColumns: relationship.TargetFields,
relationshipData);
// Adds another foreign key defintion with targetEntity.GetSourceName()
// as the referencingTableName - in the situation of a One-to-One relationship
// and the foreign key is defined in the source of targetEntity.
// This foreign key WILL NOT exist if its a Many-One relationship.
AddForeignKeyForTargetEntity(
targetEntityName,
referencingDbTable: targetDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.TargetFields,
referencedColumns: relationship.SourceFields,
relationshipData);
}
else if (relationship.Cardinality is Cardinality.Many)
{
// Case of publisher(One)-books(Many)
// we would need to obtain the foreign key information from the books table
// about the publisher id so we can do the join.
// so, the referencingTable is the source of the target entity.
AddForeignKeyForTargetEntity(
targetEntityName,
referencingDbTable: targetDbTable,
referencedDbTable: databaseTable,
referencingColumns: relationship.TargetFields,
referencedColumns: relationship.SourceFields,
relationshipData);
}
}
}
/// <summary>
/// Adds a new foreign key definition for the target entity
/// in the relationship metadata.
/// </summary>
private static void AddForeignKeyForTargetEntity(
string targetEntityName,
DatabaseTable referencingDbTable,
DatabaseTable referencedDbTable,
string[]? referencingColumns,
string[]? referencedColumns,
RelationshipMetadata relationshipData)
{
ForeignKeyDefinition foreignKeyDefinition = new()
{
Pair = new()
{
ReferencingDbTable = referencingDbTable,
ReferencedDbTable = referencedDbTable
}
};
if (referencingColumns is not null)
{
foreignKeyDefinition.ReferencingColumns.AddRange(referencingColumns);
}
if (referencedColumns is not null)
{
foreignKeyDefinition.ReferencedColumns.AddRange(referencedColumns);
}
if (relationshipData
.TargetEntityToFkDefinitionMap.TryGetValue(targetEntityName, out List<ForeignKeyDefinition>? foreignKeys))
{
foreignKeys.Add(foreignKeyDefinition);
}
else
{
relationshipData.TargetEntityToFkDefinitionMap
.Add(targetEntityName,
new List<ForeignKeyDefinition>() { foreignKeyDefinition });
}
}
/// <summary>
/// Helper function will parse the schema and database object name
/// from the provided source string and sort out if a default schema
/// should be used.
/// </summary>
/// <param name="source">source string to parse</param>
/// <returns>The appropriate schema and db object name as a tuple of strings.</returns>
/// <exception cref="DataApiBuilderException"></exception>
public (string, string) ParseSchemaAndDbTableName(string source)
{
(string? schemaName, string dbTableName) = EntitySourceNamesParser.ParseSchemaAndTable(source)!;
// if schemaName is empty we check if the DB type is postgresql
// and if the schema name was included in the connection string
// as a value associated with the keyword 'SearchPath'.
// if the DB type is not postgresql or if the connection string
// does not include the schema name, we use the default schema name.
// if schemaName is not empty we must check if Database Type is MySql
// and in this case we throw an exception since there should be no
// schema name in this case.
if (string.IsNullOrEmpty(schemaName))
{
// if DatabaseType is not postgresql will short circuit and use default
if (_databaseType is not DatabaseType.postgresql ||
!PostgreSqlMetadataProvider.TryGetSchemaFromConnectionString(
connectionString: ConnectionString,
out schemaName))
{
schemaName = GetDefaultSchemaName();
}
}
else if (_databaseType is DatabaseType.mysql)
{
throw new DataApiBuilderException(message: $"Invalid database object name: \"{schemaName}.{dbTableName}\"",
statusCode: System.Net.HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
return (schemaName, dbTableName);
}
/// <inheritdoc />
public List<string> GetSchemaGraphQLFieldNamesForEntityName(string entityName)
=> throw new NotImplementedException();
/// <inheritdoc />
public string? GetSchemaGraphQLFieldTypeFromFieldName(string graphQLType, string fieldName)
=> throw new NotImplementedException();
/// <summary>
/// Enrich the entities in the runtime config with the
/// object definition information needed by the runtime to serve requests.
/// Populates table definition for entities specified as tables or views
/// Populates procedure definition for entities specified as stored procedures
/// </summary>
private async Task PopulateObjectDefinitionForEntities()
{
foreach ((string entityName, Entity entity) in _entities)
{
SourceType entitySourceType = entity.ObjectType;
if (entitySourceType is SourceType.StoredProcedure)
{
await FillSchemaForStoredProcedureAsync(
entity,
entityName,
GetSchemaName(entityName),
GetDatabaseObjectName(entityName),
GetStoredProcedureDefinition(entityName));
if (GetDatabaseType() == DatabaseType.mssql)
{
await PopulateResultSetDefinitionsForStoredProcedureAsync(
GetSchemaName(entityName),
GetDatabaseObjectName(entityName),
GetStoredProcedureDefinition(entityName));
}
}
else if (entitySourceType is SourceType.Table)
{
await PopulateSourceDefinitionAsync(
entityName,
GetSchemaName(entityName),
GetDatabaseObjectName(entityName),
GetSourceDefinition(entityName),
entity.KeyFields);
}
else
{
ViewDefinition viewDefinition = (ViewDefinition)GetSourceDefinition(entityName);
await PopulateSourceDefinitionAsync(
entityName,
GetSchemaName(entityName),
GetDatabaseObjectName(entityName),
viewDefinition,
entity.KeyFields);
}
}
await PopulateForeignKeyDefinitionAsync();
}
/// <summary>
/// Queries DB to get the result fields name and type to
/// populate the result set definition for entities specified as stored procedures
/// </summary>
private async Task PopulateResultSetDefinitionsForStoredProcedureAsync(
string schemaName,
string storedProcedureName,
SourceDefinition sourceDefinition)
{
StoredProcedureDefinition storedProcedureDefinition = (StoredProcedureDefinition)sourceDefinition;
string dbStoredProcedureName = $"{schemaName}.{storedProcedureName}";
// Generate query to get result set details
// of the stored procedure.
string queryForResultSetDetails = SqlQueryBuilder.BuildStoredProcedureResultDetailsQuery(
dbStoredProcedureName);
// Execute the query to get columns' details.
JsonArray? resultArray = await QueryExecutor.ExecuteQueryAsync(
sqltext: queryForResultSetDetails,
parameters: null!,
dataReaderHandler: QueryExecutor.GetJsonArrayAsync);
using JsonDocument sqlResult = JsonDocument.Parse(resultArray!.ToJsonString());
// Iterate through each row returned by the query which corresponds to
// one row in the result set.
foreach (JsonElement element in sqlResult.RootElement.EnumerateArray())
{
string resultFieldName = element.GetProperty("result_field_name").ToString();
Type resultFieldType = SqlToCLRType(element.GetProperty("result_type").ToString());
bool isResultFieldNullable = element.GetProperty("is_nullable").GetBoolean();
// Store the dictionary containing result set field with its type as Columns
storedProcedureDefinition.Columns.TryAdd(resultFieldName, new(resultFieldType) { IsNullable = isResultFieldNullable });
}
}
/// <summary>
/// Helper method to create params for the query.
/// </summary>
/// <param name="paramName">Common prefix of param names.</param>
/// <param name="paramValues">Values of the param.</param>
/// <returns></returns>
private static Dictionary<string, object> GetQueryParams(
string paramName,
object[] paramValues)
{
Dictionary<string, object> parameters = new();
for (int paramNumber = 0; paramNumber < paramValues.Length; paramNumber++)
{
parameters.Add($"{paramName}{paramNumber}", paramValues[paramNumber]);
}
return parameters;
}
/// <summary>
/// Generate the mappings of exposed names to
/// backing columns, and of backing columns to
/// exposed names. Used to generate EDM Model using
/// the exposed names, and to translate between
/// exposed name and backing column (or the reverse)
/// when needed while processing the request.
/// For now, only do this for tables/views as Stored Procedures do not have a SourceDefinition
/// In the future, mappings for SPs could be used for parameter renaming.
/// We also handle logging the primary key information here since this is when we first have
/// the exposed names suitable for logging.
/// </summary>
private void GenerateExposedToBackingColumnMapsForEntities()
{
foreach (string entityName in _entities.Keys)
{
// InCase of StoredProcedures, result set definitions becomes the column definition.
Dictionary<string, string>? mapping = GetMappingForEntity(entityName);
EntityBackingColumnsToExposedNames[entityName] = mapping is not null ? mapping : new();
EntityExposedNamesToBackingColumnNames[entityName] = EntityBackingColumnsToExposedNames[entityName].ToDictionary(x => x.Value, x => x.Key);
SourceDefinition sourceDefinition = GetSourceDefinition(entityName);
foreach (string columnName in sourceDefinition.Columns.Keys)
{
if (!EntityExposedNamesToBackingColumnNames[entityName].ContainsKey(columnName) && !EntityBackingColumnsToExposedNames[entityName].ContainsKey(columnName))
{
EntityBackingColumnsToExposedNames[entityName].Add(columnName, columnName);
EntityExposedNamesToBackingColumnNames[entityName].Add(columnName, columnName);
}
}
}
}
/// <summary>
/// Obtains the underlying mapping that belongs
/// to a given entity.
/// </summary>
/// <param name="entityName">entity whose map we get.</param>
/// <returns>mapping belonging to eneity.</returns>
private Dictionary<string, string>? GetMappingForEntity(string entityName)
{
_entities.TryGetValue(entityName, out Entity? entity);
return entity is not null ? entity.Mappings : null;
}
/// <summary>
/// Initialize OData parser by buidling OData model.
/// The parser will be used for parsing filter clause and order by clause.
/// </summary>
private void InitODataParser()
{
_oDataParser.BuildModel(this);
}
/// <summary>
/// Fills the table definition with information of all columns and
/// primary keys.
/// </summary>
/// <param name="schemaName">Name of the schema.</param>
/// <param name="tableName">Name of the table.</param>
/// <param name="sourceDefinition">Table definition to fill.</param>
/// <param name="entityName">EntityName included to pass on for error messaging.</param>
private async Task PopulateSourceDefinitionAsync(
string entityName,
string schemaName,
string tableName,
SourceDefinition sourceDefinition,
string[]? runtimeConfigKeyFields)
{
DataTable dataTable = await GetTableWithSchemaFromDataSetAsync(entityName, schemaName, tableName);
List<DataColumn> primaryKeys = new(dataTable.PrimaryKey);
if (runtimeConfigKeyFields is null || runtimeConfigKeyFields.Length == 0)
{
sourceDefinition.PrimaryKey = new(primaryKeys.Select(primaryKey => primaryKey.ColumnName));
}
else
{
sourceDefinition.PrimaryKey = new(runtimeConfigKeyFields);
}
if (sourceDefinition.PrimaryKey.Count == 0)
{
throw new DataApiBuilderException(
message: $"Primary key not configured on the given database object {tableName}",
statusCode: HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
using DataTableReader reader = new(dataTable);
DataTable schemaTable = reader.GetSchemaTable();
RuntimeConfig runtimeConfig = _runtimeConfigProvider.GetRuntimeConfiguration();
foreach (DataRow columnInfoFromAdapter in schemaTable.Rows)
{