Skip to content

Commit

Permalink
Adjusted code due to breaking change in EF 9
Browse files Browse the repository at this point in the history
  • Loading branch information
PawelGerr committed Nov 12, 2024
1 parent 6388d3f commit 33bf654
Show file tree
Hide file tree
Showing 28 changed files with 268 additions and 238 deletions.
80 changes: 41 additions & 39 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
name: CI

on:
push

env:
UseSqlServerContainer: true

jobs:
build:
runs-on: ubuntu-latest

steps:

- name: install .NET Core 8 SDK
uses: actions/setup-dotnet@v2
with:
dotnet-version: 8.0.x
include-prerelease: false

- name: checkout repository
uses: actions/checkout@v2

- name: dotnet restore
run: dotnet restore

- name: build
run: dotnet build --configuration Release --no-restore

- name: test
run: dotnet test --configuration Release --no-build

- name: test results
uses: EnricoMi/publish-unit-test-result-action@v2
id: test-results
if: always()
with:
check_name: tests results
trx_files: "**/test-results/**/*.trx"
name: CI

on:
push

env:
UseSqlServerContainer: true

jobs:
build:
runs-on: ubuntu-latest

steps:

- name: install .NET Core 8/9 SDKs
uses: actions/setup-dotnet@v2
with:
include-prerelease: false
dotnet-version: |
8.0.x
9.0.x
- name: checkout repository
uses: actions/checkout@v2

- name: dotnet restore
run: dotnet restore

- name: build
run: dotnet build --configuration Release --no-restore

- name: test
run: dotnet test --configuration Release --no-build

- name: test results
uses: EnricoMi/publish-unit-test-result-action@v2
id: test-results
if: always()
with:
check_name: tests results
trx_files: "**/test-results/**/*.trx"
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<Copyright>(c) $([System.DateTime]::Now.Year), Pawel Gerr. All rights reserved.</Copyright>
<VersionPrefix>8.1.1</VersionPrefix>
<VersionPrefix>9.0.0</VersionPrefix>
<Authors>Pawel Gerr</Authors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageProjectUrl>https://dev.azure.com/pawelgerr/Thinktecture.EntityFrameworkCore</PackageProjectUrl>
Expand All @@ -13,7 +13,7 @@
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<RootNamespace>Thinktecture</RootNamespace>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<LangVersion>13.0</LangVersion>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);CA1303;MSB3884;</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
Expand Down
16 changes: 8 additions & 8 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
<ItemGroup>
<PackageVersion Include="BenchmarkDotNet" Version="0.14.0" />
<PackageVersion Include="FluentAssertions" Version="6.12.2" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.10" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.10" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.10" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="8.0.10" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="9.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageVersion Include="Microsoft.SourceLink.AzureRepos.Git" Version="8.0.0" PrivateAssets="all" />
<PackageVersion Include="NSubstitute" Version="5.3.0" />
Expand Down
8 changes: 8 additions & 0 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ steps:
includePreviewVersions: false
installationPath: $(Agent.ToolsDirectory)/dotnet

- task: UseDotNet@2
displayName: 'use .NET 9.0 SDK'
inputs:
packageType: sdk
version: 9.0.x
includePreviewVersions: false
installationPath: $(Agent.ToolsDirectory)/dotnet

- script: |
echo dotnet --version
dotnet --version
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
Expand All @@ -10,6 +11,8 @@ namespace Thinktecture.EntityFrameworkCore.Query.SqlExpressions;
/// </summary>
public sealed class WindowFunctionOrderingsExpression : SqlExpression, INotNullableSqlExpression
{
private static readonly ConstructorInfo _quotingConstructor = typeof(WindowFunctionOrderingsExpression).GetConstructors().Single();

/// <summary>
/// Orderings.
/// </summary>
Expand Down Expand Up @@ -39,6 +42,13 @@ protected override Expression VisitChildren(ExpressionVisitor visitor)
return ReferenceEquals(visited, Orderings) ? this : new WindowFunctionOrderingsExpression(visited);
}

/// <inheritdoc />
public override Expression Quote()
{
return New(_quotingConstructor,
NewArrayInit(typeof(OrderingExpression), initializers: Orderings.Select(o => o.Quote())));
}

