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
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore;

/// <summary>
/// Npgsql specific extension methods for relationship builders.
/// </summary>
public static class NpgsqlForeignKeyBuilderExtensions
{
#region Period

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="referenceCollectionBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static ReferenceCollectionBuilder WithPeriod(
this ReferenceCollectionBuilder referenceCollectionBuilder,
bool withPeriod = true)
{
Check.NotNull(referenceCollectionBuilder, nameof(referenceCollectionBuilder));

referenceCollectionBuilder.Metadata.SetPeriod(withPeriod);

return referenceCollectionBuilder;
}

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="referenceCollectionBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <typeparam name="TEntity">The principal entity type in this relationship.</typeparam>
/// <typeparam name="TRelatedEntity">The dependent entity type in this relationship.</typeparam>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static ReferenceCollectionBuilder<TEntity, TRelatedEntity> WithPeriod<TEntity, TRelatedEntity>(
this ReferenceCollectionBuilder<TEntity, TRelatedEntity> referenceCollectionBuilder,
bool withPeriod = true)
where TEntity : class
where TRelatedEntity : class
=> (ReferenceCollectionBuilder<TEntity, TRelatedEntity>)WithPeriod(
(ReferenceCollectionBuilder)referenceCollectionBuilder, withPeriod);

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="referenceReferenceBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static ReferenceReferenceBuilder WithPeriod(
this ReferenceReferenceBuilder referenceReferenceBuilder,
bool withPeriod = true)
{
Check.NotNull(referenceReferenceBuilder, nameof(referenceReferenceBuilder));

referenceReferenceBuilder.Metadata.SetPeriod(withPeriod);

return referenceReferenceBuilder;
}

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="referenceReferenceBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <typeparam name="TEntity">The entity type on one end of the relationship.</typeparam>
/// <typeparam name="TRelatedEntity">The entity type on the other end of the relationship.</typeparam>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static ReferenceReferenceBuilder<TEntity, TRelatedEntity> WithPeriod<TEntity, TRelatedEntity>(
this ReferenceReferenceBuilder<TEntity, TRelatedEntity> referenceReferenceBuilder,
bool withPeriod = true)
where TEntity : class
where TRelatedEntity : class
=> (ReferenceReferenceBuilder<TEntity, TRelatedEntity>)WithPeriod(
(ReferenceReferenceBuilder)referenceReferenceBuilder, withPeriod);

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="ownershipBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static OwnershipBuilder WithPeriod(
this OwnershipBuilder ownershipBuilder,
bool withPeriod = true)
{
Check.NotNull(ownershipBuilder, nameof(ownershipBuilder));

ownershipBuilder.Metadata.SetPeriod(withPeriod);

return ownershipBuilder;
}

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="ownershipBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <typeparam name="TEntity">The entity type on one end of the relationship.</typeparam>
/// <typeparam name="TDependentEntity">The entity type on the other end of the relationship.</typeparam>
/// <returns>The same builder instance so that multiple calls can be chained.</returns>
public static OwnershipBuilder<TEntity, TDependentEntity> WithPeriod<TEntity, TDependentEntity>(
this OwnershipBuilder<TEntity, TDependentEntity> ownershipBuilder,
bool withPeriod = true)
where TEntity : class
where TDependentEntity : class
=> (OwnershipBuilder<TEntity, TDependentEntity>)WithPeriod(
(OwnershipBuilder)ownershipBuilder, withPeriod);

/// <summary>
/// Configures the foreign key to use the PostgreSQL PERIOD feature for temporal foreign keys.
/// The last column in the foreign key must be a PostgreSQL range type, and the referenced
/// principal key must have WITHOUT OVERLAPS configured.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="foreignKeyBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionForeignKeyBuilder? WithPeriod(
this IConventionForeignKeyBuilder foreignKeyBuilder,
bool? withPeriod = true,
bool fromDataAnnotation = false)
{
if (foreignKeyBuilder.CanSetPeriod(withPeriod, fromDataAnnotation))
{
foreignKeyBuilder.Metadata.SetPeriod(withPeriod, fromDataAnnotation);

return foreignKeyBuilder;
}

return null;
}

