Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions schemas/dab.draft.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,8 @@
},
"name": {
"type": "string",
"description": "Entity name interpolation pattern using {schema} and {object}. Null defaults to {object}. Must be unique for every entity inside the pattern",
"default": "{object}"
"description": "Entity name interpolation pattern using {schema} and {object}. Null defaults to {schema}_{object}. Must be unique for every entity inside the pattern",
"default": "{schema}_{object}"
}
}
},
Expand Down
2 changes: 1 addition & 1 deletion src/Cli/Commands/AutoConfigOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public AutoConfigOptions(
[Option("patterns.exclude", Required = false, HelpText = "T-SQL LIKE pattern(s) to exclude database objects. Space-separated array of patterns. Default: null")]
public IEnumerable<string>? PatternsExclude { get; }

[Option("patterns.name", Required = false, HelpText = "Interpolation syntax for entity naming (must be unique for each generated entity). Default: '{object}'")]
[Option("patterns.name", Required = false, HelpText = "Interpolation syntax for entity naming (must be unique for each generated entity). Default: '{schema}_{object}'")]
public string? PatternsName { get; }

[Option("template.mcp.dml-tools", Required = false, HelpText = "Enable/disable DML tools for generated entities. Allowed values: true, false. Default: true")]
Expand Down
2 changes: 1 addition & 1 deletion src/Config/ObjectModel/AutoentityPatterns.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public AutoentityPatterns(
}
else
{
this.Name = "{object}";
this.Name = "{schema}_{object}";
Comment thread
RubenCerna2079 marked this conversation as resolved.
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ protected override async Task GenerateAutoentitiesIntoEntities(IReadOnlyDictiona
// Currently the source type is always Table for auto-generated entities from database objects.
Entity generatedEntity = new(
Source: new EntitySource(
Object: objectName,
Object: $"{schemaName}.{objectName}",
Comment thread
RubenCerna2079 marked this conversation as resolved.
Type: EntitySourceType.Table,
Parameters: null,
KeyFields: null),
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<PackageVersion Include="Microsoft.Extensions.Primitives" Version="9.0.0" />
<PackageVersion Include="ModelContextProtocol" Version="1.0.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="1.0.0" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.13.0" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.3" />
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.13.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
Comment thread
RubenCerna2079 marked this conversation as resolved.
Expand Down
246 changes: 231 additions & 15 deletions src/Service.Tests/Configuration/ConfigurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5428,10 +5428,10 @@ public async Task TestGraphQLIntrospectionQueriesAreNotImpactedByDepthLimit()
}

/// <summary>
///
/// Ensures that autoentities are properly generated into in-memory entities
/// </summary>
/// <param name="useEntities"></param>
/// <param name="expectedEntityCount"></param>
/// <param name="useEntities">Boolean that indicates if we should also use regular entities from config</param>
/// <param name="expectedEntityCount">The expected number of entities</param>
/// <returns></returns>
[TestCategory(TestCategory.MSSQL)]
[DataTestMethod]
Expand Down Expand Up @@ -5536,12 +5536,12 @@ public async Task TestAutoentitiesAreGeneratedIntoEntities(bool useEntities, int
{
// Act
RuntimeConfigProvider configProvider = server.Services.GetService<RuntimeConfigProvider>();
using HttpRequestMessage restRequest = new(HttpMethod.Get, "/api/publishers");
using HttpRequestMessage restRequest = new(HttpMethod.Get, "/api/dbo_publishers");
using HttpResponseMessage restResponse = await client.SendAsync(restRequest);

string graphqlQuery = @"
{
publishers {
dbo_publishers {
items {
id
name
Expand Down Expand Up @@ -5580,20 +5580,236 @@ public async Task TestAutoentitiesAreGeneratedIntoEntities(bool useEntities, int
}

/// <summary>
///
/// This test validates that multiple autoentities with the same object name
/// but different schemas can be generated and accessed properly with the
/// default 'property.name' which should generate entities named '{schema}_{object}'.
/// </summary>
/// <param name="entityName"></param>
/// <param name="singular"></param>
/// <param name="plural"></param>
/// <param name="path"></param>
/// <param name="exceptionMessage"></param>
[TestCategory(TestCategory.MSSQL)]
[TestMethod]
public async Task TestAutoentitiesWithSameObjectDifferentSchemas()
{
// Arrange
Dictionary<string, Autoentity> autoentityMap = new()
{
{
"PublisherAutoEntity", new Autoentity(
Patterns: new AutoentityPatterns(
Include: null,
Exclude: new[] { "dbo.GQLmappings", "dbo.graphql_incompatible", "dbo.brokers" },
Name: null
),
Template: new AutoentityTemplate(
Rest: new EntityRestOptions(Enabled: true),
GraphQL: new EntityGraphQLOptions(
Singular: string.Empty,
Plural: string.Empty,
Enabled: true
),
Health: null,
Cache: null
),
Permissions: new[] { GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) }
)
}
};

// Create DataSource for MSSQL connection
DataSource dataSource = new(DatabaseType.MSSQL,
GetConnectionStringFromEnvironmentConfig(environment: TestCategory.MSSQL), Options: null);

// Build complete runtime configuration with autoentities
RuntimeConfig configuration = new(
Schema: "TestAutoentitiesSchema",
DataSource: dataSource,
Runtime: new(
Rest: new(Enabled: true),
GraphQL: new(Enabled: true),
Mcp: new(Enabled: false),
Host: new(
Cors: null,
Authentication: new Config.ObjectModel.AuthenticationOptions(
Provider: nameof(EasyAuthType.StaticWebApps),
Jwt: null
)
)
),
Entities: new(new Dictionary<string, Entity>()),
Autoentities: new RuntimeAutoentities(autoentityMap)
);

File.WriteAllText(CUSTOM_CONFIG_FILENAME, configuration.ToJson());

string[] args = new[] { $"--ConfigFileName={CUSTOM_CONFIG_FILENAME}" };

using (TestServer server = new(Program.CreateWebHostBuilder(args)))
using (HttpClient client = server.CreateClient())
{
// Act
using HttpRequestMessage restFooRequest = new(HttpMethod.Get, "/api/foo_magazines");
using HttpResponseMessage restFooResponse = await client.SendAsync(restFooRequest);

using HttpRequestMessage restBarRequest = new(HttpMethod.Get, "/api/bar_magazines");
using HttpResponseMessage restBarResponse = await client.SendAsync(restBarRequest);

string graphqlQuery = @"
{
foo_magazines {
items {
id
issue_number
}
}
bar_magazines {
items {
comic_name
issue
}
}
}";

object graphqlPayload = new { query = graphqlQuery };
HttpRequestMessage graphqlRequest = new(HttpMethod.Post, "/graphql")
{
Content = JsonContent.Create(graphqlPayload)
};
HttpResponseMessage graphqlResponse = await client.SendAsync(graphqlRequest);

Comment thread
RubenCerna2079 marked this conversation as resolved.
// Assert
// Verify REST response
Assert.AreEqual(HttpStatusCode.OK, restFooResponse.StatusCode, "REST request to auto-generated entity 'foo_magazines' should succeed");
Assert.AreEqual(HttpStatusCode.OK, restBarResponse.StatusCode, "REST request to auto-generated entity 'bar_magazines' should succeed");

// Verify GraphQL response
Assert.AreEqual(HttpStatusCode.OK, graphqlResponse.StatusCode, "GraphQL request to auto-generated entity should succeed");
}
}

/// <summary>
/// Ensures that autoentities are properly generated into in-memory entities when entities have non-default schemas.
/// </summary>
/// <param name="includePattern">The pattern to include for autoentities</param>
/// <param name="isPatternFoo">Boolean that indicates if the pattern is for the foo schema</param>
/// <returns></returns>
[TestCategory(TestCategory.MSSQL)]
[DataTestMethod]
[DataRow("foo.%", true, DisplayName = "Test Autoentities with foo schema")]
[DataRow("bar.%", false, DisplayName = "Test Autoentities with bar schema")]
public async Task TestAutoentitiesGeneratedWithDifferentSchemas(string includePattern, bool isPatternFoo)
{
// Arrange
Dictionary<string, Autoentity> autoentityMap = new()
{
{
"PublisherAutoEntity", new Autoentity(
Patterns: new AutoentityPatterns(
Include: new[] { includePattern },
Exclude: null,
Name: null
),
Template: new AutoentityTemplate(
Rest: new EntityRestOptions(Enabled: true),
GraphQL: new EntityGraphQLOptions(
Singular: string.Empty,
Plural: string.Empty,
Enabled: true
),
Health: null,
Cache: null
),
Permissions: new[] { GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) }
)
}
};

// Create DataSource for MSSQL connection
DataSource dataSource = new(DatabaseType.MSSQL,
GetConnectionStringFromEnvironmentConfig(environment: TestCategory.MSSQL), Options: null);

// Build complete runtime configuration with autoentities
RuntimeConfig configuration = new(
Schema: "TestAutoentitiesSchema",
DataSource: dataSource,
Runtime: new(
Rest: new(Enabled: true),
GraphQL: new(Enabled: true),
Mcp: new(Enabled: false),
Host: new(
Cors: null,
Authentication: new Config.ObjectModel.AuthenticationOptions(
Provider: nameof(EasyAuthType.StaticWebApps),
Jwt: null
)
)
),
Entities: new(new Dictionary<string, Entity>()),
Autoentities: new RuntimeAutoentities(autoentityMap)
);

File.WriteAllText(CUSTOM_CONFIG_FILENAME, configuration.ToJson());

string[] args = new[] { $"--ConfigFileName={CUSTOM_CONFIG_FILENAME}" };
using (TestServer server = new(Program.CreateWebHostBuilder(args)))
using (HttpClient client = server.CreateClient())
{
// Act
string path = isPatternFoo ? "foo_magazines" : "bar_magazines";
using HttpRequestMessage restRequest = new(HttpMethod.Get, $"/api/{path}");
using HttpResponseMessage restResponse = await client.SendAsync(restRequest);

string item = isPatternFoo ? "title" : "comic_name";
string graphqlQuery = $@"
{{
{path} {{
items {{
{item}
}}
}}
}}";

object graphqlPayload = new { query = graphqlQuery };
HttpRequestMessage graphqlRequest = new(HttpMethod.Post, "/graphql")
{
Content = JsonContent.Create(graphqlPayload)
};
HttpResponseMessage graphqlResponse = await client.SendAsync(graphqlRequest);

// Assert
string expectedResponseFragment = isPatternFoo ? @"""title"":""Vogue""" : @"""comic_name"":""NotVogue""";

// Verify REST response
Assert.AreEqual(HttpStatusCode.OK, restResponse.StatusCode, "REST request to auto-generated entity should succeed");

string restResponseBody = await restResponse.Content.ReadAsStringAsync();
Assert.IsTrue(!string.IsNullOrEmpty(restResponseBody), "REST response should contain data");
Assert.IsTrue(restResponseBody.Contains(expectedResponseFragment));

// Verify GraphQL response
Assert.AreEqual(HttpStatusCode.OK, graphqlResponse.StatusCode, "GraphQL request to auto-generated entity should succeed");

string graphqlResponseBody = await graphqlResponse.Content.ReadAsStringAsync();
Assert.IsTrue(!string.IsNullOrEmpty(graphqlResponseBody), "GraphQL response should contain data");
Assert.IsFalse(graphqlResponseBody.Contains("errors"), "GraphQL response should not contain errors");
Assert.IsTrue(graphqlResponseBody.Contains(expectedResponseFragment));
}
}

/// <summary>
/// Tests that DAB fails if the entities generated from autoentities property
/// do not contain unique parameters such as rest path, graphql singular/plural names,
/// or if the autoentity pattern conflicts with an existing entity name.
/// </summary>
/// <param name="entityName">Definition name of the generated entity from autoentities</param>
/// <param name="singular">GraphQL singular name of the generated entity from autoentities</param>
/// <param name="plural">GraphQL plural name of the generated entity from autoentities</param>
/// <param name="path">REST path of the generated entity from autoentities</param>
/// <param name="exceptionMessage">Expected exception message</param>
/// <returns></returns>
[TestCategory(TestCategory.MSSQL)]
[DataTestMethod]
[DataRow("publishers", "uniqueSingularPublisher", "uniquePluralPublishers", "/unique/publisher", "Entity 'publishers' conflicts with autoentity pattern 'PublisherAutoEntity'. Use --patterns.exclude to skip it.", DisplayName = "Autoentities fail due to entity name")]
[DataRow("UniquePublisher", "publishers", "uniquePluralPublishers", "/unique/publisher", "Entity publishers generates queries/mutation that already exist", DisplayName = "Autoentities fail due to graphql singular type")]
[DataRow("UniquePublisher", "uniqueSingularPublisher", "publishers", "/unique/publisher", "Entity publishers generates queries/mutation that already exist", DisplayName = "Autoentities fail due to graphql plural type")]
[DataRow("UniquePublisher", "uniqueSingularPublisher", "uniquePluralPublishers", "/publishers", "The rest path: publishers specified for entity: publishers is already used by another entity.", DisplayName = "Autoentities fail due to rest path")]
[DataRow("dbo_publishers", "uniqueSingularPublisher", "uniquePluralPublishers", "/unique/publisher", "Entity 'dbo_publishers' conflicts with autoentity pattern 'PublisherAutoEntity'. Use --patterns.exclude to skip it.", DisplayName = "Autoentities fail due to entity name")]
[DataRow("UniquePublisher", "dbo_publishers", "uniquePluralPublishers", "/unique/publisher", "Entity dbo_publishers generates queries/mutation that already exist", DisplayName = "Autoentities fail due to graphql singular type")]
[DataRow("UniquePublisher", "uniqueSingularPublisher", "dbo_publishers", "/unique/publisher", "Entity dbo_publishers generates queries/mutation that already exist", DisplayName = "Autoentities fail due to graphql plural type")]
[DataRow("UniquePublisher", "uniqueSingularPublisher", "uniquePluralPublishers", "/dbo_publishers", "The rest path: dbo_publishers specified for entity: dbo_publishers is already used by another entity.", DisplayName = "Autoentities fail due to rest path")]
public async Task ValidateAutoentityGenerationConflicts(string entityName, string singular, string plural, string path, string exceptionMessage)
{
// Arrange
Expand Down
Loading