/// <inheritdoc />
protected override void Print(ExpressionPrinter expressionPrinter)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
Expand All @@ -10,6 +11,8 @@ namespace Thinktecture.EntityFrameworkCore.Query.SqlExpressions;
/// </summary>
public class WindowFunctionPartitionByExpression : SqlExpression, INotNullableSqlExpression
{
private static readonly ConstructorInfo _quotingConstructor = typeof(WindowFunctionPartitionByExpression).GetConstructors().Single();

/// <summary>
/// Partition by expressions.
/// </summary>
Expand Down Expand Up @@ -39,6 +42,13 @@ protected override Expression VisitChildren(ExpressionVisitor visitor)
return ReferenceEquals(visited, PartitionBy) ? this : new WindowFunctionPartitionByExpression(visited);
}

/// <inheritdoc />
public override Expression Quote()
{
return New(_quotingConstructor,
NewArrayInit(typeof(SqlExpression), initializers: PartitionBy.Select(o => o.Quote())));
}

/// <inheritdoc />
protected override void Print(ExpressionPrinter expressionPrinter)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public class ThinktectureSqlNullabilityProcessor : SqlNullabilityProcessor
/// <inheritdoc />
public ThinktectureSqlNullabilityProcessor(
RelationalParameterBasedSqlProcessorDependencies dependencies,
bool useRelationalNulls)
: base(dependencies, useRelationalNulls)
RelationalParameterBasedSqlProcessorParameters parameters)
: base(dependencies, parameters)
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Thinktecture.EntityFrameworkCore;
using Thinktecture.EntityFrameworkCore.Internal;
using Thinktecture.Internal;

Expand Down Expand Up @@ -54,8 +55,13 @@ private static Expression TranslateTableHints(
ShapedQueryExpression shapedQueryExpression,
MethodCallExpression methodCallExpression)
{
var tableHintsExpression = (TableHintsExpression)methodCallExpression.Arguments[1] ?? throw new InvalidOperationException("Table hints cannot be null.");
var tableHints = tableHintsExpression.Value ?? throw new Exception("No table hints provided.");
var hintArgs = methodCallExpression.Arguments[1];
var tableHints = hintArgs switch
{
TableHintsExpression tableHintsExpression => tableHintsExpression.Value,
ConstantExpression constantExpression => (IReadOnlyList<ITableHint>?)constantExpression.Value ?? throw new Exception("No table hints provided."),
_ => throw new NotSupportedException($"Table hint argument of type '{hintArgs.GetType().FullName}' is not supported.")
};

if (tableHints.Count == 0)
return shapedQueryExpression;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,76 +239,6 @@ protected virtual IDbContextTransaction BeginTransaction(T ctx)
return ctx.Database.BeginTransaction(_sharedTablesIsolationLevel);
}

/// <summary>
/// Starts a new transaction for migration and cleanup.
/// </summary>
/// <param name="ctx">Database context.</param>
/// <returns>An instance of <see cref="IDbContextTransaction"/>.</returns>
protected virtual IDbContextTransaction? BeginMigrationAndCleanupTransaction(T ctx)
{
ArgumentNullException.ThrowIfNull(ctx);

if (!_lockTableEnabled)
return ctx.Database.BeginTransaction(IsolationLevel.Serializable);

var sqlGenerationHelper = ctx.GetService<ISqlGenerationHelper>();
var lockTableName = sqlGenerationHelper.DelimitIdentifier(_lockTableName, _lockTableSchema);

CreateTestIsolationTable(ctx, lockTableName);

for (var i = 0;; i++)
{
var tx = ctx.Database.BeginTransaction(IsolationLevel.Serializable);

try
{
LockDatabase(ctx, lockTableName);
return tx;
}
catch (Exception)
{
tx.Dispose();

if (i > _maxNumberOfLockRetries)
throw;

var delay = new TimeSpan(_random.NextInt64(_minRetryDelay.Ticks, _maxRetryDelay.Ticks));
Task.Delay(delay).GetAwaiter().GetResult();
}
}
}

