|
| 1 | +namespace TestHelper; |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Globalization; |
| 6 | +using System.Linq; |
| 7 | +using System.Runtime.CompilerServices; |
| 8 | +using System.Text; |
| 9 | +using Microsoft.EntityFrameworkCore; |
| 10 | +using Microsoft.EntityFrameworkCore.Infrastructure; |
| 11 | +using Microsoft.EntityFrameworkCore.Migrations; |
| 12 | +using Microsoft.EntityFrameworkCore.Migrations.Operations; |
| 13 | +using Particular.Approvals; |
| 14 | + |
| 15 | +public static class SlowMigrationOperations |
| 16 | +{ |
| 17 | + const string ChangedMessage = |
| 18 | + "The migration steps that can block writes on a large table do not match the approved file. Index, key, foreign key, check constraint, column and raw SQL changes can block writes for a long time during an upgrade. " + |
| 19 | + "If the diff shows a changed step, record it in the upgrade guide of the next release. If the step is in an existing migration, add a new migration instead. " + |
| 20 | + "Then approve the new list. See docs/testing.md."; |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Compares the slow steps in the migrations of <paramref name="context"/> with the approved file for the calling test. |
| 24 | + /// The slow steps are index, primary key and unique constraint changes, new foreign keys and check constraints, altered columns, raw SQL, |
| 25 | + /// and new columns that are NOT NULL with a default or are stored computed columns. |
| 26 | + /// Other steps, such as renames and drops of columns, tables and constraints, are not listed. |
| 27 | + /// Steps on a table that the same migration creates are left out, because that table starts empty. Raw SQL is always listed. |
| 28 | + /// When the list differs, it throws an exception that says what to check before approving the new list, with the approval failure as the inner exception. |
| 29 | + /// </summary> |
| 30 | + public static void Verify(DbContext context, [CallerFilePath] string callerFilePath = null, [CallerMemberName] string callerMemberName = null) |
| 31 | + { |
| 32 | + var steps = Describe(context); |
| 33 | + |
| 34 | + try |
| 35 | + { |
| 36 | + Approver.Verify(steps, callerFilePath: callerFilePath, callerMemberName: callerMemberName); |
| 37 | + } |
| 38 | + catch (Exception e) |
| 39 | + { |
| 40 | + throw new Exception(ChangedMessage, e); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + static string Describe(DbContext context) |
| 45 | + { |
| 46 | + var migrationsAssembly = context.GetService<IMigrationsAssembly>(); |
| 47 | + var text = new StringBuilder(); |
| 48 | + |
| 49 | + foreach (var (id, type) in migrationsAssembly.Migrations.OrderBy(migration => migration.Key, StringComparer.Ordinal)) |
| 50 | + { |
| 51 | + var operations = migrationsAssembly.CreateMigration(type, context.Database.ProviderName).UpOperations; |
| 52 | + var newTables = operations.OfType<CreateTableOperation>().Select(table => table.Name).ToHashSet(StringComparer.Ordinal); |
| 53 | + var steps = operations.Select(operation => Describe(operation, newTables)).OfType<string>().ToList(); |
| 54 | + |
| 55 | + if (steps.Count == 0) |
| 56 | + { |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + text.AppendLine(id); |
| 61 | + foreach (var step in steps) |
| 62 | + { |
| 63 | + text.AppendLine(Indent(step)); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return text.ToString(); |
| 68 | + } |
| 69 | + |
| 70 | + static string Describe(MigrationOperation operation, HashSet<string> newTables) => operation switch |
| 71 | + { |
| 72 | + SqlOperation sql => $"Sql{Environment.NewLine}{Indent(sql.Sql)}", |
| 73 | + ITableMigrationOperation table when newTables.Contains(table.Table) => null, |
| 74 | + CreateIndexOperation index => $"CreateIndex {index.Name} on {index.Table} ({IndexColumns(index)}){(index.IsUnique ? " unique" : "")}{(index.Filter is null ? "" : $" where {index.Filter}")}{Annotations(index)}", |
| 75 | + DropIndexOperation index => $"DropIndex {index.Name} on {index.Table}", |
| 76 | + AddPrimaryKeyOperation key => $"AddPrimaryKey {key.Name} on {key.Table} ({string.Join(", ", key.Columns)}){Annotations(key)}", |
| 77 | + DropPrimaryKeyOperation key => $"DropPrimaryKey {key.Name} on {key.Table}", |
| 78 | + AddUniqueConstraintOperation constraint => $"AddUniqueConstraint {constraint.Name} on {constraint.Table} ({string.Join(", ", constraint.Columns)}){Annotations(constraint)}", |
| 79 | + DropUniqueConstraintOperation constraint => $"DropUniqueConstraint {constraint.Name} on {constraint.Table}", |
| 80 | + AddCheckConstraintOperation constraint => $"AddCheckConstraint {constraint.Name} on {constraint.Table} ({constraint.Sql})", |
| 81 | + AddForeignKeyOperation key => $"AddForeignKey {key.Name} on {key.Table} ({string.Join(", ", key.Columns)}) references {key.PrincipalTable} ({string.Join(", ", key.PrincipalColumns ?? [])})", |
| 82 | + AlterColumnOperation column => $"AlterColumn {column.Table}.{column.Name} {ColumnType(column.OldColumn)} -> {ColumnType(column)}", |
| 83 | + AddColumnOperation column when CanRewriteEveryRow(column) => $"AddColumn {column.Table}.{column.Name} {ColumnType(column)}{ColumnValue(column)}", |
| 84 | + _ => null |
| 85 | + }; |
| 86 | + |
| 87 | + static bool CanRewriteEveryRow(AddColumnOperation column) => |
| 88 | + (!column.IsNullable && (column.DefaultValue is not null || column.DefaultValueSql is not null)) || (column.ComputedColumnSql is not null && column.IsStored == true); |
| 89 | + |
| 90 | + static string ColumnValue(ColumnOperation column) => |
| 91 | + column.ComputedColumnSql is not null ? $" computed {column.ComputedColumnSql}" |
| 92 | + : column.DefaultValueSql is not null ? $" default {column.DefaultValueSql}" |
| 93 | + : $" default {Convert.ToString(column.DefaultValue, CultureInfo.InvariantCulture)}"; |
| 94 | + |
| 95 | + // An empty IsDescending array means every column is descending. |
| 96 | + static string IndexColumns(CreateIndexOperation index) => string.Join(", ", index.Columns.Select((column, i) => |
| 97 | + index.IsDescending is { } descending && (descending.Length == 0 || descending[i]) ? $"{column} desc" : column)); |
| 98 | + |
| 99 | + static string ColumnType(ColumnOperation column) => $"{column.ColumnType ?? column.ClrType.Name} {(column.IsNullable ? "null" : "not null")}"; |
| 100 | + |
| 101 | + static string Annotations(MigrationOperation operation) => string.Concat(operation.GetAnnotations().Select(annotation => |
| 102 | + $" {annotation.Name}={(annotation.Value is IEnumerable<string> values ? $"[{string.Join(", ", values)}]" : annotation.Value)}")); |
| 103 | + |
| 104 | + static string Indent(string text) => string.Join(Environment.NewLine, text.Split('\n').Select(line => line.TrimEnd('\r')).Select(line => line.Length == 0 ? line : " " + line)); |
| 105 | +} |
0 commit comments