/// <summary>
/// Returns a value indicating whether PERIOD can be configured.
/// </summary>
/// <param name="foreignKeyBuilder">The builder being used to configure the relationship.</param>
/// <param name="withPeriod">A value indicating whether to use PERIOD.</param>
/// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param>
/// <returns><see langword="true" /> if the foreign key can be configured with PERIOD.</returns>
public static bool CanSetPeriod(
this IConventionForeignKeyBuilder foreignKeyBuilder,
bool? withPeriod = true,
bool fromDataAnnotation = false)
{
Check.NotNull(foreignKeyBuilder, nameof(foreignKeyBuilder));

return foreignKeyBuilder.CanSetAnnotation(NpgsqlAnnotationNames.Period, withPeriod, fromDataAnnotation);
}

#endregion Period
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore;

/// <summary>
/// Extension methods for <see cref="IForeignKey" /> for Npgsql-specific metadata.
/// </summary>
public static class NpgsqlForeignKeyExtensions
{
#region Period

/// <summary>
/// Returns a value indicating whether the foreign key uses the PostgreSQL PERIOD feature for temporal foreign keys.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="foreignKey">The foreign key.</param>
/// <returns><see langword="true" /> if the foreign key uses PERIOD.</returns>
public static bool? GetPeriod(this IReadOnlyForeignKey foreignKey)
=> (bool?)foreignKey[NpgsqlAnnotationNames.Period];

/// <summary>
/// Sets a value indicating whether the foreign key uses the PostgreSQL PERIOD feature for temporal foreign keys.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="foreignKey">The foreign key.</param>
/// <param name="period">The value to set.</param>
public static void SetPeriod(this IMutableForeignKey foreignKey, bool? period)
=> foreignKey.SetOrRemoveAnnotation(NpgsqlAnnotationNames.Period, period);

/// <summary>
/// Sets a value indicating whether the foreign key uses the PostgreSQL PERIOD feature for temporal foreign keys.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/sql-createtable.html for more information.
/// </remarks>
/// <param name="foreignKey">The foreign key.</param>
/// <param name="period">The value to set.</param>
/// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param>
/// <returns>The configured value.</returns>
public static bool? SetPeriod(this IConventionForeignKey foreignKey, bool? period, bool fromDataAnnotation = false)
{
foreignKey.SetOrRemoveAnnotation(NpgsqlAnnotationNames.Period, period, fromDataAnnotation);

return period;
}

/// <summary>
/// Returns the <see cref="ConfigurationSource" /> for whether the foreign key uses PERIOD.
/// </summary>
/// <param name="foreignKey">The foreign key.</param>
/// <returns>The <see cref="ConfigurationSource" />.</returns>
public static ConfigurationSource? GetPeriodConfigurationSource(this IConventionForeignKey foreignKey)
=> foreignKey.FindAnnotation(NpgsqlAnnotationNames.Period)?.GetConfigurationSource();

#endregion Period
}
66 changes: 64 additions & 2 deletions src/EFCore.PG/Infrastructure/Internal/NpgsqlModelValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public override void Validate(IModel model, IDiagnosticsLogger<DbLoggerCategory.
ValidateIdentityVersionCompatibility(model);
ValidateIndexIncludeProperties(model);
ValidateWithoutOverlaps(model);
ValidatePeriod(model);
}

/// <summary>
Expand Down Expand Up @@ -294,7 +295,7 @@ protected virtual void ValidateWithoutOverlaps(IModel model)

private void ValidateWithoutOverlapsKey(IKey key)
{
var keyName = key.IsPrimaryKey() ? "primary key" : $"alternate key {{{string.Join(", ", key.Properties.Select(p => p.Name))}}}";
var keyName = key.IsPrimaryKey() ? "primary key" : $"alternate key {key.Properties.Format()}";
var entityType = key.DeclaringEntityType;

// Check PostgreSQL version requirement
Expand All @@ -305,7 +306,7 @@ private void ValidateWithoutOverlapsKey(IKey key)
}