private void CreateTestIsolationTable(T ctx, string lockTableName)
{
var createTableSql = $"""
IF(OBJECT_ID('{lockTableName}') IS NULL)
CREATE TABLE {lockTableName}(Id INT NOT NULL)
""";

for (var i = 0;; i++)
{
try
{
ctx.Database.ExecuteSqlRaw(createTableSql);
return;
}
catch (Exception)
{
if (i > _maxNumberOfLockRetries)
throw;

var delay = new TimeSpan(_random.NextInt64(_minRetryDelay.Ticks, _maxRetryDelay.Ticks));
Task.Delay(delay).GetAwaiter().GetResult();
}
}
}

private static void LockDatabase(T ctx, string lockTableName)
{
var selectSql = $"SELECT * FROM {lockTableName} WITH (HOLDLOCK, UPDLOCK)";
ctx.Database.ExecuteSqlRaw(selectSql);
}

/// <summary>
/// Runs migrations for provided <paramref name="ctx" />.
/// </summary>
Expand All @@ -326,21 +256,7 @@ protected virtual void RunMigrations(T ctx)
try
{
LogLevelSwitch.MinimumLogLevel = _testingLoggingOptions.MigrationLogLevel;

IDbContextTransaction? migrationTx = null;

if (ctx.Database.CurrentTransaction is null)
migrationTx = BeginMigrationAndCleanupTransaction(ctx);

try
{
_migrationExecutionStrategy.Migrate(ctx);
migrationTx?.Commit();
}
finally
{
migrationTx?.Dispose();
}
_migrationExecutionStrategy.Migrate(ctx);
}
finally
{
Expand Down Expand Up @@ -427,22 +343,7 @@ private async Task DisposeContextsAndRollbackMigrationsAsync(CancellationToken c
{
// Create a new ctx as a last resort to rollback migrations and clean up the database
await using var ctx = _actDbContext ?? _arrangeDbContext ?? _assertDbContext ?? CreateDbContext(_masterDbContextOptions, Schema is null ? null : new DbDefaultSchema(Schema));

IDbContextTransaction? migrationTx = null;

if (ctx.Database.CurrentTransaction is null)
migrationTx = BeginMigrationAndCleanupTransaction(ctx);

try
{
await _isolationOptions.CleanupAsync(ctx, Schema, cancellationToken);

await (migrationTx?.CommitAsync(cancellationToken) ?? Task.CompletedTask);
}
finally
{
await (migrationTx?.DisposeAsync() ?? ValueTask.CompletedTask);
}
await _isolationOptions.CleanupAsync(ctx, Schema, cancellationToken);
}

await (_arrangeDbContext?.DisposeAsync() ?? ValueTask.CompletedTask);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Microsoft.EntityFrameworkCore.Storage;

namespace Thinktecture.EntityFrameworkCore.Query.SqlExpressions;
Expand All @@ -11,6 +12,8 @@ namespace Thinktecture.EntityFrameworkCore.Query.SqlExpressions;
/// </summary>
public class WindowFunctionExpression : SqlExpression
{
private static readonly ConstructorInfo _quotingConstructor = typeof(WindowFunctionExpression).GetConstructors().Single();

/// <summary>
/// Creates a new instance of the <see cref="WindowFunctionExpression" /> class.
/// </summary>
Expand Down Expand Up @@ -75,6 +78,20 @@ protected override Expression VisitChildren(ExpressionVisitor visitor)
: this;
}

/// <inheritdoc />
[Experimental("EF9100")]
public override Expression Quote()
{
return New(_quotingConstructor,
Constant(Name),
Constant(UseAsteriskWhenNoArguments),
Constant(Type),
RelationalExpressionQuotingUtilities.QuoteTypeMapping(TypeMapping),
NewArrayInit(typeof(SqlExpression), Arguments.Select(a => a.Quote())),
NewArrayInit(typeof(SqlExpression), Partitions.Select(p => p.Quote())),
NewArrayInit(typeof(OrderingExpression), Orderings.Select(o => o.Quote())));
}

/// <inheritdoc />
protected override void Print(ExpressionPrinter expressionPrinter)
{
Expand Down
Loading

0 comments on commit 33bf654

Please sign in to comment.