LowCodeHub.Migration.SqlServer
0.0.13
See the version list below for details.
dotnet add package LowCodeHub.Migration.SqlServer --version 0.0.13
NuGet\Install-Package LowCodeHub.Migration.SqlServer -Version 0.0.13
<PackageReference Include="LowCodeHub.Migration.SqlServer" Version="0.0.13" />
<PackageVersion Include="LowCodeHub.Migration.SqlServer" Version="0.0.13" />
<PackageReference Include="LowCodeHub.Migration.SqlServer" />
paket add LowCodeHub.Migration.SqlServer --version 0.0.13
#r "nuget: LowCodeHub.Migration.SqlServer, 0.0.13"
#:package LowCodeHub.Migration.SqlServer@0.0.13
#addin nuget:?package=LowCodeHub.Migration.SqlServer&version=0.0.13
#tool nuget:?package=LowCodeHub.Migration.SqlServer&version=0.0.13
LowCodeHub.Migration.SqlServer
A startup migration runner for SQL Server. You embed plain .sql scripts in your assembly. The runner orders them by their Unix-timestamp prefix and runs each one in its own transaction, under a database-wide lock. DbUp records which scripts have run in its journal table.
Installation
dotnet add package LowCodeHub.Migration.SqlServer
Quick start
- Embed your scripts and add a marker type, which tells the runner which assembly holds them:
<ItemGroup>
<EmbeddedResource Include="Migrations\**\*.sql" />
</ItemGroup>
public sealed class AppMigrations; // any type in the assembly that holds the scripts
- Register the migrations and run them at startup:
using LowCodeHub.Migration.SqlServer.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSqlServerMigrations<AppMigrations>(
builder.Configuration.GetConnectionString("Default")!);
var app = builder.Build();
await app.RunSqlServerMigrationAsync(app.Lifetime.ApplicationStopping);
app.Run();
With these defaults the runner:
- creates the database if it is missing;
- runs every embedded
.sqlscript in the assembly that has not run before; - holds a database-wide lock, so only one instance migrates at a time;
- throws if it finds no scripts.
RunSqlServerMigrationAsync extends IHost, so it also works with Worker Service apps.
Binding from configuration
{
"Migrations": {
"ConnectionString": "Server=.;Database=App;Trusted_Connection=True;Encrypt=False",
"Directories": [ "MyApp.Migrations" ],
"ScriptTimeout": "00:10:00",
"LockTimeout": "00:05:00"
}
}
builder.Services.AddSqlServerMigrations<AppMigrations>(builder.Configuration.GetSection("Migrations"));
The connection-string and configuration overloads both accept an optional Action<MigrationOptions>, which runs after binding.
Multiple targets
Add one target per database or script assembly. Targets run in registration order:
builder.Services.AddSqlServerMigrations(migrations =>
{
migrations.AddTarget<UsersMigrations>(builder.Configuration.GetConnectionString("UsersDb")!, o =>
{
o.Directories = ["MyApp.Users.Migrations"];
o.AlwaysExecuteDirectories = ["MyApp.Users.Always"];
});
migrations.AddTarget<BillingMigrations>(builder.Configuration.GetSection("BillingMigrations"));
});
You can call AddSqlServerMigrations more than once, for example once from each module. The targets from every call accumulate.
Options (MigrationOptions)
| Option | Default | Description |
|---|---|---|
ConnectionString |
required | SQL Server connection string. Validated at registration. |
Directories |
null (all) |
Embedded-resource folders (dot-separated, e.g. MyApp.Migrations) that hold the journaled scripts. null means every .sql resource that is not in an always-execute folder. |
AlwaysExecuteDirectories |
null |
Folders whose scripts run on every startup and are not journaled. These scripts must be idempotent. |
FailOnNoScriptsFound |
true |
Throw if the target has no scripts. |
EnsureDatabaseExists |
true |
Create the database if it is missing. Needs CREATE DATABASE permission. If several instances try to create it at the same moment, the runner tolerates the "already exists" error (1801). |
UseDistributedLock |
true |
Hold an exclusive sp_getapplock (session owner) for the whole run of the target. |
LockTimeout |
null (wait) |
Maximum time to wait while another instance holds the lock. null or Timeout.InfiniteTimeSpan waits until the lock is free or the run is cancelled. When the timeout expires, the runner throws TimeoutException. |
ScriptTimeout |
null (30 s) |
Command timeout for each script. Timeout.InfiniteTimeSpan or TimeSpan.Zero disables it. |
Invalid values throw ArgumentException when the target is registered: a missing or malformed connection string, or a negative timeout.
Script naming and ordering
Each script name must start with a numeric Unix-timestamp prefix, such as 1766733156_create_users.sql. Names like create_users.sql or v1_users.sql fail startup.
Within each target, the runner orders scripts by:
- the numeric prefix, ascending;
- then the full resource name, ordinal.
Folder names only filter scripts; they never affect the order.
Transactions
Each script runs in its own transaction. If a script fails, only that script rolls back, and the run stops.
Some statements cannot run inside a transaction, for example ALTER DATABASE and some full-text DDL. To opt one script out, put the marker on its own line in the script's leading comment block:
-- lowcodehub:no-transaction
ALTER DATABASE CURRENT SET ALLOW_SNAPSHOT_ISOLATION ON;
If a script without a transaction fails, its partial changes are not rolled back. Keep these scripts small and idempotent.
Execution order per target
- The runner discovers the scripts and sorts them into journaled and always-execute groups.
- It creates the database if it is missing.
- It acquires
sp_getapplockon a dedicated connection. The wait itself has no command timeout;LockTimeoutand the cancellation token bound it. - It reads the journal once and runs each pending journaled script, then every always-execute script.
- It releases the lock. If the release fails, it clears the pooled connection so the lock is not kept alive.
If a target fails, the runner stops and skips the targets after it.
Scripts run synchronously, because DbUp has no async API. The cancellation token aborts the lock wait, and the runner checks it again between scripts. A script that is already running finishes or rolls back.
DbUp's output goes to your ILogger and is not written to the console.
Observability
Each target and each executed script emits an Activity from SqlServerMigrationDiagnostics.ActivitySourceName ("LowCodeHub.Migration.SqlServer"):
builder.Services.AddOpenTelemetry().WithTracing(t => t.AddSource(SqlServerMigrationDiagnostics.ActivitySourceName));
The package has no health check. Migrations run before the app starts serving, so a failed migration fails startup.
Best practices
- Never rename a script after it is merged. The journal tracks scripts by resource name.
- Keep one concern per script.
- Put scripts in
AlwaysExecuteDirectoriesonly if they are idempotent, for example views or permissions written withCREATE OR ALTER. - For long data migrations, set
ScriptTimeoutinstead of relying on the 30 s default.
Requirements
- .NET 10 or later
dbup-sqlserver7.2+ (included as a dependency)
License
MIT (c) Ahmed Abuelnour
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- dbup-sqlserver (>= 7.2.0)
- Microsoft.Data.SqlClient (>= 7.1.1)
- System.Security.Cryptography.Pkcs (>= 10.0.13)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.