Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic arithmetics #20212

Merged
merged 20 commits into from
Jul 10, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,9 @@ private static readonly IReadOnlyDictionary<ExpressionType, IReadOnlyCollection<
{
typeof(DateTime),
typeof(DateTimeOffset),
typeof(decimal),
typeof(TimeSpan)
},
[ExpressionType.Divide] = new HashSet<Type>
{
typeof(decimal),
typeof(TimeSpan),
typeof(ulong)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should file an issue to do the ulong ones too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it would make sense, yes. I'd be happy to work on this, when decimals are finished, if OK.

},
[ExpressionType.Divide] = new HashSet<Type> { typeof(TimeSpan), typeof(ulong) },
[ExpressionType.GreaterThan] = new HashSet<Type>
{
typeof(DateTimeOffset),
Expand All @@ -63,17 +57,11 @@ private static readonly IReadOnlyDictionary<ExpressionType, IReadOnlyCollection<
typeof(ulong)
},
[ExpressionType.Modulo] = new HashSet<Type> { typeof(ulong) },
[ExpressionType.Multiply] = new HashSet<Type>
{
typeof(decimal),
typeof(TimeSpan),
typeof(ulong)
},
[ExpressionType.Multiply] = new HashSet<Type> { typeof(TimeSpan), typeof(ulong) },
[ExpressionType.Subtract] = new HashSet<Type>
{
typeof(DateTime),
typeof(DateTimeOffset),
typeof(decimal),
typeof(TimeSpan)
}
};
Expand Down Expand Up @@ -132,8 +120,17 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression)
&& sqlUnary.OperatorType == ExpressionType.Negate)
{
var operandType = GetProviderType(sqlUnary.Operand);
if (operandType == typeof(decimal)
|| operandType == typeof(TimeSpan))
if (operandType == typeof(decimal))
{
return Dependencies.SqlExpressionFactory.Function(
name: "ef_negate",
new[] { sqlUnary.Operand },
nullable: true,
new[] { true },
visitedExpression.Type);
}

if (operandType == typeof(TimeSpan))
{
return null;
}
Expand Down Expand Up @@ -177,6 +174,11 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
return DoDecimalCompare(visitedExpression, sqlBinary.OperatorType, sqlBinary.Left, sqlBinary.Right);
}

if (AttemptDecimalArithmetic(sqlBinary))
{
return DoDecimalArithmetics(visitedExpression, sqlBinary.OperatorType, sqlBinary.Left, sqlBinary.Right);
}

if (_restrictedBinaryExpressions.TryGetValue(sqlBinary.OperatorType, out var restrictedTypes)
&& (restrictedTypes.Contains(GetProviderType(sqlBinary.Left))
|| restrictedTypes.Contains(GetProviderType(sqlBinary.Right))))
Expand Down Expand Up @@ -291,9 +293,11 @@ private static Type GetProviderType(SqlExpression expression)
?? expression.TypeMapping?.ClrType
?? expression.Type).UnwrapNullableType();

private static bool AreOperandsDecimals(SqlBinaryExpression sqlExpression) => GetProviderType(sqlExpression.Left) == typeof(decimal)
&& GetProviderType(sqlExpression.Right) == typeof(decimal);

private static bool AttemptDecimalCompare(SqlBinaryExpression sqlBinary) =>
GetProviderType(sqlBinary.Left) == typeof(decimal)
&& GetProviderType(sqlBinary.Right) == typeof(decimal)
AreOperandsDecimals(sqlBinary)
&& new[]
{
ExpressionType.GreaterThan, ExpressionType.GreaterThanOrEqual, ExpressionType.LessThan, ExpressionType.LessThanOrEqual
Expand All @@ -318,5 +322,56 @@ private Expression DoDecimalCompare(SqlExpression visitedExpression, ExpressionT
_ => visitedExpression
};
}

private static bool AttemptDecimalArithmetic(SqlBinaryExpression sqlBinary) =>
AreOperandsDecimals(sqlBinary)
&& new[] { ExpressionType.Add, ExpressionType.Subtract, ExpressionType.Multiply, ExpressionType.Divide }.Contains(
sqlBinary.OperatorType);

private Expression DoDecimalArithmetics(SqlExpression visitedExpression, ExpressionType op, SqlExpression left, SqlExpression right)
{
return op switch
{
ExpressionType.Add => DecimalArithmeticExpressionFactoryMethod(ResolveFunctionNameFromExpressionType(op), left, right),
ExpressionType.Divide => DecimalArithmeticExpressionFactoryMethod(ResolveFunctionNameFromExpressionType(op), left, right),
ExpressionType.Multiply => DecimalArithmeticExpressionFactoryMethod(ResolveFunctionNameFromExpressionType(op), left, right),
ExpressionType.Subtract => DecimalSubtractExpressionFactoryMethod(left, right),
_ => visitedExpression
};

static string ResolveFunctionNameFromExpressionType(ExpressionType expressionType)
{
return expressionType switch
{
ExpressionType.Add => "ef_add",
ExpressionType.Divide => "ef_divide",
ExpressionType.Multiply => "ef_multiply",
ExpressionType.Subtract => "ef_add",
_ => throw new InvalidOperationException()
};
}

Expression DecimalArithmeticExpressionFactoryMethod(string name, SqlExpression left, SqlExpression right)
{
return Dependencies.SqlExpressionFactory.Function(
name,
new[] { left, right },
nullable: true,
new[] { true, true },
visitedExpression.Type);
}

Expression DecimalSubtractExpressionFactoryMethod(SqlExpression left, SqlExpression right)
{
var subtrahend = Dependencies.SqlExpressionFactory.Function(
"ef_negate",
new[] { right },
nullable: true,
new[] { true },
visitedExpression.Type);

return DecimalArithmeticExpressionFactoryMethod(ResolveFunctionNameFromExpressionType(op), left, subtrahend);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,35 @@ private void InitializeDbConnection(DbConnection connection)
% Convert.ToDouble(divisor, CultureInfo.InvariantCulture);
});

