diff --git a/README.md b/README.md index 4d4a18a..95ebff0 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,22 @@ IDictionary sqlParams = result.Item2; See Unit tests for more examples +### Column names with special characters +OData identifiers only allow letters, digits and `_`. Escape any other character as `_xHHHH_` (the `XmlConvert.EncodeName` format), e.g. `Closed_x0020__x0028_UTC_x0029_` for `Closed (UTC)` or `_x0032_TableName` for `2TableName`. Escaped names are decoded and always emitted as quoted identifiers. + +Names that decode to a control character or to `.` `?` `{` `}` `[` `]` `\` throw `NotSupportedException`, because SqlKata treats these as syntax even inside quoted identifiers. + +### Thread safety +`ODataToSqlConverter` and `EdmModelBuilder` keep no per-call state, so one instance can be shared across threads and registered as a singleton: + +```c# +services.AddSingleton(); +services.AddSingleton(new SqlServerCompiler { UseLegacyPagination = false }); +services.AddSingleton(); +``` + +Configure the `Compiler` before sharing it and do not change its properties afterwards. A custom `IEdmModelBuilder` must be thread-safe as well. + ## Example OData Service See [DynamicODataSampleService](Samples/DynamicODataSampleService) for and example OData service. @@ -126,8 +142,9 @@ See [DynamicODataSampleService](Samples/DynamicODataSampleService) for and examp ### apply support (aggregations) Aggregations using Odata `apply` query option is supported. Spec: http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/odata-data-aggregation-ext-v4.0.html -- Transformations: `filter`, `groupby` and `aggregate` are supported. `expand`, `concat`, `search`, `top`, `bottom` are NOT supported. +- Transformations: `filter`, `groupby`, `aggregate` and `compute` are supported. `expand`, `concat`, `search`, `top`, `bottom` are NOT supported. - `sum`, `min`, `max`, `avg`, `countdistinct` and `count` are supported. +- `compute` supports `year`, `month`, `day`, `hour` and `minute` on SQL Server, MySQL, PostgreSQL and SQLite. Example @@ -138,7 +155,7 @@ Example is converted to ```sql - SELECT [Country], Sum(Amount) AS Total, Avg(Amount) AS AvgAmt FROM [Orders] GROUP BY [Country] + SELECT [Country], Sum([Amount]) AS [Total], AVG([Amount]) AS [AvgAmt] FROM [Orders] GROUP BY [Country] ``` For more advanced aggreagate scenarios supported, see unit tests. diff --git a/Samples/DynamicODataSampleService/Controllers/TablesController.cs b/Samples/DynamicODataSampleService/Controllers/TablesController.cs index 167fef1..e9597fc 100644 --- a/Samples/DynamicODataSampleService/Controllers/TablesController.cs +++ b/Samples/DynamicODataSampleService/Controllers/TablesController.cs @@ -15,9 +15,11 @@ namespace DynamicODataSampleService.Controllers; using Flurl; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; +using Microsoft.OData; using Newtonsoft.Json.Linq; @@ -45,16 +47,25 @@ public async Task QueryAsync(string tableName, [FromQuery(Name = "$top")] int top = 10, [FromQuery(Name = "$skip")] int skip = 0) { - var query = _oDataToSqlConverter.ConvertToSQL(tableName, - new Dictionary - { - { "select", select }, - { "filter", filter }, - { "orderby", orderby }, - { "top", (top + 1).ToString(null,CultureInfo.InvariantCulture) }, - { "skip", skip.ToString(null,CultureInfo.InvariantCulture) } - } - ); + (string, IDictionary) query; + try + { + query = _oDataToSqlConverter.ConvertToSQL(tableName, + new Dictionary + { + { "select", select }, + { "filter", filter }, + { "orderby", orderby }, + { "top", (top + 1).ToString(null,CultureInfo.InvariantCulture) }, + { "skip", skip.ToString(null,CultureInfo.InvariantCulture) } + } + ); + } + catch (Exception ex) when (ex is ODataException or NotSupportedException) + { + // Malformed or unsupported query options are client errors. + return Problem(detail: ex.Message, statusCode: StatusCodes.Status400BadRequest); + } IEnumerable rows = null; await using var conn = new SqlConnection(_connectionString); rows = (await conn.QueryAsync(query.Item1, query.Item2).ConfigureAwait(false))?.ToList(); diff --git a/Samples/DynamicODataSampleService/Startup.cs b/Samples/DynamicODataSampleService/Startup.cs index 8d9953b..5c3a35e 100644 --- a/Samples/DynamicODataSampleService/Startup.cs +++ b/Samples/DynamicODataSampleService/Startup.cs @@ -18,9 +18,9 @@ public class Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddScoped(); + services.AddSingleton(); services.AddSingleton(new SqlServerCompiler { UseLegacyPagination = false }); - services.AddScoped(); + services.AddSingleton(); services.AddControllers(); } diff --git a/Source/DynamicODataToSQL/ApplyClauseBuilder.cs b/Source/DynamicODataToSQL/ApplyClauseBuilder.cs index 2a79e40..c10c5f6 100644 --- a/Source/DynamicODataToSQL/ApplyClauseBuilder.cs +++ b/Source/DynamicODataToSQL/ApplyClauseBuilder.cs @@ -1,6 +1,7 @@ namespace DynamicODataToSQL; using System; +using System.Collections.Generic; using System.Linq; using Microsoft.OData.UriParser; @@ -47,7 +48,7 @@ public Query BuildApplyClause(Query queryIn, ApplyClause applyClause, bool tryTo if (i > 0 && applyClause.Transformations.ElementAt(i - 1).Kind != TransformationNodeKind.Filter) { // Use sub queriy if prev transformation is not filter - queryIn = new Query().From(queryIn); + queryIn = new Query().From(queryIn, "apply"); } switch (node.Kind) @@ -86,8 +87,7 @@ private Query Visit(Query queryIn, AggregateTransformationNode nodeIn) AggregationMethod.Average => queryIn.SelectRaw($"AVG({columnNameResolver.GetColumnName(expr.Expression, true)}) AS {_compiler.WrapValue(expr.Alias)}"), AggregationMethod.CountDistinct => queryIn.SelectRaw($"COUNT(DISTINCT {columnNameResolver.GetColumnName(expr.Expression, true)}) AS {_compiler.WrapValue(expr.Alias)}"), AggregationMethod.VirtualPropertyCount => queryIn.SelectRaw($"COUNT(1) AS {_compiler.WrapValue(expr.Alias)}"), - AggregationMethod.Custom => throw new NotImplementedException(), - _ => throw new NotSupportedException($"Aggregate method {expr.Method:g} not supported"), + AggregationMethod.Custom or _ => throw new NotSupportedException($"Aggregate method {expr.Method:g} not supported"), }; } } @@ -112,6 +112,25 @@ private Query Visit(Query queryIn, GroupByTransformationNode nodeIn) return queryIn; } + // MySQL has YEAR() through MINUTE(); SQL Server lacks HOUR() and MINUTE(); PostgreSQL and SQLite need their own forms. + private string DatePart(string part, string column) => _compiler.EngineCode switch + { + EngineCodes.SqlServer when part.ToUpperInvariant() is "HOUR" or "MINUTE" => $"DATEPART({part.ToUpperInvariant()}, {column})", + EngineCodes.SqlServer or EngineCodes.MySql => $"{part}({column})", + EngineCodes.PostgreSql => $"CAST(EXTRACT({part.ToUpperInvariant()} FROM {column}) AS INTEGER)", + EngineCodes.Sqlite => $"CAST(strftime('{SqliteFormats[part.ToUpperInvariant()]}', {column}) AS INTEGER)", + _ => throw new NotSupportedException($"compute({part}) is not supported for the {_compiler.EngineCode} compiler"), + }; + + private static readonly Dictionary SqliteFormats = new() + { + ["YEAR"] = "%Y", + ["MONTH"] = "%m", + ["DAY"] = "%d", + ["HOUR"] = "%H", + ["MINUTE"] = "%M", + }; + private Query Visit(Query queryIn, ComputeTransformationNode nodeIn) { queryIn = queryIn.SelectRaw("*"); @@ -127,8 +146,8 @@ private Query Visit(Query queryIn, ComputeTransformationNode nodeIn) case "HOUR": case "MINUTE": var pr = se.Parameters.Single(); - var columnName = columnNameResolver.GetColumnName(pr); - queryIn = queryIn.SelectRaw($"{se.Name}({columnName}) as {computeExpression.Alias}"); + var columnName = columnNameResolver.GetColumnName(pr, true); + queryIn = queryIn.SelectRaw($"{DatePart(se.Name, columnName)} as {computeExpression.Alias}"); break; default: throw new NotSupportedException($"Aggregate method {se.Name} not supported"); diff --git a/Source/DynamicODataToSQL/ColumnNameResolver.cs b/Source/DynamicODataToSQL/ColumnNameResolver.cs index a53698d..c620556 100644 --- a/Source/DynamicODataToSQL/ColumnNameResolver.cs +++ b/Source/DynamicODataToSQL/ColumnNameResolver.cs @@ -3,6 +3,7 @@ namespace DynamicODataToSQL; using System; using System.Collections.Generic; using System.Linq; +using System.Xml; using Microsoft.OData.Edm; using Microsoft.OData.UriParser; @@ -55,31 +56,27 @@ public string GetColumnName(QueryNode node, bool wrap = false) throw new NotSupportedException($"Expected a property, found '{node.Kind}'"); } + // Decode before wrapping so a decoded closing quote (e.g. _x005D_) is escaped by WrapValue. + table = XmlConvert.DecodeName(table); + column = DecodeColumnName(column); if (wrap) { table = compiler.WrapValue(table); column = compiler.WrapValue(column); } - if (useNamespacing) - { - return $"{table}.{column}".Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " "); - } - else - { - return column.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " "); - } + return useNamespacing ? $"{table}.{column}" : column; } public string GetColumnName(string propertyName) { if (useNamespacing) { - return $"{tableName}.{propertyName}".Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " "); + return $"{XmlConvert.DecodeName(tableName)}.{DecodeColumnName(propertyName)}"; } else { - return propertyName.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " "); + return DecodeColumnName(propertyName); } } @@ -92,11 +89,11 @@ public string[] GetColumnNames() { if (useNamespacing) { - names.Add($"{tableName}.{structuralProperty.Name.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " ")}"); + names.Add($"{tableName}.{DecodeColumnName(structuralProperty.Name)}"); } else { - names.Add(structuralProperty.Name.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " ")); + names.Add(DecodeColumnName(structuralProperty.Name)); } } } @@ -122,7 +119,7 @@ public string GetColumnName(string navigationPropertyName, string propertyName) { throw new InvalidOperationException("Only structural properties may be selected."); } - return $"{navigationPropertyName}.{structuralProperty.Name.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " ")}"; + return $"{navigationPropertyName}.{DecodeColumnName(structuralProperty.Name)}"; } public string[] GetColumnNames(string navigationPropertyName) @@ -144,9 +141,21 @@ public string[] GetColumnNames(string navigationPropertyName) { if (property is EdmStructuralProperty structuralProperty) { - names.Add($"{navigationPropertyName}.{structuralProperty.Name.Replace(ODataToSqlConverter.SPACESIGNREPLACEMENT, " ")}"); + names.Add($"{navigationPropertyName}.{DecodeColumnName(structuralProperty.Name)}"); } } return [.. names]; } + + // OData names escape non-identifier characters as _xHHHH_ (e.g. _x0020_ for a space). + private static string DecodeColumnName(string name) + { + var decoded = XmlConvert.DecodeName(name); + // SqlKata treats these as syntax even inside quoted identifiers: '.' splits names, '?' is a parameter + // placeholder, '{' '}' '[' ']' become unescaped quote characters in raw SQL and '\' escapes them. + // Databases accept any other character in a quoted identifier, so this list stays a denylist. + return decoded.IndexOfAny(['.', '?', '{', '}', '[', ']', '\\']) >= 0 || decoded.Any(char.IsControl) + ? throw new NotSupportedException($"Column name '{name}' contains a character that is not supported") + : decoded; + } } diff --git a/Source/DynamicODataToSQL/FilterClauseBuilder.cs b/Source/DynamicODataToSQL/FilterClauseBuilder.cs index 5f9a0b5..196c41d 100644 --- a/Source/DynamicODataToSQL/FilterClauseBuilder.cs +++ b/Source/DynamicODataToSQL/FilterClauseBuilder.cs @@ -247,13 +247,13 @@ private object GetConstantValue(QueryNode node) var value = (node as ConstantNode).Value; if (value is string) { - var trimedValue = value.ToString(); - if (_tryToParseDates && ConvertToDateTimeUTC(trimedValue, out var dateTime)) + var text = value.ToString(); + if (_tryToParseDates && ConvertToDateTimeUTC(text, out var dateTime)) { return dateTime.Value; } - return trimedValue; + return text; } else if (value is DateOnly date) { @@ -277,7 +277,7 @@ private object GetConstantValue(QueryNode node) } private IEnumerable GetCollectionConstantValues(CollectionConstantNode node) => - node.Collection.Select(n => + node.Items.Select(n => { // The OData library parser will take empty strings and replace them with quoted text strings, specifically // in collection filter clauses: @@ -286,7 +286,7 @@ private IEnumerable GetCollectionConstantValues(CollectionConstantNode n // an empty string, unless you special case it here. This does not seem to be an issue for general filters: // eg. $filter=Name eq '' // So we can focus this workaround to just processing collection constant values. - if (n.Kind == QueryNodeKind.Constant && n.Value is string nodeValue && nodeValue == @"""""") + if (n is ConstantNode { Value: @"""""" }) { return string.Empty; } @@ -317,14 +317,9 @@ or BinaryOperatorKind.Multiply or BinaryOperatorKind.Divide or BinaryOperatorKin BinaryOperatorKind.GreaterThanOrEqual => ">=", BinaryOperatorKind.LessThan => "<", BinaryOperatorKind.LessThanOrEqual => "<=", - BinaryOperatorKind.Or => "or", - BinaryOperatorKind.And => "and", - BinaryOperatorKind.Add => "+", - BinaryOperatorKind.Subtract => "-", - BinaryOperatorKind.Multiply => "*", - BinaryOperatorKind.Divide => "/", - BinaryOperatorKind.Modulo => "%", - BinaryOperatorKind.Has => throw new NotImplementedException(), - _ => string.Empty, + BinaryOperatorKind.Or or BinaryOperatorKind.And or BinaryOperatorKind.Add or BinaryOperatorKind.Subtract + or BinaryOperatorKind.Multiply or BinaryOperatorKind.Divide or BinaryOperatorKind.Modulo or BinaryOperatorKind.Has + => throw new ArgumentOutOfRangeException(nameof(operatorKind), operatorKind, "Only comparison operators are supported"), + _ => throw new ArgumentOutOfRangeException(nameof(operatorKind), operatorKind, "Only comparison operators are supported"), }; } diff --git a/Tests/DynamicODataToSQL.Test/FilterShapeTests.cs b/Tests/DynamicODataToSQL.Test/FilterShapeTests.cs index 86308cf..c570581 100644 --- a/Tests/DynamicODataToSQL.Test/FilterShapeTests.cs +++ b/Tests/DynamicODataToSQL.Test/FilterShapeTests.cs @@ -2,6 +2,7 @@ namespace DynamicODataToSQL.Test; using System; using System.Collections.Generic; +using System.Globalization; using SqlKata.Compilers; @@ -20,6 +21,9 @@ private static (string Sql, IDictionary Params) Convert(string o [InlineData("5 lt TotalInventory", "SELECT * FROM [Products] WHERE [Products].[TotalInventory] > @p0", 5)] [InlineData("10 ge TotalInventory", "SELECT * FROM [Products] WHERE [Products].[TotalInventory] <= @p0", 10)] [InlineData("null eq Name", "SELECT * FROM [Products] WHERE [Products].[Name] IS NULL", null)] + [InlineData("5 gt TotalInventory", "SELECT * FROM [Products] WHERE [Products].[TotalInventory] < @p0", 5)] + [InlineData("5 le TotalInventory", "SELECT * FROM [Products] WHERE [Products].[TotalInventory] >= @p0", 5)] + [InlineData("'Tea' ne Name", "SELECT * FROM [Products] WHERE [Products].[Name] <> @p0", "Tea")] [InlineData("Name eq Type", "SELECT * FROM [Products] WHERE [Products].[Name] = [Products].[Type]", null)] [InlineData("not (Name eq Type)", "SELECT * FROM [Products] WHERE NOT [Products].[Name] = [Products].[Type]", null)] [InlineData("not (Name eq 'Tea')", "SELECT * FROM [Products] WHERE NOT ([Products].[Name] = @p0)", "Tea")] @@ -53,15 +57,137 @@ public void SupportedShapeEmitsPredicate(string filter, string expectedSql, obje [InlineData("contains('abc', Name)")] [InlineData("contains(Name, Type)")] [InlineData("Id gt 0 and not (TotalInventory sub 1 eq 0)")] + [InlineData("a_x002E_b eq 'v'")] + [InlineData("a_x003F_b eq 'v'")] + [InlineData("_x007B_x_x002C_y_x007D_ eq 'v'")] + [InlineData("a_x005D_b eq 'v'")] + [InlineData("a_x005C_b eq 'v'")] + [InlineData("a_x0000_b eq 'v'")] public void UnsupportedFilterThrows(string filter) => Assert.Throws(() => Convert("filter", filter)); [Theory] [InlineData("1")] [InlineData("length(Name)")] + [InlineData("a_x002E_b")] public void UnsupportedOrderByThrows(string orderby) => Assert.Throws(() => Convert("orderby", orderby)); + [Theory] + [InlineData("aggregate(_x007D__x0029__x003B_DROP with sum as t)")] + [InlineData("groupby((a_x003F_b))")] + [InlineData("aggregate(x_x005D__x0029__x003B__x0020_DROP_x0020_TABLE_x0020_users_x003B__x0020__x002D__x002D_ with sum as t)")] + [InlineData("compute(year(a_x005B_b) as yr)")] + public void UnsupportedApplyThrows(string apply) => + Assert.Throws(() => Convert("apply", apply)); + + [Theory] + [InlineData("compute(day(OrderDate) as d, hour(OrderDate) as h, minute(OrderDate) as m)", "SELECT *, day([OrderDate]) as d, DATEPART(HOUR, [OrderDate]) as h, DATEPART(MINUTE, [OrderDate]) as m FROM [Products]")] + [InlineData("aggregate(Price with min as a, Price with max as b, Price with average as c)", "SELECT Min([Price]) AS [a], Max([Price]) AS [b], AVG([Price]) AS [c] FROM [Products]")] + [InlineData("filter(Name eq 'Tea')/groupby((Type))", "SELECT [Type] FROM [Products] WHERE [Name] = @p0 GROUP BY [Type]")] + public void SupportedApplyEmitsQuery(string apply, string expectedSql) => + Assert.Equal(expectedSql, Convert("apply", apply).Sql); + + [Theory] + [InlineData("sqlsrv", "SELECT *, year([OrderDate]) as y, DATEPART(MINUTE, [OrderDate]) as mi FROM [Products]")] + [InlineData("mysql", "SELECT *, year(`OrderDate`) as y, minute(`OrderDate`) as mi FROM `Products`")] + [InlineData("postgres", "SELECT *, CAST(EXTRACT(YEAR FROM \"OrderDate\") AS INTEGER) as y, CAST(EXTRACT(MINUTE FROM \"OrderDate\") AS INTEGER) as mi FROM \"Products\"")] + [InlineData("sqlite", "SELECT *, CAST(strftime('%Y', \"OrderDate\") AS INTEGER) as y, CAST(strftime('%M', \"OrderDate\") AS INTEGER) as mi FROM \"Products\"")] + public void ComputeDatePartMatchesDialect(string engine, string expectedSql) + { + var compiler = CompilerFor(engine); + var query = new ODataToSqlConverter(new TestsEdmModelBuilder(), compiler) + .ConvertToSQLKataQuery("Products", new Dictionary { ["apply"] = "compute(year(OrderDate) as y, minute(OrderDate) as mi)" }); + + Assert.Equal(expectedSql, compiler.Compile(query).Sql); + } + + [Theory] + [InlineData("oracle")] + [InlineData("firebird")] + public void ComputeDatePartThrowsForUnsupportedDialect(string engine) => + Assert.Throws(() => new ODataToSqlConverter(new TestsEdmModelBuilder(), CompilerFor(engine)) + .ConvertToSQLKataQuery("Products", new Dictionary { ["apply"] = "compute(year(OrderDate) as y)" })); + + private static Compiler CompilerFor(string engine) => engine switch + { + "sqlsrv" => Compiler, + "mysql" => new MySqlCompiler(), + "postgres" => new PostgresCompiler(), + "sqlite" => new SqliteCompiler(), + "oracle" => new OracleCompiler(), + "firebird" => new FirebirdCompiler(), + _ => throw new ArgumentOutOfRangeException(nameof(engine)), + }; + + [Theory] + [InlineData("compute(length(Name) as l)")] + [InlineData("compute(Name as n)")] + public void UnsupportedComputeThrows(string apply) => + Assert.Throws(() => Convert("apply", apply)); + + [Fact] + public void NullArgumentsThrow() + { + var converter = new ODataToSqlConverter(new TestsEdmModelBuilder(), Compiler); + var query = new Dictionary(); + + Assert.Throws(() => new ODataToSqlConverter(null, Compiler)); + Assert.Throws(() => new ODataToSqlConverter(new TestsEdmModelBuilder(), null)); + Assert.Throws(() => converter.ConvertToSQL(null, query)); + Assert.Throws(() => converter.ConvertToSqlFromRawSql(null, query)); + Assert.Throws(() => new EdmModelBuilder().BuildTableModel(" ")); + } + + [Theory] + [InlineData("filter", "{0} eq 'v'", "SELECT * FROM {1} WHERE {1}.{0} = @p0")] + [InlineData("select", "{0}", "SELECT {1}.{0} FROM {1}")] + [InlineData("orderby", "{0}", "SELECT * FROM {1} ORDER BY {1}.{0}")] + [InlineData("apply", "aggregate({0} with sum as t)", "SELECT Sum({0}) AS {2} FROM {1}")] + [InlineData("apply", "aggregate({0} with countdistinct as t)", "SELECT COUNT(DISTINCT {0}) AS {2} FROM {1}")] + [InlineData("apply", "compute(year({0}) as yr)", "SELECT *, {3} as yr FROM {1}")] + public void EncodedColumnCharacterIsQuotedOrRejected(string option, string odataFormat, string sqlFormat) + { + var last = int.TryParse(Environment.GetEnvironmentVariable("DECODE_SWEEP_LAST"), out var n) ? n : 0x7E; + Compiler[] compilers = [Compiler, new PostgresCompiler(), new MySqlCompiler()]; + var failures = new List(); + foreach (var compiler in compilers) + { + var converter = new ODataToSqlConverter(new TestsEdmModelBuilder(), compiler); + for (var c = 0x01; c <= last; c++) + { + if (c is >= 0xD800 and <= 0xDFFF) + { + continue; + } + + var column = $"a{(char)c}b"; + var odata = string.Format(CultureInfo.InvariantCulture, odataFormat, $"a_x{c:X4}_b"); + var rejected = char.IsControl((char)c) || "[]{}.?\\".Contains((char)c); + try + { + var (sql, _) = converter.ConvertToSQL("Products", new Dictionary { [option] = odata }, false, true); + var wrapped = compiler.WrapValue(column); + var year = compiler is PostgresCompiler ? $"CAST(EXTRACT(YEAR FROM {wrapped}) AS INTEGER)" : $"year({wrapped})"; + var expected = string.Format(CultureInfo.InvariantCulture, sqlFormat, wrapped, compiler.WrapValue("Products"), compiler.WrapValue("t"), year); + if (rejected || sql != expected) + { + failures.Add($"{compiler.EngineCode} U+{c:X4}: {sql}"); + } + } + catch (NotSupportedException) when (rejected) + { + } + catch (Exception ex) + { + failures.Add($"{compiler.EngineCode} U+{c:X4}: {ex.GetType().Name}"); + } + } + } + + Assert.Empty(failures); + } + [Fact] public void NotLeavesNoNegationForLaterPredicates() { diff --git a/Tests/DynamicODataToSQL.Test/ODataToSqlConverterTests.cs b/Tests/DynamicODataToSQL.Test/ODataToSqlConverterTests.cs index 1797181..8543854 100644 --- a/Tests/DynamicODataToSQL.Test/ODataToSqlConverterTests.cs +++ b/Tests/DynamicODataToSQL.Test/ODataToSqlConverterTests.cs @@ -1,8 +1,10 @@ namespace DynamicODataToSQL.Test; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using SqlKata.Compilers; @@ -46,6 +48,44 @@ public void ConvertToSQLExpectedBehavior( Assert.True(Utility.DictionariesAreEqual(expectedSQLParams, actualSQLParams)); } + [Fact] + public void ConvertToSQLConcurrentExpectedBehavior() + { + // Arrange: one shared instance, as when registered as a singleton. + var oDataToSqlConverter = CreateODataToSqlConverter(); + var cases = GetTestData().ToArray(); + var expected = cases.Select(Run).ToArray(); + var iterations = int.TryParse(Environment.GetEnvironmentVariable("CONCURRENCY_ITERATIONS"), out var n) ? n : 50; + var failures = new ConcurrentBag(); + + // Act + Parallel.For(0, cases.Length * iterations, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, i => + { + var index = i % cases.Length; + var actual = Run(cases[index]); + if (actual != expected[index]) + { + failures.Add($"{cases[index][0]}: {actual}"); + } + }); + + // Assert + Assert.Empty(failures); + + string Run(object[] c) + { + try + { + var (sql, parameters) = oDataToSqlConverter.ConvertToSQL((string)c[1], (IDictionary)c[3], (bool)c[4], (bool)c[2]); + return sql + "|" + string.Join(",", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")); + } + catch (Exception ex) + { + return ex.GetType().Name; + } + } + } + public static IEnumerable GetTestData() { // Test 1 @@ -211,7 +251,7 @@ public static IEnumerable GetTestData() { {"apply","filter(Amount ge 100)/groupby((Country),aggregate(Amount with sum as Total,Amount with average as AvgAmt))/filter(AvgAmt ge 20)"} }; - var expectedSQL = @"SELECT * FROM (SELECT [Country], Sum([Amount]) AS [Total], AVG([Amount]) AS [AvgAmt] FROM [Orders] WHERE [Amount] >= @p0 GROUP BY [Country]) WHERE [AvgAmt] >= @p1"; + var expectedSQL = @"SELECT * FROM (SELECT [Country], Sum([Amount]) AS [Total], AVG([Amount]) AS [AvgAmt] FROM [Orders] WHERE [Amount] >= @p0 GROUP BY [Country]) AS [apply] WHERE [AvgAmt] >= @p1"; var expectedSQLParams = new Dictionary { { "@p0", 100d }, { "@p1", 20 } }; yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } @@ -316,7 +356,7 @@ public static IEnumerable GetTestData() { {"apply","compute(year(OrderDate) as yr, month(OrderDate) as mn)/groupby((yr,mn),aggregate(value with average as AvgValue))" } }; - var expectedSQL = @"SELECT [yr], [mn], AVG([value]) AS [AvgValue] FROM (SELECT *, year(OrderDate) as yr, month(OrderDate) as mn FROM [Orders]) GROUP BY [yr], [mn]"; + var expectedSQL = @"SELECT [yr], [mn], AVG([value]) AS [AvgValue] FROM (SELECT *, year([OrderDate]) as yr, month([OrderDate]) as mn FROM [Orders]) AS [apply] GROUP BY [yr], [mn]"; var expectedSQLParams = new Dictionary { }; yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } @@ -594,6 +634,76 @@ public static IEnumerable GetTestData() yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } + // Test 30 + { + var testName = "Select+Filter+Sort+EncodedColumnNames"; + var tableName = "Products"; + var tryToParseDates = true; + var odataQueryParams = new Dictionary + { + {"select", "_x0032_TableName, Closed_x0020__x0028_UTC_x0029_" }, + {"filter", "a_x007E_b eq 'Tea'" }, + {"orderby", "_x0032_TableName" }, + }; + var expectedSQL = @"SELECT [Products].[2TableName], [Products].[Closed (UTC)] FROM [Products] WHERE [Products].[a~b] = @p0 ORDER BY [Products].[2TableName]"; + var expectedSQLParams = new Dictionary + { + {"@p0", "Tea"}, + }; + yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } + // Test 31 + { + var testName = "Filter+EncodedSqlPunctuation"; + var tableName = "Products"; + var tryToParseDates = true; + var odataQueryParams = new Dictionary + { + {"filter", "a_x0027__x0029__x003B__x0020__x002D__x002D_b eq _x0032_A" }, + }; + var expectedSQL = @"SELECT * FROM [Products] WHERE [Products].[a'); --b] = [Products].[2A]"; + var expectedSQLParams = new Dictionary { }; + yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } + // Test 32 + { + var testName = "Filter+WhitespaceInStringConstants"; + var tableName = "Products"; + var tryToParseDates = true; + var odataQueryParams = new Dictionary + { + {"filter", "Name eq 'Test ' or Name eq ' Test' or Name eq ' ' or Name eq '' or Name eq ' it''s '" }, + }; + var expectedSQL = @"SELECT * FROM [Products] WHERE (((([Products].[Name] = @p0 OR [Products].[Name] = @p1) OR [Products].[Name] = @p2) OR [Products].[Name] = @p3) OR [Products].[Name] = @p4)"; + var expectedSQLParams = new Dictionary + { + {"@p0", "Test "}, + {"@p1", " Test"}, + {"@p2", " "}, + {"@p3", ""}, + {"@p4", " it's "}, + }; + yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } + // Test 33 + { + var testName = "Filter+WhitespaceInFunctionsAndIn"; + var tableName = "Products"; + var tryToParseDates = false; + var odataQueryParams = new Dictionary + { + {"filter", "contains(Name,' a ') and Type in (' b ', 'c') and Name eq ' 2020-09-08 '" }, + }; + var expectedSQL = @"SELECT * FROM [Products] WHERE (([Products].[Name] like @p0 AND [Products].[Type] IN (@p1, @p2)) AND [Products].[Name] = @p3)"; + var expectedSQLParams = new Dictionary + { + {"@p0", "% a %"}, + {"@p1", " b "}, + {"@p2", "c"}, + {"@p3", " 2020-09-08 "}, + }; + yield return new object[] { testName, tableName, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } } private static ODataToSqlConverter CreateODataToSqlConverter() => new(new TestsEdmModelBuilder(), new SqlServerCompiler() { UseLegacyPagination = false }); diff --git a/Tests/DynamicODataToSQL.Test/ODataToSqlFromRawSqlConverterTests.cs b/Tests/DynamicODataToSQL.Test/ODataToSqlFromRawSqlConverterTests.cs index fe22267..402d58e 100644 --- a/Tests/DynamicODataToSQL.Test/ODataToSqlFromRawSqlConverterTests.cs +++ b/Tests/DynamicODataToSQL.Test/ODataToSqlFromRawSqlConverterTests.cs @@ -1,8 +1,10 @@ namespace DynamicODataToSQL.Test; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using SqlKata.Compilers; @@ -46,6 +48,44 @@ public void ConvertToSQLFromRawSqlExpectedBehavior( Assert.True(Utility.DictionariesAreEqual(expectedSQLParams, actualSQLParams)); } + [Fact] + public void ConvertToSQLFromRawSqlConcurrentExpectedBehavior() + { + // Arrange: one shared instance, as when registered as a singleton. + var oDataToSqlConverter = CreateODataToSqlConverter(); + var cases = GetTestData().ToArray(); + var expected = cases.Select(Run).ToArray(); + var iterations = int.TryParse(Environment.GetEnvironmentVariable("CONCURRENCY_ITERATIONS"), out var n) ? n : 50; + var failures = new ConcurrentBag(); + + // Act + Parallel.For(0, cases.Length * iterations, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, i => + { + var index = i % cases.Length; + var actual = Run(cases[index]); + if (actual != expected[index]) + { + failures.Add($"{cases[index][0]}: {actual}"); + } + }); + + // Assert + Assert.Empty(failures); + + string Run(object[] c) + { + try + { + var (sql, parameters) = oDataToSqlConverter.ConvertToSqlFromRawSql((string)c[1], (IDictionary)c[3], (bool)c[4], (bool)c[2]); + return sql + "|" + string.Join(",", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")); + } + catch (Exception ex) + { + return ex.GetType().Name; + } + } + } + public static IEnumerable GetTestData() { @@ -212,7 +252,7 @@ public static IEnumerable GetTestData() { {"apply","filter(Amount ge 100)/groupby((Country),aggregate(Amount with sum as Total,Amount with average as AvgAmt))/filter(AvgAmt ge 20)"} }; - var expectedSQL = "WITH [RawSql] AS (SELECT * FROM [Orders])\nSELECT * FROM (SELECT [Country], Sum([Amount]) AS [Total], AVG([Amount]) AS [AvgAmt] FROM [RawSql] WHERE [Amount] >= @p0 GROUP BY [Country]) WHERE [AvgAmt] >= @p1"; + var expectedSQL = "WITH [RawSql] AS (SELECT * FROM [Orders])\nSELECT * FROM (SELECT [Country], Sum([Amount]) AS [Total], AVG([Amount]) AS [AvgAmt] FROM [RawSql] WHERE [Amount] >= @p0 GROUP BY [Country]) AS [apply] WHERE [AvgAmt] >= @p1"; var expectedSQLParams = new Dictionary { { "@p0", 100 }, { "@p1", 20 } }; yield return new object[] { testName, rawSql, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } @@ -316,7 +356,7 @@ public static IEnumerable GetTestData() { {"apply","compute(year(OrderDate) as yr, month(OrderDate) as mn)/groupby((yr,mn),aggregate(value with average as AvgValue))" } }; - var expectedSQL = "WITH [RawSql] AS (SELECT * FROM [Orders])\nSELECT [yr], [mn], AVG([value]) AS [AvgValue] FROM (SELECT *, year(OrderDate) as yr, month(OrderDate) as mn FROM [RawSql]) GROUP BY [yr], [mn]"; + var expectedSQL = "WITH [RawSql] AS (SELECT * FROM [Orders])\nSELECT [yr], [mn], AVG([value]) AS [AvgValue] FROM (SELECT *, year([OrderDate]) as yr, month([OrderDate]) as mn FROM [RawSql]) AS [apply] GROUP BY [yr], [mn]"; var expectedSQLParams = new Dictionary { }; yield return new object[] { testName, rawSql, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } @@ -338,6 +378,32 @@ public static IEnumerable GetTestData() yield return new object[] { testName, rawSql, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; } + // Test 18 + { + var testName = "Apply+EncodedColumnNames"; + var rawSql = "select ItemCode as [2TableName], OnHand as [On Hand] from OITM"; + var tryToParseDates = true; + var odataQueryParams = new Dictionary + { + {"apply", "groupby((_x0032_TableName),aggregate(On_x0020_Hand with sum as On_x0020_Hand, $count as total))" } + }; + var expectedSQL = "WITH [RawSql] AS (select ItemCode as [2TableName], OnHand as [On Hand] from OITM)\nSELECT [2TableName], Sum([On Hand]) AS [On_x0020_Hand], COUNT(1) AS [total] FROM [RawSql] GROUP BY [2TableName]"; + var expectedSQLParams = new Dictionary { }; + yield return new object[] { testName, rawSql, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } + // Test 19 + { + var testName = "Apply+ComputeEncodedSqlPunctuation"; + var rawSql = "SELECT * FROM [Orders]"; + var tryToParseDates = true; + var odataQueryParams = new Dictionary + { + {"apply", "compute(year(OrderDate_x0029__x003B__x0020_DROP_x0020_TABLE_x0020_Users_x003B__x0020__x002D__x002D_) as yr)" } + }; + var expectedSQL = "WITH [RawSql] AS (SELECT * FROM [Orders])\nSELECT *, year([OrderDate); DROP TABLE Users; --]) as yr FROM [RawSql]"; + var expectedSQLParams = new Dictionary { }; + yield return new object[] { testName, rawSql, tryToParseDates, odataQueryParams, false, expectedSQL, expectedSQLParams }; + } } private static ODataToSqlConverter CreateODataToSqlConverter() => new(new EdmModelBuilder(), new SqlServerCompiler() { UseLegacyPagination = false }); diff --git a/Tests/DynamicODataToSQL.Test/TestsEdmModelBuilder.cs b/Tests/DynamicODataToSQL.Test/TestsEdmModelBuilder.cs index fb30dab..9224da3 100644 --- a/Tests/DynamicODataToSQL.Test/TestsEdmModelBuilder.cs +++ b/Tests/DynamicODataToSQL.Test/TestsEdmModelBuilder.cs @@ -85,7 +85,7 @@ protected override void AddNavigationProperties(EdmEntityType rootType, EdmModel } } - var targetEntity = lookupEntitySet.EntityType(); + var targetEntity = (lookupEntitySet ?? throw new InvalidOperationException("Entity container is not mutable")).EntityType; var navigationPropertyInfo = new EdmNavigationPropertyInfo { Name = navigationProperty.navigationPropertyName,