Skip to content

Commit

Permalink
Additional improvements and code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
artiomchi committed Nov 21, 2024
1 parent cf9171e commit 05fc67a
Show file tree
Hide file tree
Showing 17 changed files with 51 additions and 67 deletions.
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<Project>

<Sdk Name="DotNet.ReproducibleBuilds.Isolated" Version="1.1.1" />
<Sdk Name="DotNet.ReproducibleBuilds.Isolated" Version="1.2.25" />

<ItemGroup>
<PackageReference Include="DotNet.ReproducibleBuilds" Version="1.1.1" PrivateAssets="All"/>
<PackageReference Include="DotNet.ReproducibleBuilds" Version="1.2.25" PrivateAssets="All"/>
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions FlexLabs.Upsert.sln
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".solution", ".solution", "{
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
build.release.signed.bat = build.release.signed.bat
Directory.Build.props = Directory.Build.props
README.md = README.md
EndProjectSection
EndProject
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Metadata;

Expand Down Expand Up @@ -52,7 +51,7 @@ public IEnumerable<ConstantValue> GetConstantValues()
/// <inheritdoc/>
public IEnumerable<PropertyValue> GetPropertyValues()
{
return Array.Empty<PropertyValue>();
return [];
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Metadata;

namespace FlexLabs.EntityFrameworkCore.Upsert.Internal
Expand Down Expand Up @@ -40,7 +39,7 @@ public PropertyValue(string propertyName, bool isLeftParameter, IProperty proper
/// <inheritdoc/>
public IEnumerable<ConstantValue> GetConstantValues()
{
return Array.Empty<ConstantValue>();
return [];
}

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Globalization;

namespace FlexLabs.EntityFrameworkCore.Upsert
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand Down Expand Up @@ -107,7 +106,7 @@ public EntityMatch(TEntity? dbEntity, TEntity newEntity)
public TEntity NewEntity;
}

private static ICollection<EntityMatch<TEntity>> FindMatches<TEntity>(IEntityType entityType, IEnumerable<TEntity> entities, DbContext dbContext,
private static EntityMatch<TEntity>[] FindMatches<TEntity>(IEntityType entityType, IEnumerable<TEntity> entities, DbContext dbContext,
Expression<Func<TEntity, object>>? matchExpression) where TEntity : class
{
if (matchExpression != null)
Expand All @@ -119,7 +118,7 @@ private static ICollection<EntityMatch<TEntity>> FindMatches<TEntity>(IEntityTyp
// If we're resorting to matching on PKs, we'll have to load them manually
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
return Array.Empty<EntityMatch<TEntity>>();
return [];

object?[] getPKs(TEntity entity)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using FlexLabs.EntityFrameworkCore.Upsert.Internal;
Expand Down Expand Up @@ -33,7 +34,7 @@ public override string GenerateCommand(string tableName, ICollection<ICollection
var result = new StringBuilder("INSERT ");
if (updateExpressions == null)
result.Append("IGNORE ");
result.Append($"INTO {tableName} (");
result.Append(CultureInfo.InvariantCulture, $"INTO {tableName} (");
result.Append(string.Join(", ", entities.First().Select(e => EscapeName(e.ColumnName))));
result.Append(") VALUES (");
result.Append(string.Join("), (", entities.Select(ec => string.Join(", ", ec.Select(e => e.DefaultSql ?? Parameter(e.Value.ArgumentIndex))))));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using FlexLabs.EntityFrameworkCore.Upsert.Internal;
Expand Down Expand Up @@ -27,7 +28,7 @@ public override string GenerateCommand(string tableName, ICollection<ICollection
KnownExpression? updateCondition)
{
var result = new StringBuilder();
result.Append($"INSERT INTO {tableName} AS \"T\" (");
result.Append(CultureInfo.InvariantCulture, $"INSERT INTO {tableName} AS \"T\" (");
result.Append(string.Join(", ", entities.First().Select(e => EscapeName(e.ColumnName))));
result.Append(") VALUES (");
result.Append(string.Join("), (", entities.Select(ec => string.Join(", ", ec.Select(e => e.DefaultSql ?? Parameter(e.Value.ArgumentIndex))))));
Expand All @@ -39,7 +40,7 @@ public override string GenerateCommand(string tableName, ICollection<ICollection
result.Append("UPDATE SET ");
result.Append(string.Join(", ", updateExpressions.Select((e, i) => $"{EscapeName(e.ColumnName)} = {ExpandValue(e.Value)}")));
if (updateCondition != null)
result.Append($" WHERE {ExpandExpression(updateCondition)}");
result.Append(CultureInfo.InvariantCulture, $" WHERE {ExpandExpression(updateCondition)}");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
Expand Down Expand Up @@ -116,13 +115,11 @@ protected virtual string GetTableName(IEntityType entityType)
if (updater.Body is not MemberInitExpression entityUpdater)
throw new ArgumentException(Resources.FormatUpdaterMustBeAnInitialiserOfTheTEntityType(nameof(updater)), nameof(updater));

updateExpressions = new List<(IProperty Property, IKnownValue Value)>();
updateExpressions = [];
foreach (MemberAssignment binding in entityUpdater.Bindings)
{
var property = entityType.FindProperty(binding.Member.Name);
if (property == null)
throw new InvalidOperationException("Unknown property " + binding.Member.Name);

var property = entityType.FindProperty(binding.Member.Name)
?? throw new InvalidOperationException("Unknown property " + binding.Member.Name);
var value = binding.Expression.GetValue<TEntity>(updater, entityType.FindProperty, queryOptions.UseExpressionCompiler);
if (value is not IKnownValue knownVal)
knownVal = new ConstantValue(value, property);
Expand All @@ -132,7 +129,7 @@ protected virtual string GetTableName(IEntityType entityType)
}
else if (!queryOptions.NoUpdate)
{
updateExpressions = new List<(IProperty Property, IKnownValue Value)>();
updateExpressions = [];
foreach (var property in properties)
{
if (joinColumnNames.Any(c => c.ColumnName == property.GetColumnName()))
Expand Down Expand Up @@ -399,7 +396,7 @@ public override async Task<int> RunAsync<TEntity>(DbContext dbContext, IEntityTy
return result;
}

private object PrepareDbCommandArgument(DbCommand dbCommand, IRelationalTypeMappingSource relationalTypeMappingSource, ConstantValue constantValue)
private DbParameter PrepareDbCommandArgument(DbCommand dbCommand, IRelationalTypeMappingSource relationalTypeMappingSource, ConstantValue constantValue)
{
RelationalTypeMapping? relationalTypeMapping = null;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
using System.Diagnostics.CodeAnalysis;

namespace FlexLabs.EntityFrameworkCore.Upsert.Runners
namespace FlexLabs.EntityFrameworkCore.Upsert.Runners
{
/// <summary>
/// Options to configure the query behaviour
/// </summary>
[SuppressMessage("Performance", "CA1815:Override equals and operator equals on value types", Justification = "There would be no need to compare instances of these options")]
public struct RunnerQueryOptions

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Ubuntu (full)

RunnerQueryOptions should override Equals (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Ubuntu (full)

RunnerQueryOptions should override the equality (==) and inequality (!=) operators (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Ubuntu (full)

RunnerQueryOptions should override Equals (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Ubuntu (full)

RunnerQueryOptions should override the equality (==) and inequality (!=) operators (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Windows

RunnerQueryOptions should override Equals (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Windows

RunnerQueryOptions should override the equality (==) and inequality (!=) operators (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Windows

RunnerQueryOptions should override Equals (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)

Check warning on line 6 in src/FlexLabs.EntityFrameworkCore.Upsert/Runners/RunnerQueryOptions.cs

View workflow job for this annotation

GitHub Actions / Build on Windows

RunnerQueryOptions should override the equality (==) and inequality (!=) operators (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815)
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using FlexLabs.EntityFrameworkCore.Upsert.Internal;
Expand Down Expand Up @@ -27,7 +28,7 @@ public override string GenerateCommand(string tableName, ICollection<ICollection
KnownExpression? updateCondition)
{
var result = new StringBuilder();
result.Append($"MERGE INTO {tableName} WITH (HOLDLOCK) AS [T] USING ( VALUES (");
result.Append(CultureInfo.InvariantCulture, $"MERGE INTO {tableName} WITH (HOLDLOCK) AS [T] USING ( VALUES (");
result.Append(string.Join("), (", entities.Select(ec => string.Join(", ", ec.Select(e => e.DefaultSql ?? Parameter(e.Value.ArgumentIndex))))));
result.Append($") ) AS [S] (");
result.Append(string.Join(", ", entities.First().Select(e => EscapeName(e.ColumnName))));
Expand All @@ -44,7 +45,7 @@ public override string GenerateCommand(string tableName, ICollection<ICollection
{
result.Append(" WHEN MATCHED");
if (updateCondition != null)
result.Append($" AND {ExpandExpression(updateCondition)}");
result.Append(CultureInfo.InvariantCulture, $" AND {ExpandExpression(updateCondition)}");
result.Append(" THEN UPDATE SET ");
result.Append(string.Join(", ", updateExpressions.Select((e, i) => $"{EscapeName(e.ColumnName)} = {ExpandValue(e.Value)}")));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand Down Expand Up @@ -50,34 +49,31 @@ protected static ICollection<IProperty> ProcessMatchExpression<TEntity>(IEntityT
}
else if (matchExpression.Body is NewExpression newExpression)
{
joinColumns = new List<IProperty>();
joinColumns = [];
foreach (MemberExpression arg in newExpression.Arguments)
{
if (arg == null || arg.Member is not PropertyInfo || !typeof(TEntity).Equals(arg.Expression?.Type))
throw new InvalidOperationException(Resources.MatchColumnsHaveToBePropertiesOfTheTEntityClass);
var property = entityType.FindProperty(arg.Member.Name);
if (property == null)
throw new InvalidOperationException(Resources.FormatUnknownProperty(arg.Member.Name));
var property = entityType.FindProperty(arg.Member.Name)
?? throw new InvalidOperationException(Resources.FormatUnknownProperty(arg.Member.Name));
joinColumns.Add(property);
}
}
else if (matchExpression.Body is UnaryExpression unaryExpression)
{
if (unaryExpression.Operand is not MemberExpression memberExp || memberExp.Member is not PropertyInfo || !typeof(TEntity).Equals(memberExp.Expression?.Type))
throw new InvalidOperationException(Resources.MatchColumnsHaveToBePropertiesOfTheTEntityClass);
var property = entityType.FindProperty(memberExp.Member.Name);
if (property == null)
throw new InvalidOperationException(Resources.FormatUnknownProperty(memberExp.Member.Name));
joinColumns = new List<IProperty> { property };
var property = entityType.FindProperty(memberExp.Member.Name)
?? throw new InvalidOperationException(Resources.FormatUnknownProperty(memberExp.Member.Name));
joinColumns = [property];
}
else if (matchExpression.Body is MemberExpression memberExpression)
{
if (!typeof(TEntity).Equals(memberExpression.Expression?.Type) || memberExpression.Member is not PropertyInfo)
throw new InvalidOperationException(Resources.MatchColumnsHaveToBePropertiesOfTheTEntityClass);
var property = entityType.FindProperty(memberExpression.Member.Name);
if (property == null)
throw new InvalidOperationException(Resources.FormatUnknownProperty(memberExpression.Member.Name));
joinColumns = new List<IProperty> { property };
var property = entityType.FindProperty(memberExpression.Member.Name)
?? throw new InvalidOperationException(Resources.FormatUnknownProperty(memberExpression.Member.Name));
joinColumns = [property];
}
else
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Globalization;

namespace FlexLabs.EntityFrameworkCore.Upsert
{
Expand All @@ -23,7 +22,7 @@ internal UnsupportedExpressionException(System.Linq.Expressions.Expression expre
}

internal static UnsupportedExpressionException MySQLConditionalUpdate()
=> new UnsupportedExpressionException(Resources.UsingConditionalUpdatesIsNotSupportedInMySQLDueToDatabaseSyntaxLimitations + " " +
=> new(Resources.UsingConditionalUpdatesIsNotSupportedInMySQLDueToDatabaseSyntaxLimitations + " " +
Resources.FormatSeeLinkForMoreDetails(HelpLinks.MySQLConditionalUpdate),
HelpLinks.MySQLConditionalUpdate);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
Expand Down Expand Up @@ -171,10 +170,8 @@ private IUpsertCommandRunner GetCommandRunner()
var dbProvider = _dbContext.GetService<IDatabaseProvider>();
var commandRunner = _dbContext.GetInfrastructure().GetServices<IUpsertCommandRunner>()
.Concat(DefaultRunners.GetRunners())
.FirstOrDefault(r => r.Supports(dbProvider.Name));
if (commandRunner == null)
throw new NotSupportedException(Resources.DatabaseProviderNotSupportedYet);

.FirstOrDefault(r => r.Supports(dbProvider.Name))
?? throw new NotSupportedException(Resources.DatabaseProviderNotSupportedYet);
return commandRunner;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,24 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.8.0" />
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.*" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0-rc.2" />
<PackageReference Include="NSubstitute" Version="4.4.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.15">
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.0-beta.2" />
<PackageReference Include="Testcontainers.MsSql" Version="3.6.0" />
<PackageReference Include="Testcontainers.MySql" Version="3.6.0" />
<PackageReference Include="Testcontainers.PostgreSql" Version="3.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Testcontainers.MsSql" Version="4.0.0" />
<PackageReference Include="Testcontainers.MySql" Version="4.0.0" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.0.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.8.0" />
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.*" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="NSubstitute" Version="4.4.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.15">
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using System;
using System;
using System.Collections.Generic;
using System.Data.Common;
using FlexLabs.EntityFrameworkCore.Upsert.Runners;
using FlexLabs.EntityFrameworkCore.Upsert.Tests.Runners.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Storage;
Expand Down Expand Up @@ -75,9 +74,8 @@ protected static EntityType AddEntity<TEntity>(Model model)
{
entityType.AddProperty(property.Name, ConfigurationSource.Explicit);
}
var idProperty = entityType.FindProperty("ID");
if (idProperty == null)
throw new InvalidOperationException("ID property missing on entity " + typeof(TEntity).Name);
var idProperty = entityType.FindProperty("ID")
?? throw new InvalidOperationException("ID property missing on entity " + typeof(TEntity).Name);
entityType.AddKey(idProperty, ConfigurationSource.Convention);
return entityType;
}
Expand Down

0 comments on commit 05fc67a

Please sign in to comment.