sqliteConnection.CreateFunction(
name: "ef_add",
(decimal? left, decimal? right) => left + right,
isDeterministic: true);

sqliteConnection.CreateFunction(
name: "ef_divide",
(decimal? dividend, decimal? divisor) => dividend / divisor,
isDeterministic: true);

sqliteConnection.CreateFunction(
name: "ef_compare",
(decimal? left, decimal? right) => left.HasValue && right.HasValue
? decimal.Compare(left.Value, right.Value)
: default(int?),
isDeterministic: true);

sqliteConnection.CreateFunction(
name: "ef_multiply",
(decimal? left, decimal? right) => left * right,
isDeterministic: true);

sqliteConnection.CreateFunction(
name: "ef_negate",
(decimal? m) => -m,
isDeterministic: true);
}
else

{
_logger.UnexpectedConnectionTypeWarning(connection.GetType());
}
Expand Down
47 changes: 47 additions & 0 deletions test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1505,6 +1505,53 @@ public override void Object_to_string_conversion()
WHERE ""b"".""Id"" = 13");
}

[ConditionalFact]
public virtual void Projecting_aritmetic_operations_on_decimals()
{
using var context = CreateContext();
var expected = (from dt1 in context.Set<BuiltInDataTypes>().ToList()
from dt2 in context.Set<BuiltInDataTypes>().ToList()
orderby dt1.Id, dt2.Id
select new
{
add = dt1.TestDecimal + dt2.TestDecimal,
subtract = dt1.TestDecimal - dt2.TestDecimal,
multiply = dt1.TestDecimal * dt2.TestDecimal,
divide = dt1.TestDecimal / dt2.TestDecimal,
negate = -dt1.TestDecimal
}).ToList();

Fixture.TestSqlLoggerFactory.Clear();

var actual = (from dt1 in context.Set<BuiltInDataTypes>()
from dt2 in context.Set<BuiltInDataTypes>()
orderby dt1.Id, dt2.Id
select new
{
add = dt1.TestDecimal + dt2.TestDecimal,
subtract = dt1.TestDecimal - dt2.TestDecimal,
multiply = dt1.TestDecimal * dt2.TestDecimal,
divide = dt1.TestDecimal / dt2.TestDecimal,
negate = -dt1.TestDecimal
}).ToList();

Assert.Equal(expected.Count, actual.Count);
for (var i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i].add, actual[i].add);
Assert.Equal(expected[i].subtract, actual[i].subtract);
Assert.Equal(expected[i].multiply, actual[i].multiply);
Assert.Equal(expected[i].divide, actual[i].divide);
Assert.Equal(expected[i].negate, actual[i].negate);
}

AssertSql(
@"SELECT ef_add(""b"".""TestDecimal"", ""b0"".""TestDecimal"") AS ""add"", ef_add(""b"".""TestDecimal"", ef_negate(""b0"".""TestDecimal"")) AS ""subtract"", ef_multiply(""b"".""TestDecimal"", ""b0"".""TestDecimal"") AS ""multiply"", ef_divide(""b"".""TestDecimal"", ""b0"".""TestDecimal"") AS ""divide"", ef_negate(""b"".""TestDecimal"") AS ""negate""
FROM ""BuiltInDataTypes"" AS ""b""
CROSS JOIN ""BuiltInDataTypes"" AS ""b0""
ORDER BY ""b"".""Id"", ""b0"".""Id""");
}

private void AssertTranslationFailed(Action testCode)
=> Assert.Contains(
CoreStrings.TranslationFailed("").Substring(21),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.EntityFrameworkCore.Query
Expand All @@ -17,15 +19,15 @@ public NorthwindAggregateOperatorsQuerySqliteTest(NorthwindQuerySqliteFixture<No
}

public override Task Sum_with_division_on_decimal(bool async)
=> AssertTranslationFailed(() => base.Sum_with_division_on_decimal(async));
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Sum_with_division_on_decimal(async));

public override Task Sum_with_division_on_decimal_no_significant_digits(bool async)
=> AssertTranslationFailed(() => base.Sum_with_division_on_decimal_no_significant_digits(async));
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Sum_with_division_on_decimal_no_significant_digits(async));

public override Task Average_with_division_on_decimal(bool async)
=> AssertTranslationFailed(() => base.Average_with_division_on_decimal(async));
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Average_with_division_on_decimal(async));

public override Task Average_with_division_on_decimal_no_significant_digits(bool async)
=> AssertTranslationFailed(() => base.Average_with_division_on_decimal_no_significant_digits(async));
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Average_with_division_on_decimal_no_significant_digits(async));
}
}