SchemaDiff

Classes > Migration > SchemaDiff

Calculates the difference between two schema definitions. Produces a list of operations to transform current schema into desired schema.

public static class SchemaDiff

Example

// Compare current database schema against desired schema
var currentSchema = await schemaInspector.InspectAsync(connection);
var desiredSchema = Schema.Define("mydb")
    .Table("users", t => t
        .Column("id", PortableTypes.Uuid, c => c.PrimaryKey())
        .Column("email", PortableTypes.VarChar(255), c => c.NotNull())
        .Column("name", PortableTypes.VarChar(100)))  // New column
    .Build();

// Calculate safe (additive-only) migration operations
var result = SchemaDiff.Calculate(currentSchema, desiredSchema);
if (result is OperationsResult.Ok<IReadOnlyList<SchemaOperation>, MigrationError> ok)
{
    foreach (var op in ok.Value)
    {
        var ddl = ddlGenerator.Generate(op);
        await connection.ExecuteAsync(ddl);
    }
}

// Or allow destructive changes (DROP operations)
var destructiveResult = SchemaDiff.Calculate(
    currentSchema, desiredSchema, allowDestructive: true);

Methods

Calculate(SchemaDefinition, SchemaDefinition, bool, ILogger?)

public static Result<IReadOnlyList<SchemaOperation>, MigrationError> Calculate(SchemaDefinition current, SchemaDefinition desired, bool allowDestructive = false, ILogger? logger = null)

Calculate operations needed to transform current schema into desired schema. By default, only produces additive operations (safe upgrades).

Parameters:

Name Type Description
current SchemaDefinition Current database schema
desired SchemaDefinition Desired target schema
allowDestructive Boolean If true, include DROP operations
logger ILogger Logger for diagnostics

Returns: MigrationError> - List of operations to apply