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

Add MATCH strategies to FK configuration #3243

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
@@ -0,0 +1,66 @@
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore;

/// <summary>
/// Npgsql specific extension methods for configuring foreign keys.
/// </summary>
public static class NpgsqlForeignKeyBuilderExtensions
{
/// <summary>
/// Configure the matching strategy to be used with the foreign key.
/// </summary>
/// <param name="builder">The builder for the foreign key being configured.</param>
/// <param name="matchStrategy">The <see cref="PostgresMatchStrategy"/> defining the used matching strategy.</param>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public static ReferenceReferenceBuilder UsesMatchStrategy(this ReferenceReferenceBuilder builder, PostgresMatchStrategy matchStrategy){
Check.NotNull(builder, nameof(builder));
Check.IsDefined(matchStrategy);
builder.Metadata.SetMatchStrategy(matchStrategy);
return builder;
}

/// <summary>
/// Configure the matching strategy to be used with the foreign key.
/// </summary>
/// <param name="builder">The builder for the foreign key being configured.</param>
/// <param name="matchStrategy">The <see cref="PostgresMatchStrategy"/> defining the used matching strategy.</param>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public static ReferenceReferenceBuilder<TEntity, TRelatedEntity> UsesMatchStrategy<TEntity, TRelatedEntity>(this ReferenceReferenceBuilder<TEntity, TRelatedEntity> builder, PostgresMatchStrategy matchStrategy)
where TEntity : class
where TRelatedEntity : class
=> (ReferenceReferenceBuilder<TEntity, TRelatedEntity>)UsesMatchStrategy((ReferenceReferenceBuilder)builder, matchStrategy);

/// <summary>
/// Configure the matching strategy to be used with the foreign key.
/// </summary>
/// <param name="builder">The builder for the foreign key being configured.</param>
/// <param name="matchStrategy">The <see cref="PostgresMatchStrategy"/> defining the used matching strategy.</param>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public static ReferenceCollectionBuilder UsesMatchStrategy(this ReferenceCollectionBuilder builder, PostgresMatchStrategy matchStrategy){
Check.NotNull(builder, nameof(builder));
Check.IsDefined(matchStrategy);
builder.Metadata.SetMatchStrategy(matchStrategy);
return builder;
}

/// <summary>
/// Configure the matching strategy to be used with the foreign key.
/// </summary>
/// <param name="builder">The builder for the foreign key being configured.</param>
/// <param name="matchStrategy">The <see cref="PostgresMatchStrategy"/> defining the used matching strategy.</param>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public static ReferenceCollectionBuilder UsesMatchStrategy<TEntity, TRelatedEntity>(this ReferenceCollectionBuilder<TEntity, TRelatedEntity> builder, PostgresMatchStrategy matchStrategy)
where TEntity : class
where TRelatedEntity : class
=> (ReferenceCollectionBuilder<TEntity, TRelatedEntity>)UsesMatchStrategy((ReferenceCollectionBuilder)builder, matchStrategy);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

// ReSharper disable once CheckNamespace
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;

namespace Microsoft.EntityFrameworkCore;

