Skip to content
Merged
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
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ IDictionary<string, object> 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<IEdmModelBuilder, EdmModelBuilder>();
services.AddSingleton<Compiler>(new SqlServerCompiler { UseLegacyPagination = false });
services.AddSingleton<IODataToSqlConverter, ODataToSqlConverter>();
```

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.

Expand Down Expand Up @@ -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

Expand All @@ -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.
Expand Down
31 changes: 21 additions & 10 deletions Samples/DynamicODataSampleService/Controllers/TablesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -45,16 +47,25 @@ public async Task<IActionResult> QueryAsync(string tableName,
[FromQuery(Name = "$top")] int top = 10,
[FromQuery(Name = "$skip")] int skip = 0)
{
var query = _oDataToSqlConverter.ConvertToSQL(tableName,
new Dictionary<string, string>
{
{ "select", select },
{ "filter", filter },
{ "orderby", orderby },
{ "top", (top + 1).ToString(null,CultureInfo.InvariantCulture) },
{ "skip", skip.ToString(null,CultureInfo.InvariantCulture) }
}
);
(string, IDictionary<string, object>) query;
try
{
query = _oDataToSqlConverter.ConvertToSQL(tableName,
new Dictionary<string, string>
{
{ "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<dynamic> rows = null;
await using var conn = new SqlConnection(_connectionString);
rows = (await conn.QueryAsync(query.Item1, query.Item2).ConfigureAwait(false))?.ToList();
Expand Down
4 changes: 2 additions & 2 deletions Samples/DynamicODataSampleService/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IEdmModelBuilder, EdmModelBuilder>();
services.AddSingleton<IEdmModelBuilder, EdmModelBuilder>();
services.AddSingleton<Compiler>(new SqlServerCompiler { UseLegacyPagination = false });
services.AddScoped<IODataToSqlConverter, ODataToSqlConverter>();
services.AddSingleton<IODataToSqlConverter, ODataToSqlConverter>();

services.AddControllers();
}
Expand Down
29 changes: 24 additions & 5 deletions Source/DynamicODataToSQL/ApplyClauseBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace DynamicODataToSQL;

using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.OData.UriParser;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"),
};
}
}
Expand All @@ -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<string, string> SqliteFormats = new()
{
["YEAR"] = "%Y",
["MONTH"] = "%m",
["DAY"] = "%d",
["HOUR"] = "%H",
["MINUTE"] = "%M",
};

private Query Visit(Query queryIn, ComputeTransformationNode nodeIn)
{
queryIn = queryIn.SelectRaw("*");
Expand All @@ -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");
Expand Down
37 changes: 23 additions & 14 deletions Source/DynamicODataToSQL/ColumnNameResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

Expand All @@ -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));
}
}
}
Expand All @@ -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)
Expand All @@ -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;
}
}
23 changes: 9 additions & 14 deletions Source/DynamicODataToSQL/FilterClauseBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -277,7 +277,7 @@ private object GetConstantValue(QueryNode node)
}

private IEnumerable<object> 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:
Expand All @@ -286,7 +286,7 @@ private IEnumerable<object> 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;
}
Expand Down Expand Up @@ -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"),
};
}
Loading
Loading