-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Migrations: Re-trust untrusted foreign key and check constraints on SQL Server and fix bulk inserts to prevent recurrence #21744
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b6e04c8
Be explicit about creating foreign key constrains with check (already…
AndyButland 169dc7e
Add a migration to attempt to ensure that all constrains a trusted.
AndyButland 8ad7809
Updated name of migration class.
AndyButland e33b141
Ensure long timeout for migration.
AndyButland 09c14e5
Update BulkInsertRecordsSqlServer to use SqlBulkCopyOptions.CheckCons…
AndyButland 4bf1d05
Ensure NPoco InsertBulk uses SqlBulkCopyOptions.CheckConstraints by i…
AndyButland f52cff3
Also handle InsertBulkAsync.
AndyButland File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
src/Umbraco.Cms.Persistence.SqlServer/Services/UmbracoSqlServerDatabaseType.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| using Microsoft.Data.SqlClient; | ||
| using NPoco; | ||
| using NPoco.DatabaseTypes; | ||
| using NPoco.SqlServer; | ||
|
|
||
| namespace Umbraco.Cms.Persistence.SqlServer.Services; | ||
|
|
||
| /// <summary> | ||
| /// Custom SQL Server database type that ensures FK constraints remain trusted | ||
| /// during bulk insert operations by using <see cref="SqlBulkCopyOptions.CheckConstraints"/>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// NPoco's default <see cref="SqlServerDatabaseType.InsertBulk{T}"/> and <see cref="SqlServerDatabaseType.InsertBulkAsync{T}"/> uses | ||
| /// <see cref="SqlBulkCopyOptions.Default"/> which bypasses FK validation during <see cref="SqlBulkCopy"/> operations, causing | ||
| /// SQL Server to mark constraints as untrusted (<c>is_not_trusted = 1</c>). | ||
| /// Untrusted constraints prevent the query optimizer from using them for join elimination and cardinality estimation. | ||
| /// </remarks> | ||
| internal sealed class UmbracoSqlServerDatabaseType : SqlServer2012DatabaseType | ||
| { | ||
| /// <inheritdoc /> | ||
| public override void InsertBulk<T>(IDatabase db, IEnumerable<T> pocos, InsertBulkOptions? options) | ||
| => SqlBulkCopyHelper.BulkInsert(db, pocos, SqlBulkCopyOptions.CheckConstraints, options); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override Task InsertBulkAsync<T>(IDatabase db, IEnumerable<T> pocos, InsertBulkOptions? options, CancellationToken cancellationToken = default) | ||
| => SqlBulkCopyHelper.BulkInsertAsync(db, pocos, SqlBulkCopyOptions.CheckConstraints, options ?? new InsertBulkOptions(), cancellationToken); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
...mbraco.Infrastructure/Migrations/Upgrade/V_17_3_0/RetrustForeignKeyAndCheckConstraints.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using NPoco; | ||
| using Umbraco.Cms.Core; | ||
|
|
||
| namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_17_3_0; | ||
|
|
||
| /// <summary> | ||
| /// Re-trusts all untrusted foreign key and check constraints on SQL Server. | ||
| /// Untrusted constraints (where <c>is_not_trusted = 1</c>) prevent the query optimizer from using them | ||
| /// for join elimination, cardinality estimation, and index selection. They can result from historical | ||
| /// upgrades, EF Core migrations, or DBA operations such as backup restores. | ||
| /// </summary> | ||
| public class RetrustForeignKeyAndCheckConstraints : AsyncMigrationBase | ||
| { | ||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="RetrustForeignKeyAndCheckConstraints"/> class. | ||
| /// </summary> | ||
| /// <param name="context">The migration context.</param> | ||
| public RetrustForeignKeyAndCheckConstraints(IMigrationContext context) | ||
| : base(context) | ||
| { | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| protected override Task MigrateAsync() | ||
| { | ||
| if (DatabaseType == DatabaseType.SQLite) | ||
| { | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| RetrustConstraints(); | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private void RetrustConstraints() | ||
| { | ||
| List<UntrustedConstraintDto> untrustedConstraints = Database.Fetch<UntrustedConstraintDto>( | ||
| @"SELECT | ||
| s.name AS SchemaName, | ||
| OBJECT_NAME(fk.parent_object_id) AS TableName, | ||
| fk.name AS ConstraintName | ||
| FROM sys.foreign_keys fk | ||
| INNER JOIN sys.schemas s ON fk.schema_id = s.schema_id | ||
| WHERE fk.is_not_trusted = 1 | ||
|
|
||
| UNION ALL | ||
|
|
||
| SELECT | ||
| s.name AS SchemaName, | ||
| OBJECT_NAME(cc.parent_object_id) AS TableName, | ||
| cc.name AS ConstraintName | ||
| FROM sys.check_constraints cc | ||
| INNER JOIN sys.schemas s ON cc.schema_id = s.schema_id | ||
| WHERE cc.is_not_trusted = 1"); | ||
|
|
||
| if (untrustedConstraints.Count == 0) | ||
| { | ||
| Logger.LogInformation("No untrusted constraints found."); | ||
| return; | ||
| } | ||
|
|
||
| Logger.LogInformation("Found {Count} untrusted constraint(s) to re-trust.", untrustedConstraints.Count); | ||
|
|
||
| // Ensure we have a long command timeout, in case the migration targets a huge table. | ||
| EnsureLongCommandTimeout(Database); | ||
|
|
||
| var retrusted = 0; | ||
| var failed = 0; | ||
|
|
||
| foreach (UntrustedConstraintDto constraint in untrustedConstraints) | ||
| { | ||
| var sql = $"ALTER TABLE [{constraint.SchemaName}].[{constraint.TableName}] WITH CHECK CHECK CONSTRAINT [{constraint.ConstraintName}]"; | ||
|
|
||
AndyButland marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| try | ||
| { | ||
| Database.Execute(sql); | ||
| retrusted++; | ||
| Logger.LogDebug( | ||
| "Re-trusted constraint [{ConstraintName}] on [{SchemaName}].[{TableName}].", | ||
| constraint.ConstraintName, | ||
| constraint.SchemaName, | ||
| constraint.TableName); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| failed++; | ||
| Logger.LogWarning( | ||
| ex, | ||
| "Could not re-trust constraint [{ConstraintName}] on [{SchemaName}].[{TableName}]. " + | ||
| "This likely means existing data violates the constraint. " + | ||
| "Please investigate and fix the data integrity issue manually.", | ||
| constraint.ConstraintName, | ||
| constraint.SchemaName, | ||
| constraint.TableName); | ||
| } | ||
| } | ||
|
|
||
| Logger.LogInformation( | ||
| "Constraint re-trust complete: {Retrusted} succeeded, {Failed} failed out of {Total} total.", | ||
| retrusted, | ||
kjac marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
kjac marked this conversation as resolved.
Dismissed
Show dismissed
Hide dismissed
|
||
| failed, | ||
| untrustedConstraints.Count); | ||
| } | ||
|
|
||
| [TableName("")] | ||
| private class UntrustedConstraintDto | ||
| { | ||
| [Column("SchemaName")] | ||
| public string SchemaName { get; set; } = null!; | ||
|
|
||
| [Column("TableName")] | ||
| public string TableName { get; set; } = null!; | ||
|
|
||
| [Column("ConstraintName")] | ||
| public string ConstraintName { get; set; } = null!; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.