LowCodeHub.Migration.PostgreSql 0.1.0

dotnet add package LowCodeHub.Migration.PostgreSql --version 0.1.0
                    
NuGet\Install-Package LowCodeHub.Migration.PostgreSql -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LowCodeHub.Migration.PostgreSql" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.Migration.PostgreSql" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.Migration.PostgreSql" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LowCodeHub.Migration.PostgreSql --version 0.1.0
                    
#r "nuget: LowCodeHub.Migration.PostgreSql, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LowCodeHub.Migration.PostgreSql@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LowCodeHub.Migration.PostgreSql&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.Migration.PostgreSql&version=0.1.0
                    
Install as a Cake Tool

LowCodeHub.Migration.PostgreSql

A startup migration runner for PostgreSQL. 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.

NuGet License: MIT

Installation

dotnet add package LowCodeHub.Migration.PostgreSql

Quick start

  1. 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
  1. Register the migrations and run them at startup:
using LowCodeHub.Migration.PostgreSql.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddPostgreSqlMigrations<AppMigrations>(
    builder.Configuration.GetConnectionString("Default")!);

var app = builder.Build();
await app.RunPostgreSqlMigrationAsync(app.Lifetime.ApplicationStopping);
app.Run();

With these defaults the runner:

  • creates the database if it is missing;
  • runs every embedded .sql script 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.

RunPostgreSqlMigrationAsync extends IHost, so it also works with Worker Service apps.

Binding from configuration

{
  "Migrations": {
    "ConnectionString": "Host=localhost;Database=app;Username=app;Password=secret",
    "Directories": [ "MyApp.Migrations" ],
    "ScriptTimeout": "00:10:00",
    "LockTimeout": "00:05:00"
  }
}
builder.Services.AddPostgreSqlMigrations<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.AddPostgreSqlMigrations(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 AddPostgreSqlMigrations more than once, for example once from each module. The targets from every call accumulate.

Options (MigrationOptions)

Option Default Description
ConnectionString required PostgreSQL (Npgsql) 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 the CREATEDB privilege. If several instances try to create it at the same moment, the runner tolerates the "already exists" errors (42P04 / 23505).
UseDistributedLock true Hold a session-level pg_advisory_lock 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. The timeout is applied through lock_timeout.
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:

  1. the numeric prefix, ascending;
  2. 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 block, for example CREATE INDEX CONCURRENTLY, ALTER TYPE ... ADD VALUE (before PG 12) and VACUUM. To opt one script out, put the marker on its own line in the script's leading comment block:

-- lowcodehub:no-transaction
CREATE INDEX CONCURRENTLY ix_orders_customer ON orders (customer_id);

If a script without a transaction fails, its partial changes are not rolled back. Keep these scripts small and idempotent.

Execution order per target

  1. The runner discovers the scripts and sorts them into journaled and always-execute groups.
  2. It creates the database if it is missing.
  3. It acquires pg_advisory_lock on a dedicated connection. The wait itself has no command timeout; LockTimeout and the cancellation token bound it.
  4. It reads the journal once and runs each pending journaled script, then every always-execute script.
  5. 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 PostgreSqlMigrationDiagnostics.ActivitySourceName ("LowCodeHub.Migration.PostgreSql"):

builder.Services.AddOpenTelemetry().WithTracing(t => t.AddSource(PostgreSqlMigrationDiagnostics.ActivitySourceName));

The package has no health check. Migrations run before the app starts serving, so a failed migration fails startup.

Best practices

  1. Never rename a script after it is merged. The journal tracks scripts by resource name.
  2. Keep one concern per script.
  3. Put scripts in AlwaysExecuteDirectories only if they are idempotent, for example views or permissions written with CREATE OR REPLACE.
  4. For long data migrations, set ScriptTimeout instead of relying on the 30 s default.

Requirements

  • .NET 11 or later
  • dbup-postgresql 7.0+ (included as a dependency)

License

MIT (c) Ahmed Abuelnour

AI agent skills

This package targets net11.0 and includes version-matched agent instructions under skills/. After restoring your application's dependencies, install them into your agent's skill directory:

dotnet tool install --global dotnet-package-skills --prerelease
dotnet-package-skills install

The default destination is .agents/skills/. For Claude, pass --destination .claude/skills. Run the installer again after package upgrades.

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 163 11/15/2026
0.0.13 166 10/22/2026
0.0.12 1,018 7/3/2026
0.0.11 151 6/23/2026
0.0.10 132 6/21/2026
0.0.3 940 5/18/2026
0.0.2 136 4/23/2026