| | | 1 | | namespace ZhEaIsNsAaBn.DbSeeder.Design; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// The operate commands on the dev database, from the migrations folder on disk: <c>list</c>, <c>update</c>, <c>down</c |
| | | 5 | | /// blockers offer, forced delete) and <c>script</c>. Exit code 0 = done, 1 = error, refused or cancelled. |
| | | 6 | | /// </summary> |
| | | 7 | | internal sealed class SeedOperator |
| | | 8 | | { |
| | | 9 | | private const string Production = nameof( Production ); |
| | | 10 | | |
| | | 11 | | private readonly DesignSession _session; |
| | | 12 | | private readonly SeedDesigner _designer; |
| | | 13 | | private readonly SeedConfiguration _configuration; |
| | | 14 | | private readonly IAnsiConsole _console; |
| | | 15 | | |
| | | 16 | | |
| | 168 | 17 | | private SeedOperator( DesignSession session, SeedDesigner designer, SeedConfiguration configuration ) |
| | | 18 | | { |
| | 168 | 19 | | _session = session; |
| | 168 | 20 | | _designer = designer; |
| | 168 | 21 | | _configuration = configuration; |
| | 168 | 22 | | _console = session.Console; |
| | 168 | 23 | | } |
| | | 24 | | |
| | | 25 | | |
| | | 26 | | /// The operator for the settings' folder; <see langword="null"/> (error printed) when the folder can't be chosen. |
| | | 27 | | public static SeedOperator? For( DesignSession session, FolderSettings settings ) |
| | | 28 | | { |
| | 168 | 29 | | var designer = session.Designer( settings ); |
| | 168 | 30 | | var configuration = designer.FolderConfiguration( settings.Folder ); |
| | | 31 | | |
| | 336 | 32 | | if ( configuration.IsSuccess ) { return new SeedOperator( session, designer, configuration.Result! ); } |
| | | 33 | | |
| | | 34 | | |
| | 0 | 35 | | session.Report( DesignResult.Failed( configuration.Errors[ 0 ].Message ) ); |
| | | 36 | | |
| | 0 | 37 | | return null; |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | |
| | | 41 | | // ---- list / update / script ---- |
| | | 42 | | |
| | | 43 | | public async Task<int> ListAsync( CancellationToken cancellationToken ) |
| | | 44 | | { |
| | 9 | 45 | | var list = await SeedEngine.ListAsync( _session.DbContext, _configuration, _session.Provider, async: true, cance |
| | | 46 | | |
| | 9 | 47 | | if ( list.IsFailure ) { return Errors( list.Errors ); } |
| | | 48 | | |
| | | 49 | | |
| | 9 | 50 | | var inCode = _configuration.Migrations.Result!.Select( m => m.Id ).ToHashSet( StringComparer.Ordinal ); |
| | 9 | 51 | | var newest = list.Result!.Where( m => m.IsApplied ).Select( m => m.Id ).Max( StringComparer.Ordinal ); |
| | 9 | 52 | | var table = new Table().AddColumns( "Migration", "Status", "Applied on", "Checksum", "Note" ); |
| | | 53 | | |
| | 42 | 54 | | foreach ( var migration in list.Result! ) |
| | | 55 | | { |
| | 12 | 56 | | var checksum = !migration.IsApplied ? "" : !inCode.Contains( migration.Id ) ? "not in code" : migration.Chec |
| | 12 | 57 | | var note = !migration.IsApplied && newest is not null && string.CompareOrdinal( migration.Id, newest ) < |
| | | 58 | | |
| | 12 | 59 | | table.AddRow( Markup.Escape( migration.Id ), migration.IsApplied ? "applied" : "pending", |
| | 12 | 60 | | migration.AppliedOn?.ToString( "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture ) ?? "", ch |
| | | 61 | | } |
| | | 62 | | |
| | 9 | 63 | | if ( list.Result!.Count == 0 ) { _console.WriteLine( "No seed migrations." ); } |
| | 9 | 64 | | else { _console.Write( table ); } |
| | | 65 | | |
| | | 66 | | |
| | 9 | 67 | | return 0; |
| | 9 | 68 | | } |
| | | 69 | | |
| | | 70 | | public async Task<int> UpdateAsync( string? to, CancellationToken cancellationToken ) |
| | | 71 | | { |
| | 102 | 72 | | var result = await SeedEngine.UpAsync( _session.DbContext, _configuration, _session.Provider, to, takeLock: true |
| | | 73 | | |
| | 102 | 74 | | if ( result.IsFailure ) { return Errors( result.Errors ); } |
| | | 75 | | |
| | | 76 | | |
| | 102 | 77 | | _console.WriteLine( result.Result!.Ids.Count == 0 ? "Nothing pending." : $"Applied: {string.Join( ", ", result.R |
| | 102 | 78 | | Warnings( result.Result.Warnings ); |
| | | 79 | | |
| | 102 | 80 | | return 0; |
| | 102 | 81 | | } |
| | | 82 | | |
| | | 83 | | public int Script( string? from, string? to, string output ) |
| | | 84 | | { |
| | 3 | 85 | | var migrations = SeedScriptBuilder.Build( _session.DbContext.Model, _configuration, from, to ); |
| | | 86 | | |
| | 3 | 87 | | if ( migrations.IsFailure ) { return Errors( migrations.Errors ); } |
| | | 88 | | |
| | | 89 | | |
| | 3 | 90 | | var path = Path.Combine( _designer.Root, output ); |
| | | 91 | | |
| | 3 | 92 | | Directory.CreateDirectory( Path.GetDirectoryName( path )! ); |
| | 3 | 93 | | File.WriteAllText( path, _session.Provider.Script( migrations.Result! ), new UTF8Encoding( false ) ); |
| | | 94 | | |
| | 3 | 95 | | _console.WriteLine( $"Script of {migrations.Result!.Count} seed migration(s) written to {output}." ); |
| | | 96 | | |
| | 3 | 97 | | return 0; |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | |
| | | 101 | | // ---- down ---- |
| | | 102 | | |
| | | 103 | | public async Task<int> DownAsync( DownSettings settings, CancellationToken cancellationToken ) |
| | | 104 | | { |
| | 54 | 105 | | if ( Invalid( settings ) is { } problem ) { return Errors( [ problem ] ); } |
| | | 106 | | |
| | | 107 | | |
| | 54 | 108 | | var mode = settings.Soft ? SeedDeleteMode.Soft : settings.Hard ? SeedDeleteMode.Hard : (SeedDeleteMode?) null; |
| | 54 | 109 | | var plan = await PlanAsync( settings, mode, force: settings.Force, cancellationToken ).ConfigureAwait( false ); |
| | | 110 | | |
| | 54 | 111 | | if ( plan is null ) { return 1; } |
| | | 112 | | |
| | 54 | 113 | | if ( plan.Migrations.Count == 0 ) |
| | | 114 | | { |
| | 0 | 115 | | _console.WriteLine( "Nothing to roll back." ); |
| | | 116 | | |
| | 0 | 117 | | return 0; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | |
| | 84 | 121 | | if ( settings.Force ) { return await ForceAsync( settings, mode, plan, cancellationToken ).ConfigureAwait( false |
| | | 122 | | |
| | 39 | 123 | | if ( plan.CanRollBack ) { return await ConfirmAndRollBackAsync( settings, mode, settings.Yes, cancellationToken |
| | | 124 | | |
| | | 125 | | |
| | | 126 | | // Blocked: offer a soft delete, cancel, or a forced dry run (executing needs --force --execute). |
| | 12 | 127 | | if ( !_console.Profile.Capabilities.Interactive ) { return Errors( [ "Seed rows are still referenced. Run intera |
| | | 128 | | |
| | 6 | 129 | | var choice = _console.Prompt( new TextPrompt<string>( "Rows are still referenced. Choose:" ).AddChoices( [ "soft |
| | | 130 | | |
| | | 131 | | switch ( choice ) |
| | | 132 | | { |
| | | 133 | | case "soft": |
| | 3 | 134 | | var soft = await PlanAsync( settings, SeedDeleteMode.Soft, force: false, cancellationToken ).ConfigureAw |
| | | 135 | | |
| | 3 | 136 | | if ( soft is null ) { return 1; } |
| | | 137 | | |
| | 3 | 138 | | return soft.CanRollBack |
| | 3 | 139 | | ? await ConfirmAndRollBackAsync( settings, SeedDeleteMode.Soft, skipConfirm: false, cancellat |
| | 3 | 140 | | : Errors( [ "Still blocked with soft deletes." ] ); |
| | | 141 | | |
| | | 142 | | case "force": |
| | 0 | 143 | | var forced = await PlanAsync( settings, mode, force: true, cancellationToken ).ConfigureAwait( false ); |
| | | 144 | | |
| | 0 | 145 | | if ( forced is null ) { return 1; } |
| | | 146 | | |
| | 0 | 147 | | ForcePanel( forced ); |
| | 0 | 148 | | _console.WriteLine( "Dry run: nothing changed. Run again with --force --execute to delete." ); |
| | | 149 | | |
| | 0 | 150 | | return 0; |
| | | 151 | | |
| | | 152 | | default: |
| | 3 | 153 | | _console.WriteLine( "Cancelled: nothing changed." ); |
| | | 154 | | |
| | 3 | 155 | | return 1; |
| | | 156 | | } |
| | 54 | 157 | | } |
| | | 158 | | |
| | | 159 | | private async Task<int> ForceAsync( DownSettings settings, SeedDeleteMode? mode, SeedRollbackPlan plan, Cancellation |
| | | 160 | | { |
| | 30 | 161 | | if ( plan.ForceRefusal is not null ) { return Errors( [ $"A forced delete is refused: {plan.ForceRefusal}" ] ); |
| | | 162 | | |
| | 30 | 163 | | ForcePanel( plan ); |
| | | 164 | | |
| | 30 | 165 | | if ( !settings.Execute ) |
| | | 166 | | { |
| | 3 | 167 | | _console.WriteLine( "Dry run: nothing changed. Add --execute to delete." ); |
| | | 168 | | |
| | 3 | 169 | | return 0; |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | |
| | | 173 | | // The guards: never in Production, never in a protected database, only a person typing the database name. |
| | 27 | 174 | | var database = _session.DbContext.Database.GetDbConnection().Database; |
| | | 175 | | |
| | 36 | 176 | | if ( ProductionRefusal() is { } refusal ) { return Errors( [ refusal ] ); } |
| | | 177 | | |
| | 21 | 178 | | if ( _configuration.Options.ProtectedDatabases.Contains( database ) ) { return Errors( [ $"Refused: {database} i |
| | | 179 | | |
| | 21 | 180 | | if ( !_console.Profile.Capabilities.Interactive ) { return Errors( [ "Refused: a forced delete needs an interact |
| | | 181 | | |
| | | 182 | | |
| | 9 | 183 | | var typed = _console.Prompt( new TextPrompt<string>( $"Type the database name ([red]{Markup.Escape( database )}[ |
| | | 184 | | |
| | 12 | 185 | | if ( !string.Equals( typed, database, StringComparison.Ordinal ) ) { return Errors( [ "Refused: the typed name d |
| | | 186 | | |
| | | 187 | | |
| | 6 | 188 | | var result = await SeedRollback.DownAsync( _session.DbContext, _configuration, _session.Provider, Steps( setting |
| | 6 | 189 | | .ConfigureAwait( false ); |
| | | 190 | | |
| | 6 | 191 | | return result.IsFailure ? Errors( result.Errors ) : RolledBack( result.Result! ); |
| | 30 | 192 | | } |
| | | 193 | | |
| | | 194 | | /// Production anywhere refuses: either variable, or the host's IHostEnvironment. None of them set counts as Product |
| | | 195 | | /// with no environment (dotnet dbseeder sets Development when neither variable is set, so this only bites in-app ru |
| | | 196 | | private string? ProductionRefusal() |
| | | 197 | | { |
| | 27 | 198 | | var any = false; |
| | | 199 | | |
| | 159 | 200 | | foreach ( var variable in new[] { "DOTNET_ENVIRONMENT", "ASPNETCORE_ENVIRONMENT" } ) |
| | | 201 | | { |
| | 54 | 202 | | var value = Environment.GetEnvironmentVariable( variable ); |
| | | 203 | | |
| | 54 | 204 | | if ( string.IsNullOrEmpty( value ) ) { continue; } |
| | | 205 | | |
| | 30 | 206 | | if ( string.Equals( value, Production, StringComparison.OrdinalIgnoreCase ) ) { return $"Refused: {variable} |
| | | 207 | | |
| | 24 | 208 | | any = true; |
| | | 209 | | } |
| | | 210 | | |
| | 24 | 211 | | if ( _session.HostEnvironmentName() is { Length: > 0 } host ) |
| | | 212 | | { |
| | 6 | 213 | | if ( string.Equals( host, Production, StringComparison.OrdinalIgnoreCase ) ) { return "Refused: the host's e |
| | | 214 | | |
| | 0 | 215 | | any = true; |
| | | 216 | | } |
| | | 217 | | |
| | 21 | 218 | | return any ? null : "Refused: no environment is set (DOTNET_ENVIRONMENT, ASPNETCORE_ENVIRONMENT), so it counts a |
| | | 219 | | } |
| | | 220 | | |
| | | 221 | | private async Task<int> ConfirmAndRollBackAsync( DownSettings settings, SeedDeleteMode? mode, bool skipConfirm, Canc |
| | | 222 | | { |
| | 18 | 223 | | if ( !skipConfirm ) |
| | | 224 | | { |
| | 21 | 225 | | if ( !_console.Profile.Capabilities.Interactive ) { return Errors( [ "Confirm with --yes when the console is |
| | | 226 | | |
| | 9 | 227 | | if ( !_console.Confirm( "Roll back?", defaultValue: false ) ) |
| | | 228 | | { |
| | 3 | 229 | | _console.WriteLine( "Cancelled: nothing changed." ); |
| | | 230 | | |
| | 3 | 231 | | return 1; |
| | | 232 | | } |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | |
| | 9 | 236 | | var result = await SeedRollback.DownAsync( _session.DbContext, _configuration, _session.Provider, Steps( setting |
| | 9 | 237 | | .ConfigureAwait( false ); |
| | | 238 | | |
| | 9 | 239 | | return result.IsFailure ? Errors( result.Errors ) : RolledBack( result.Result! ); |
| | 18 | 240 | | } |
| | | 241 | | |
| | | 242 | | /// The plan (a dry run), printed: steps, then blockers. |
| | | 243 | | private async Task<SeedRollbackPlan?> PlanAsync( DownSettings settings, SeedDeleteMode? mode, bool force, Cancellati |
| | | 244 | | { |
| | 57 | 245 | | var plan = await SeedRollback.PlanAsync( _session.DbContext, _configuration, _session.Provider, Steps( settings |
| | 57 | 246 | | .ConfigureAwait( false ); |
| | | 247 | | |
| | 57 | 248 | | if ( plan.IsFailure ) |
| | | 249 | | { |
| | 0 | 250 | | Errors( plan.Errors ); |
| | | 251 | | |
| | 0 | 252 | | return null; |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | |
| | 57 | 256 | | var result = plan.Result!; |
| | | 257 | | |
| | 57 | 258 | | if ( result.Migrations.Count > 0 ) |
| | | 259 | | { |
| | 57 | 260 | | _console.WriteLine( $"Roll back: {string.Join( ", ", result.Migrations )}" ); |
| | | 261 | | |
| | 57 | 262 | | var steps = new Table().AddColumns( "Migration", "Table", "Operation", "Rows" ); |
| | | 263 | | |
| | 285 | 264 | | foreach ( var step in result.Steps ) { steps.AddRow( Markup.Escape( step.MigrationId ), Markup.Escape( step. |
| | | 265 | | |
| | 57 | 266 | | _console.Write( steps ); |
| | | 267 | | } |
| | | 268 | | |
| | 57 | 269 | | if ( result.Blockers.Count > 0 ) |
| | | 270 | | { |
| | 39 | 271 | | var blockers = new Table().AddColumns( "Referencing table", "Column", "Rows" ).BorderColor( Color.Yellow ); |
| | | 272 | | |
| | 195 | 273 | | foreach ( var blocker in result.Blockers ) { blockers.AddRow( Markup.Escape( blocker.Table ), Markup.Escape( |
| | | 274 | | |
| | 39 | 275 | | _console.MarkupLine( "[yellow]Blocked:[/] these rows still reference seed rows a real delete would remove." |
| | 39 | 276 | | _console.Write( blockers ); |
| | | 277 | | } |
| | | 278 | | |
| | 57 | 279 | | Warnings( result.Warnings ); |
| | | 280 | | |
| | 57 | 281 | | return result; |
| | 57 | 282 | | } |
| | | 283 | | |
| | | 284 | | /// The red dry-run panel: the full recursive tree, in delete order (deepest first), then the seed rows themselves. |
| | | 285 | | private void ForcePanel( SeedRollbackPlan plan ) |
| | | 286 | | { |
| | 30 | 287 | | var tree = new Table().AddColumns( "Order", "Depth", "Table", "Column(s)", "References", "Rows" ); |
| | 30 | 288 | | var i = 0; |
| | | 289 | | |
| | 180 | 290 | | foreach ( var node in plan.ForceTree ) |
| | | 291 | | { |
| | 60 | 292 | | tree.AddRow( ( ++i ).ToString( CultureInfo.InvariantCulture ), node.Depth.ToString( CultureInfo.InvariantCul |
| | 60 | 293 | | Markup.Escape( node.ReferencedTable ), node.Rows.ToString( CultureInfo.InvariantCulture ) ); |
| | | 294 | | } |
| | | 295 | | |
| | 30 | 296 | | _console.Write( new Panel( tree ) { Header = new PanelHeader( "[red bold]FORCED DELETE — every row below is dele |
| | 30 | 297 | | } |
| | | 298 | | |
| | | 299 | | private int RolledBack( SeedRunResult result ) |
| | | 300 | | { |
| | 12 | 301 | | _console.WriteLine( $"Rolled back: {string.Join( ", ", result.Ids )}" ); |
| | 12 | 302 | | Warnings( result.Warnings ); |
| | | 303 | | |
| | 12 | 304 | | return 0; |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | private static string? Invalid( DownSettings settings ) |
| | 54 | 308 | | => settings switch |
| | 54 | 309 | | { |
| | 0 | 310 | | { Soft: true, Hard: true } => "Choose --soft or --hard, not both.", |
| | 0 | 311 | | { Execute: true, Force: false } => "--execute needs --force.", |
| | 0 | 312 | | { Force: true, Soft: true } => "--force deletes for real; it can't be combined with --so |
| | 0 | 313 | | { Steps: not null, To: not null } => "Choose --steps or --to, not both.", |
| | 0 | 314 | | { Steps: < 1 } => "--steps must be at least 1.", |
| | 54 | 315 | | _ => null |
| | 54 | 316 | | }; |
| | | 317 | | |
| | 72 | 318 | | private static int? Steps( DownSettings settings ) => settings.To is null ? settings.Steps ?? 1 : null; |
| | | 319 | | |
| | | 320 | | private void Warnings( IEnumerable<Error> warnings ) |
| | | 321 | | { |
| | 369 | 322 | | foreach ( var warning in warnings ) { _console.MarkupLine( $"[yellow]warning:[/] {Markup.Escape( SeedDesigner.De |
| | 171 | 323 | | } |
| | | 324 | | |
| | 3 | 325 | | private int Errors( IEnumerable<Error> errors ) => Errors( errors.Select( SeedDesigner.Describe ) ); |
| | | 326 | | |
| | | 327 | | private int Errors( IEnumerable<string> errors ) |
| | | 328 | | { |
| | 165 | 329 | | foreach ( var error in errors ) { _console.MarkupLine( $"[red]error:[/] {Markup.Escape( error )}" ); } |
| | | 330 | | |
| | 33 | 331 | | return 1; |
| | | 332 | | } |
| | | 333 | | } |