Conditional Logic in Migrations
FluentMigrator provides powerful conditional logic capabilities that allow you to create adaptive migrations that behave differently based on database providers, environments, existing schema state, or custom conditions. This guide covers all aspects of conditional migration logic.
Database Provider Conditionals
Provider conditionals can be achieved using the IfDatabase method, which allows you to execute specific migration steps based on the database type.
It can take a single provider name or an array of provider names, or a custom predicate function:
// Will also match "SqlServer2019", "SqlServer2022", etc.
IfDatabase(ProcessorIdConstants.SqlServer).Execute.Sql("...");
// Matches multiple providers
IfDatabase(new[] { ProcessorIdConstants.SqlServer, ProcessorIdConstants.Postgres }).Execute.Sql("...");
// Custom predicate function
IfDatabase(db =>
db.StartsWith(ProcessorIdConstants.SqlServer, StringComparison.InvariantCultureIgnoreCase) ||
db.StartsWith(ProcessorIdConstants.Postgres, StringComparison.InvariantCultureIgnoreCase)
).Execute.Sql("...");Provider Detection
[Migration(202401151000)]
public class DatabaseProviderConditionals : Migration
{
public override void Up()
{
Create.Table("CrossPlatformTable")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(100).NotNullable()
.WithColumn("CreatedAt").AsDateTime().NotNullable();
// SQL Server specific features
IfDatabase(ProcessorIdConstants.SqlServer).Execute.Sql(@"
CREATE INDEX IX_CrossPlatformTable_Name_Active
ON CrossPlatformTable (Name)
WHERE Name IS NOT NULL");
// PostgreSQL specific features
IfDatabase(ProcessorIdConstants.Postgres).Execute.Sql(@"
CREATE INDEX IX_CrossPlatformTable_JsonData
ON CrossPlatformTable USING GIN (JsonData)");
// MySQL specific features
IfDatabase(ProcessorIdConstants.MySql).Execute.Sql("ALTER TABLE CrossPlatformTable ENGINE=InnoDB");
// SQLite specific features
IfDatabase(ProcessorIdConstants.SQLite).Execute.Sql("CREATE INDEX IX_CrossPlatformTable_Name ON CrossPlatformTable (Name)");
// Oracle specific features
IfDatabase(ProcessorIdConstants.Oracle).Execute.Sql("CREATE INDEX IX_CrossPlatformTable_Name ON CrossPlatformTable (UPPER(Name))");
}
public override void Down()
{
Delete.Table("CrossPlatformTable");
}
}Schema State Conditionals
Conditional Based on Existing Schema
[Migration(202401151400)]
public class SchemaStateConditionals : Migration
{
public override void Up()
{
// Check if tables exist before creating or altering them
if (!Schema.Table("Users").Exists())
{
CreateUsersTable();
}
else
{
ModifyExistingUsersTable();
}
// Conditional column addition based on existing columns
if (!Schema.Table("Users").Column("Email").Exists())
{
Alter.Table("Users")
.AddColumn("Email").AsString(255).Nullable();
}
// Conditional index creation
if (!Schema.Table("Users").Index("IX_Users_Email").Exists())
{
Create.Index("IX_Users_Email")
.OnTable("Users")
.OnColumn("Email");
}
// Conditional constraint creation
if (!Schema.Table("Users").Constraint("CK_Users_Email_Format").Exists())
{
Execute.Sql(@"
ALTER TABLE Users
ADD CONSTRAINT CK_Users_Email_Format
CHECK (Email IS NULL OR Email LIKE '%@%')");
}
// Check for foreign key relationships
if (Schema.Table("Orders").Exists() &&
!Schema.Table("Orders").Constraint("FK_Orders_Users").Exists())
{
Create.ForeignKey("FK_Orders_Users")
.FromTable("Orders").ForeignColumn("UserId")
.ToTable("Users").PrimaryColumn("Id");
}
}
private void CreateUsersTable()
{
Console.WriteLine("Creating Users table...");
Create.Table("Users")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Username").AsString(50).NotNullable()
.WithColumn("Email").AsString(255).Nullable()
.WithColumn("CreatedAt").AsDateTime().NotNullable().WithDefaultValue(SystemMethods.CurrentDateTime);
}
private void ModifyExistingUsersTable()
{
Console.WriteLine("Modifying existing Users table...");
// Only add columns that don't exist
if (!Schema.Table("Users").Column("LastLoginAt").Exists())
{
Alter.Table("Users")
.AddColumn("LastLoginAt").AsDateTime().Nullable();
}
if (!Schema.Table("Users").Column("IsActive").Exists())
{
Alter.Table("Users")
.AddColumn("IsActive").AsBoolean().NotNullable().WithDefaultValue(true);
}
}
public override void Down()
{
// Conditional rollback - only drop if we created it
if (Schema.Table("Users").Exists())
{
// Remove constraints we may have added
Execute.Sql("ALTER TABLE Users DROP CONSTRAINT IF EXISTS CK_Users_Email_Format");
// Remove indexes we may have added
if (Schema.Table("Users").Index("IX_Users_Email").Exists())
{
Delete.Index("IX_Users_Email").OnTable("Users");
}
// Remove columns we may have added
if (Schema.Table("Users").Column("LastLoginAt").Exists())
{
Delete.Column("LastLoginAt").FromTable("Users");
}
if (Schema.Table("Users").Column("IsActive").Exists())
{
Delete.Column("IsActive").FromTable("Users");
}
}
}
}Which schema the checks look in
An idempotent migration has two halves, and they only work together if they point at the same schema:
if (!Schema.Table("Users").Exists()) // the check: a query the processor runs right away
{
Create.Table("Users") // the create: SQL the generator writes
.WithColumn("Id").AsInt32().PrimaryKey();
}The two halves are handled differently. Create.Table(...) is an expression: the runner collects it, applies its conventions (such as the default schema), and the generator turns it into SQL after Up() returns. Schema.Table(...).Exists() is a processor-level check: it queries the database through the processor right away, while Up() is still running. The runner's conventions don't apply to it by themselves. Since 9.0 the check asks the runner for the schema the convention would use, as described below. If you call the processor yourself, for example IMigrationProcessor.TableExists(schema, table), no convention is applied at all, so pass the schema you mean.
If the check looks in one schema and the create writes to another, the check never finds the table. The first run is fine, and the next migration that repeats the check fails with "already exists". The opposite mismatch is worse: if the check finds a table of the same name in some other schema, the migration skips the create, and nothing reports that the table is missing.
With a default schema (recommended)
If your convention set has a default schema, both halves use it:
services.AddSingleton<IConventionSet>(new DefaultConventionSet("app", workingDirectory: null));With dotnet-fm, use --default-schema-name app. Then Schema.Table("Users").Exists() checks app.Users, and Create.Table("Users") creates app.Users. The same goes for Schema.Sequence(...) and for the column, index and constraint checks under Schema.Table(...). The $(DefaultSchema) token in Execute.Sql is app too, because the token and the checks get the schema from the same service, IDefaultSchemaNameResolver.
This is the most reliable setup on every provider, because neither half falls back to a provider default.
Without a default schema
The check passes no schema to the database provider, and the provider picks one. That isn't always the connection's current schema. What matters is whether the provider's check and its generated SQL pick the same one:
| Provider | Check with no schema | Create with no schema | Agree? |
|---|---|---|---|
| PostgreSQL, tables | public | "public"."Users" | Yes |
| PostgreSQL, sequences | public | CREATE SEQUENCE "Seq", so the first schema on search_path | Only if that schema is public |
| SQL Server | dbo | [dbo].[Users] | Yes |
| Oracle | USER_TABLES / USER_SEQUENCES: the login's own schema | CREATE TABLE Users, so the session's current schema | Yes, unless the session changes CURRENT_SCHEMA |
| Db2 | any schema: the check has no schema filter | CREATE TABLE Users, so CURRENT SCHEMA | Only if no other schema has an object with that name |
On PostgreSQL and SQL Server, the connection's search_path or the login's default schema doesn't change where the check looks.
Two cases fail:
- PostgreSQL sequences. With the default
search_path("$user", public) and a schema named after the login,Create.Sequence("Seq")creates the sequence in that schema.Schema.Sequence("Seq").Exists()still looks inpublic, so a repeated check creates the sequence again and fails. - Db2. If another schema already has a
Userstable,Schema.Table("Users").Exists()returnstrue. The migration skipsCreate.Table("Users"), and the table is never created in your schema.
In both cases, configure a default schema as shown above, or name the schema in both halves:
if (!Schema.Schema("app").Sequence("Seq").Exists())
{
Create.Sequence("Seq").InSchema("app");
}Naming a schema explicitly
Schema.Schema("audit").Table("Users").Exists()looks forUsersinaudit. The name goes through the same schema convention asCreate.Table("Users").InSchema("audit"), so a custom convention that renames schemas applies to both.Schema.Schema("audit").Exists()checks forauditexactly as written.Create.Schema("audit")doesn't go through the schema convention, so the check doesn't either.
Before 9.0
Checks without a schema ignored the convention set's default schema and always used the provider's choice from the table above. With a default schema configured, Create.Table("Users") created app.Users while Schema.Table("Users").Exists() looked in public or dbo. So an idempotent migration missed the table it had created itself and tried to create it again (issue #1055).
Custom Conditional Logic
Feature Flag-Based Conditionals
[Migration(202401151600)]
public class FeatureFlagConditionals : Migration
{
public override void Up()
{
var featureFlags = GetFeatureFlags();
Create.Table("FeatureBasedTable")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(100).NotNullable();
// Apply features based on flags
if (featureFlags.Contains("ENHANCED_SEARCH"))
{
EnableEnhancedSearch();
}
if (featureFlags.Contains("ADVANCED_ANALYTICS"))
{
EnableAdvancedAnalytics();
}
}
private HashSet<string> GetFeatureFlags()
{
var flagsString = Environment.GetEnvironmentVariable("FEATURE_FLAGS") ?? "";
return flagsString.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(f => f.Trim().ToUpper())
.ToHashSet();
}
private void EnableEnhancedSearch()
{
Console.WriteLine("Enabling enhanced search features...");
Alter.Table("FeatureBasedTable")
.AddColumn("SearchKeywords").AsString(1000).Nullable()
.AddColumn("SearchRanking").AsInt32().NotNullable().WithDefaultValue(0);
// Create full-text search support
IfDatabase(ProcessorIdConstants.SqlServer).Execute.Sql("CREATE FULLTEXT CATALOG SearchCatalog AS DEFAULT");
IfDatabase(ProcessorIdConstants.Postgres).Execute.Sql("ALTER TABLE FeatureBasedTable ADD COLUMN SearchVector tsvector");
}
private void EnableAdvancedAnalytics()
{
Console.WriteLine("Enabling advanced analytics features...");
// Create analytics tables
Create.Table("AnalyticsEvents")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("EntityId").AsInt32().NotNullable()
.WithColumn("EventType").AsString(50).NotNullable()
.WithColumn("EventData").AsString(2000).Nullable()
.WithColumn("UserId").AsInt32().Nullable()
.WithColumn("SessionId").AsString(100).Nullable()
.WithColumn("Timestamp").AsDateTime().NotNullable().WithDefaultValue(SystemMethods.CurrentDateTime);
Create.Table("AnalyticsSummary")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("EntityId").AsInt32().NotNullable()
.WithColumn("SummaryDate").AsDate().NotNullable()
.WithColumn("ViewCount").AsInt32().NotNullable().WithDefaultValue(0)
.WithColumn("InteractionCount").AsInt32().NotNullable().WithDefaultValue(0)
.WithColumn("UniqueUsers").AsInt32().NotNullable().WithDefaultValue(0);
// Add analytics columns to main table
Alter.Table("FeatureBasedTable")
.AddColumn("AnalyticsEnabled").AsBoolean().NotNullable().WithDefaultValue(true)
.AddColumn("LastAnalyticsUpdate").AsDateTime().Nullable();
}
public override void Down()
{
// Clean up feature-specific tables and columns
Execute.Sql("DROP TABLE IF EXISTS SecurityEvents");
Execute.Sql("DROP TABLE IF EXISTS AnalyticsSummary");
Execute.Sql("DROP TABLE IF EXISTS AnalyticsEvents");
IfDatabase(ProcessorIdConstants.SqlServer).Execute.Sql("DROP FULLTEXT INDEX ON FeatureBasedTable");
Delete.Table("FeatureBasedTable");
}
}Best Practices for Conditional Logic
✅ Do:
- Use database provider conditionals for database-specific optimizations
- Validate schema state before making assumptions
- Document all conditional logic clearly
- Test all conditional paths thoroughly
❌ Don't:
- Rely on conditionals for core business logic that should be in application code
- Create overly complex nested conditions that are hard to maintain
- Skip error handling in conditional branches
- Make assumptions about schema state without validation
- Use conditionals to work around poor design decisions
Conditional logic in migrations enables powerful, adaptive database evolution while maintaining compatibility across different environments and scenarios.