// Check that the last property is a range type
var lastProperty = key.Properties.Last();
var lastProperty = key.Properties[^1];
var typeMapping = lastProperty.FindTypeMapping();

if (typeMapping is not NpgsqlRangeTypeMapping)
Expand All @@ -318,4 +319,65 @@ private void ValidateWithoutOverlapsKey(IKey key)
lastProperty.ClrType.ShortDisplayName()));
}
}

/// <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>
protected virtual void ValidatePeriod(IModel model)
{
foreach (var entityType in model.GetEntityTypes())
{
foreach (var foreignKey in entityType.GetDeclaredForeignKeys())
{
if (foreignKey.GetPeriod() == true)
{
ValidatePeriodForeignKey(foreignKey);
}
}
}
}

private void ValidatePeriodForeignKey(IForeignKey foreignKey)
{
var entityType = foreignKey.DeclaringEntityType;
var fkName = foreignKey.Properties.Format();
var principalKey = foreignKey.PrincipalKey;
var principalEntityType = principalKey.DeclaringEntityType;

if (!_postgresVersion.AtLeast(18))
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresPostgres18(fkName, entityType.DisplayName()));
}

// Check that the principal key has WITHOUT OVERLAPS (check this before range type)
if (principalKey.GetWithoutOverlaps() != true)
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresWithoutOverlapsOnPrincipal(
fkName,
entityType.DisplayName(),
principalKey.IsPrimaryKey()
? "primary key"
: $"alternate key {principalKey.Properties.Format()}",
principalEntityType.DisplayName()));
}

// Check that the last property is a range type
var lastProperty = foreignKey.Properties[^1];
var typeMapping = lastProperty.FindTypeMapping();

if (typeMapping is not NpgsqlRangeTypeMapping)
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresRangeType(
fkName,
entityType.DisplayName(),
lastProperty.Name,
lastProperty.ClrType.ShortDisplayName()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ public override ConventionSet CreateConventionSet()

ReplaceConvention(conventionSet.ForeignKeyRemovedConventions, valueGenerationConvention);

conventionSet.ForeignKeyAnnotationChangedConventions.Add(
new NpgsqlPeriodConvention(Dependencies, RelationalDependencies));

var storeGenerationConvention =
new NpgsqlStoreGenerationConvention(Dependencies, RelationalDependencies);
ReplaceConvention(conventionSet.PropertyAnnotationChangedConventions, storeGenerationConvention);
Expand Down
39 changes: 39 additions & 0 deletions src/EFCore.PG/Metadata/Conventions/NpgsqlPeriodConvention.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;

namespace Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Conventions;

/// <summary>
/// A convention that sets the delete behavior to <see cref="DeleteBehavior.NoAction" /> for foreign keys with PERIOD,
/// since PostgreSQL does not support cascading deletes for temporal foreign keys.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this convention.</param>
/// <param name="relationalDependencies">Parameter object containing relational dependencies for this convention.</param>
public class NpgsqlPeriodConvention(
ProviderConventionSetBuilderDependencies dependencies,
RelationalConventionSetBuilderDependencies relationalDependencies)
: IForeignKeyAnnotationChangedConvention
{
/// <summary>
/// Dependencies for this service.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; } = dependencies;

/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalConventionSetBuilderDependencies RelationalDependencies { get; } = relationalDependencies;

/// <inheritdoc />
public virtual void ProcessForeignKeyAnnotationChanged(
IConventionForeignKeyBuilder relationshipBuilder,
string name,
IConventionAnnotation? annotation,
IConventionAnnotation? oldAnnotation,
IConventionContext<IConventionAnnotation> context)
{
if (name == NpgsqlAnnotationNames.Period && annotation?.Value is true)
{
relationshipBuilder.OnDelete(DeleteBehavior.NoAction);
}
}
}
Loading
Loading