/// <summary>
/// Npgsql specific extension methods for <see cref="IForeignKey"/>.
/// </summary>
public static class NpgsqlForeignKeyExtensions
{
/// <summary>
/// Sets the <see cref="PostgresMatchStrategy"/> for a foreign key.
/// </summary>
/// <param name="foreignKey">the foreign key being configured.</param>
/// <param name="matchStrategy">the <see cref="PostgresMatchStrategy"/> defining the used matching strategy.</param>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public static void SetMatchStrategy(this IMutableForeignKey foreignKey, PostgresMatchStrategy matchStrategy)
=> foreignKey.SetOrRemoveAnnotation(NpgsqlAnnotationNames.MatchStrategy, matchStrategy);

/// <summary>
/// Returns the assigned <see cref="PostgresMatchStrategy"/> for the provided foreign key
/// </summary>
/// <param name="foreignKey">the foreign key</param>
/// <returns>the <see cref="PostgresMatchStrategy"/> if assigned, null otherwise</returns>
public static PostgresMatchStrategy? GetMatchStrategy(this IReadOnlyForeignKey foreignKey) =>
(PostgresMatchStrategy?)foreignKey[NpgsqlAnnotationNames.MatchStrategy];
}
8 changes: 8 additions & 0 deletions src/EFCore.PG/Metadata/Internal/NpgsqlAnnotationNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,4 +271,12 @@ public static class NpgsqlAnnotationNames
/// </summary>
// Replaced by IsDescending in EF Core 7.0
public const string IndexSortOrder = Prefix + "IndexSortOrder";

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string MatchStrategy = Prefix + "MatchStrategy";
}
21 changes: 21 additions & 0 deletions src/EFCore.PG/Metadata/Internal/NpgsqlAnnotationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,27 @@ public override IEnumerable<IAnnotation> For(ITableIndex index, bool designTime)
}
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override IEnumerable<IAnnotation> For(IForeignKeyConstraint foreignKey, bool designTime){
if (!designTime)
{
yield break;
}

foreach (var item in foreignKey.MappedForeignKeys)
{
if (item.GetMatchStrategy() is {} match)
{
yield return new Annotation(NpgsqlAnnotationNames.MatchStrategy, match);
}
}
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
23 changes: 23 additions & 0 deletions src/EFCore.PG/Metadata/PostgresMatchStrategy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

/// <summary>
/// Matching strategies for a foreign key.
/// </summary>
/// <remarks>
/// <see href="https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES"/>
/// </remarks>
public enum PostgresMatchStrategy
{
/// <summary>
/// The default matching strategy, allows any foreign key column to be NULL.
/// </summary>
Simple = 0,
/// <summary>
/// Currently not implemented in PostgreSQL.
/// </summary>
Partial = 1,
/// <summary>
/// Requires the foreign key to either have all columns to be set or all columns to be NULL.
/// </summary>
Full = 2
}
49 changes: 49 additions & 0 deletions src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.ComponentModel;
using System.Globalization;
using System.Text;
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
Expand Down Expand Up @@ -1464,6 +1465,54 @@ protected virtual void GenerateDropRange(PostgresRange rangeType, IModel? model,

#endregion Range management


#region MatchingStrategy management


/// <inheritdoc/>
protected override void ForeignKeyConstraint(AddForeignKeyOperation operation, IModel? model, MigrationCommandListBuilder builder){
if (operation.Name != null)
{
builder.Append("CONSTRAINT ").Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)).Append(" ");
}

builder.Append("FOREIGN KEY (").Append(ColumnList(operation.Columns)).Append(") REFERENCES ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.PrincipalTable, operation.PrincipalSchema));
if (operation.PrincipalColumns != null)
{
builder.Append(" (").Append(ColumnList(operation.PrincipalColumns)).Append(")");
}

if (operation[NpgsqlAnnotationNames.MatchStrategy] is PostgresMatchStrategy matchStrategy)
{
builder.Append(" MATCH ")
.Append(TranslateMatchStrategy(matchStrategy));

}

if (operation.OnUpdate != 0)
{
builder.Append(" ON UPDATE ");
ForeignKeyAction(operation.OnUpdate, builder);
}

if (operation.OnDelete != 0)
{
builder.Append(" ON DELETE ");
ForeignKeyAction(operation.OnDelete, builder);
}
}

private string TranslateMatchStrategy(PostgresMatchStrategy matchStrategy)
=> matchStrategy switch {
PostgresMatchStrategy.Simple => "SIMPLE",
PostgresMatchStrategy.Partial => "PARTIAL",
PostgresMatchStrategy.Full => "FULL",
_ => throw new InvalidEnumArgumentException(nameof(matchStrategy), (int)matchStrategy, typeof(PostgresMatchStrategy))
};

#endregion MatchingStrategy management

/// <inheritdoc />
protected override void Generate(
DropIndexOperation operation,
Expand Down
12 changes: 12 additions & 0 deletions src/Shared/Check.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;

namespace Microsoft.EntityFrameworkCore.Utilities;
Expand Down Expand Up @@ -127,4 +129,14 @@ public static void DebugAssert([DoesNotReturnIf(false)] bool condition, string m
[DoesNotReturn]
public static void DebugFail(string message)
=> throw new Exception($"Check.DebugFail failed: {message}");

public static void IsDefined<T>(T value,
[InvokerParameterName, CallerArgumentExpression(nameof(value))] string? parameterName = null)
where T : struct, Enum
{
if (!Enum.IsDefined(value))
{
throw new InvalidEnumArgumentException(parameterName, Convert.ToInt32(value), typeof(T));
}
}
}
43 changes: 43 additions & 0 deletions test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2549,6 +2549,49 @@ public override async Task Drop_check_constraint()
AssertSql("""ALTER TABLE "People" DROP CONSTRAINT "CK_People_Foo";""");
}

[Theory]
[InlineData(PostgresMatchStrategy.Simple, "SIMPLE", false)]
[InlineData(PostgresMatchStrategy.Partial, "PARTIAL", true)]
[InlineData(PostgresMatchStrategy.Full, "FULL", false)]
public async Task Add_foreign_key_with_match_strategy(PostgresMatchStrategy strategy, string matchValue, bool throws)
{
Task runningTest = Test(
builder => {
builder.Entity("Customers", delegate (EntityTypeBuilder e)
{
e.Property<int>("Id");
e.HasKey("Id");
e.Property<int>("AddressId");
});
builder.Entity("Orders", delegate (EntityTypeBuilder e)
{
e.Property<int>("Id");
e.Property<int>("CustomerId");
});
},
_ => {},
builder => {
builder.Entity("Orders")
.HasOne("Customers")
.WithMany()
.HasForeignKey("CustomerId")
.UsesMatchStrategy(strategy)
.HasConstraintName("FK_Foo");
},
asserter: null);

if (throws)
{
await Assert.ThrowsAsync<PostgresException>(() => runningTest);
}else{
await runningTest;
}

AssertSql(
"""CREATE INDEX "IX_Orders_CustomerId" ON "Orders" ("CustomerId");""",
$"""ALTER TABLE "Orders" ADD CONSTRAINT "FK_Foo" FOREIGN KEY ("CustomerId") REFERENCES "Customers" ("Id") MATCH {matchValue} ON DELETE CASCADE;""");
}

#endregion

#region Sequence
Expand Down