StellaOps.Infrastructure.Postgres

Shared PostgreSQL infrastructure for StellaOps modules

library
Component
Workflow
Licence
BUSL-1.1 (Workflow licence)
Target framework
net10.0
Latest release
1.0.1-20261118T121708Z

Install

dotnet add package StellaOps.Infrastructure.Postgres --version 1.0.1-20261118T121708Z

Namespaces

NamespaceTypes
StellaOps.Infrastructure.Postgres1
StellaOps.Infrastructure.Postgres.Capacity29
StellaOps.Infrastructure.Postgres.Connections2
StellaOps.Infrastructure.Postgres.Exceptions1
StellaOps.Infrastructure.Postgres.Migrations32
StellaOps.Infrastructure.Postgres.Options1
StellaOps.Infrastructure.Postgres.Repositories1
StellaOps.Infrastructure.Postgres.Testing2

namespace StellaOps.Infrastructure.Postgres

TypeKindDescription
ServiceCollectionExtensionsclassExtension methods for configuring PostgreSQL infrastructure services.

class ServiceCollectionExtensions

public static class ServiceCollectionExtensions

Extension methods for configuring PostgreSQL infrastructure services.

Members

MemberKindSummary
AddPostgresInfrastructure(IServiceCollection, Action<PostgresOptions>)extension methodAdds PostgreSQL infrastructure with the specified options.
AddPostgresOptions(IServiceCollection, IConfiguration, string)extension methodAdds PostgreSQL infrastructure options from configuration.

extension method AddPostgresInfrastructure(IServiceCollection, Action<PostgresOptions>) #

public static IServiceCollection AddPostgresInfrastructure(this IServiceCollection services, Action<PostgresOptions> configureOptions)

Adds PostgreSQL infrastructure with the specified options.

Parameters

  • services: Service collection.
  • configureOptions: Options configuration action.

Returns

Service collection for chaining.

extension method AddPostgresOptions(IServiceCollection, IConfiguration, string) #

public static IServiceCollection AddPostgresOptions(this IServiceCollection services, IConfiguration configuration, string sectionName = "Postgres")

Adds PostgreSQL infrastructure options from configuration.

Parameters

  • services: Service collection.
  • configuration: Configuration root.
  • sectionName: Configuration section name for PostgreSQL options.

Returns

Service collection for chaining.

namespace StellaOps.Infrastructure.Postgres.Capacity

TypeKindDescription
CapacityAssessmentrecordThe capacity verdict an operator sees, with its evidence.
CapacityBudgetRegisterclassReads budgets from the data identity register, the one source of truth for them.
CapacityBudgetSetrecordEverything one host’s probe measures against, with the register version it came from.
CapacityCountSessionclassThe probe’s READ ONLY transaction as a count sees it.
CapacityDatabaseBudgetrecordA service database’s byte budget, with its shrink-only interim ceiling.
CapacityDuplicationBudgetrecordOne duplication line’s budget, read from the register entry’s budget.duplication.
CapacityDuplicationCountstructA count, and whether it stopped at the cap it was given.
CapacityDuplicationMeasurementrecordOne duplication line as measured.
CapacityEvaluatorclassTurns a measurement into a receipt; pure, so a health check and the probe agree.
CapacityEventLedgerMeasurementrecordAn eventing ledger as measured: the rows written in the trailing CapacityEvaluator.EventRateWindow.
CapacityEventRateBudgetrecordAn eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.EventRateWindowdivided by its days.
CapacityLinerecordOne measured value against its lines.
CapacityMeasurementrecordThe host database and its registered tables at one instant.
CapacityPauseCauseenumWhy a writer gate is closed.
CapacityReceiptrecordOne probe run, as written to <schema>.capacity_probe_receipt.
CapacityReceiptAssessmentclassJudges the newest receipt.
CapacityReceiptWriterGateclassCloses while the newest receipt shows the database at or above its stop line, while the newest receipt is older than CapacityWriterGateOptions.StaleAfter, and while no receipt exists once CapacityWriterGateOptions.UnmeasuredGraceafter the gate started has passed.
CapacityTableBudgetrecordOne registered table’s budget, read from the data-identity register.
CapacityTableMeasurementrecordOne registered table as measured.
CapacityVerdictenumThe verdict of a capacity line or receipt.
CapacityWriterGateDecisionrecordWhether a writer may start a cycle, and if not, the reason an operator reads.
CapacityWriterGateOptionsclassSettings of the capacity writer gate (Capacity:WriterGate).
CapacityWriterGateServiceCollectionExtensionsclassRegisters the capacity writer gate.
ICapacityDuplicationLineinterfaceThe owning host’s count for one duplication line.
ICapacityReceiptStoreinterfaceReads and writes one host database’s capacity receipts.
ICapacityWriterGateinterfaceConsulted by a writer before a write cycle.
PostgresCapacityDuplicationProbeclassMeasures the declared duplication lines with the owning host’s counts.
PostgresCapacityProbeclassCatalog-only measurement: pg_total_relation_size and pg_class.reltuples (a partitioned table sums its partition tree, because its own size is zero and pg_partition_tree lists nothing for a plain table), plus pg_database_size.
PostgresCapacityReceiptStoreclass<schema>.capacity_probe_receipt in the host’s own database.

record CapacityAssessment

public sealed record CapacityAssessment

The capacity verdict an operator sees, with its evidence.

Parameters

  • Verdict: The verdict.
  • Message: The operator message.
  • Evidence: The evidence, by key, in key order.

Members

MemberKindSummary
CapacityAssessment(CapacityVerdict, string, IReadOnlyDictionary<string, string>)constructorThe capacity verdict an operator sees, with its evidence.
EvidencepropertyThe evidence, by key, in key order.
MessagepropertyThe operator message.
VerdictpropertyThe verdict.

constructor CapacityAssessment(CapacityVerdict, string, IReadOnlyDictionary<string, string>) #

public CapacityAssessment(CapacityVerdict Verdict, string Message, IReadOnlyDictionary<string, string> Evidence)

The capacity verdict an operator sees, with its evidence.

Parameters

  • Verdict: The verdict.
  • Message: The operator message.
  • Evidence: The evidence, by key, in key order.

property Evidence #

public IReadOnlyDictionary<string, string> Evidence { get; init; }

The evidence, by key, in key order.

property Message #

public string Message { get; init; }

The operator message.

property Verdict #

public CapacityVerdict Verdict { get; init; }

The verdict.

class CapacityBudgetRegister

public static class CapacityBudgetRegister

Reads budgets from the data identity register, the one source of truth for them. Each owning host embeds the register under CapacityBudgetRegister.ResourceName; nothing copies a budget into code or configuration.

Members

MemberKindSummary
InterimHeadroomconstantHeadroom above a pinned measurement before a pinned table reaches its stop line.
ResourceNameconstantThe logical name every host embeds the register under.
LoadEmbedded(Assembly, string)methodReads the budgets of a database from the register an assembly embeds under CapacityBudgetRegister.ResourceName.
Parse(byte[], string)methodReads the budgets of a database from the register: the database budget and its event rates, the table budgets of its family’s entries with their duplication lines, and the interim lines of the pins that cover budget.

constant InterimHeadroom #

public const readonly decimal InterimHeadroom = 1.05

Headroom above a pinned measurement before a pinned table reaches its stop line.

constant ResourceName #

public const string ResourceName = "StellaOps.Capacity.DataIdentityRegister.json"

The logical name every host embeds the register under.

method LoadEmbedded(Assembly, string) #

public static CapacityBudgetSet LoadEmbedded(Assembly assembly, string database)

Reads the budgets of a database from the register an assembly embeds under CapacityBudgetRegister.ResourceName.

Parameters

  • assembly: The assembly.
  • database: The register’s name for the database.

Returns

The budgets.

Exceptions

  • InvalidOperationException: The assembly does not embed the register, or the register declares no budget for the database.

method Parse(byte[], string) #

public static CapacityBudgetSet Parse(byte[] registerJson, string database)

Reads the budgets of a database from the register: the database budget and its event rates, the table budgets of its family’s entries with their duplication lines, and the interim lines of the pins that cover budget.

Parameters

  • registerJson: The register, as UTF-8 JSON.
  • database: The register’s name for the database.

Returns

The budgets, with the SHA-256 of the register.

Exceptions

  • InvalidOperationException: The register declares no budget, or more than one, for the database.

record CapacityBudgetSet

public sealed record CapacityBudgetSet

Everything one host’s probe measures against, with the register version it came from.

Parameters

  • Database: The database budget.
  • Tables: The table budgets, ordered by table.
  • RegisterSha256: The SHA-256 of the register the budgets came from.
  • EventRates: The database’s eventing ledger budgets, ordered by ledger; empty when the register declares none.
  • Duplication: The family’s duplication line budgets, ordered by table and metric.

Members

MemberKindSummary
CapacityBudgetSet(CapacityDatabaseBudget, IReadOnlyList<CapacityTableBudget>, string, IReadOnlyList<CapacityEventRateBudget>, IReadOnlyList<CapacityDuplicationBudget>)constructorEverything one host’s probe measures against, with the register version it came from.
DatabasepropertyThe database budget.
DuplicationpropertyThe family’s duplication line budgets, ordered by table and metric.
EventRatespropertyThe database’s eventing ledger budgets, ordered by ledger; empty when the register declares none.
RegisterSha256propertyThe SHA-256 of the register the budgets came from.
TablespropertyThe table budgets, ordered by table.

constructor CapacityBudgetSet(CapacityDatabaseBudget, IReadOnlyList<CapacityTableBudget>, string, IReadOnlyList<CapacityEventRateBudget>, IReadOnlyList<CapacityDuplicationBudget>) #

public CapacityBudgetSet(CapacityDatabaseBudget Database, IReadOnlyList<CapacityTableBudget> Tables, string RegisterSha256, IReadOnlyList<CapacityEventRateBudget>? EventRates = null, IReadOnlyList<CapacityDuplicationBudget>? Duplication = null)

Everything one host’s probe measures against, with the register version it came from.

Parameters

  • Database: The database budget.
  • Tables: The table budgets, ordered by table.
  • RegisterSha256: The SHA-256 of the register the budgets came from.
  • EventRates: The database’s eventing ledger budgets, ordered by ledger; empty when the register declares none.
  • Duplication: The family’s duplication line budgets, ordered by table and metric.

property Database #

public CapacityDatabaseBudget Database { get; init; }

The database budget.

property Duplication #

public IReadOnlyList<CapacityDuplicationBudget>? Duplication { get; init; }

The family’s duplication line budgets, ordered by table and metric.

property EventRates #

public IReadOnlyList<CapacityEventRateBudget>? EventRates { get; init; }

The database’s eventing ledger budgets, ordered by ledger; empty when the register declares none.

property RegisterSha256 #

public string RegisterSha256 { get; init; }

The SHA-256 of the register the budgets came from.

property Tables #

public IReadOnlyList<CapacityTableBudget> Tables { get; init; }

The table budgets, ordered by table.

class CapacityCountSession

public sealed class CapacityCountSession

The probe’s READ ONLY transaction as a count sees it. A count creates its commands here, never on a raw connection: each command’s client timeout is longer than the posture’s statement timeout, so a slow count is cancelled by the server (SQLSTATE 57014), rolled back to its savepoint and reported absent. With a client timeout shorter than the statement timeout (Npgsql’s default is 30 s), a slow count would end the pass with a client-side TimeoutException and write no receipt.

Members

MemberKindSummary
ClientTimeoutMarginfieldHow long a command’s client timeout outlasts the statement timeout, so the server cancels first.
CommandTimeoutSecondspropertyThe client timeout, in whole seconds, every command of this session carries.
ClientTimeoutSeconds(TimeSpan)methodThe statement timeout rounded up to whole seconds, plus CapacityCountSession.ClientTimeoutMargin.
CreateCommand(string)methodA command in the probe’s transaction whose client timeout outlasts the statement timeout.

field ClientTimeoutMargin #

public static readonly TimeSpan ClientTimeoutMargin

How long a command’s client timeout outlasts the statement timeout, so the server cancels first.

property CommandTimeoutSeconds #

public int CommandTimeoutSeconds { get; }

The client timeout, in whole seconds, every command of this session carries.

method ClientTimeoutSeconds(TimeSpan) #

public static int ClientTimeoutSeconds(TimeSpan statementTimeout)

The statement timeout rounded up to whole seconds, plus CapacityCountSession.ClientTimeoutMargin.

method CreateCommand(string) #

public NpgsqlCommand CreateCommand(string sql)

A command in the probe’s transaction whose client timeout outlasts the statement timeout.

record CapacityDatabaseBudget

public sealed record CapacityDatabaseBudget

A service database’s byte budget, with its shrink-only interim ceiling.

Parameters

  • Database: The register’s name for the database.
  • Family: The service family that owns the database.
  • Bytes: The byte budget of the database.
  • Alarm: The alarm line as a ratio of a budget, for every line of the database.
  • Stop: The stop line as a ratio of a budget, for every line of the database.
  • InterimCeilingBytes: While set, the database’s stop line (FAIL, writer pause). The owner budget keeps setting the alarm line, so a database above its budget warns until the remediation lands.
  • Remediation: The work items that own the excess, as the register records them.

Members

MemberKindSummary
CapacityDatabaseBudget(string, string, long, decimal, decimal, long?, IReadOnlyList<string>)constructorA service database’s byte budget, with its shrink-only interim ceiling.
AlarmpropertyThe alarm line as a ratio of a budget, for every line of the database.
BytespropertyThe byte budget of the database.
DatabasepropertyThe register’s name for the database.
FamilypropertyThe service family that owns the database.
InterimCeilingBytespropertyWhile set, the database’s stop line (FAIL, writer pause).
RemediationpropertyThe work items that own the excess, as the register records them.
StoppropertyThe stop line as a ratio of a budget, for every line of the database.

constructor CapacityDatabaseBudget(string, string, long, decimal, decimal, long?, IReadOnlyList<string>) #

public CapacityDatabaseBudget(string Database, string Family, long Bytes, decimal Alarm, decimal Stop, long? InterimCeilingBytes = null, IReadOnlyList<string>? Remediation = null)

A service database’s byte budget, with its shrink-only interim ceiling.

Parameters

  • Database: The register’s name for the database.
  • Family: The service family that owns the database.
  • Bytes: The byte budget of the database.
  • Alarm: The alarm line as a ratio of a budget, for every line of the database.
  • Stop: The stop line as a ratio of a budget, for every line of the database.
  • InterimCeilingBytes: While set, the database’s stop line (FAIL, writer pause). The owner budget keeps setting the alarm line, so a database above its budget warns until the remediation lands.
  • Remediation: The work items that own the excess, as the register records them.

property Alarm #

public decimal Alarm { get; init; }

The alarm line as a ratio of a budget, for every line of the database.

property Bytes #

public long Bytes { get; init; }

The byte budget of the database.

property Database #

public string Database { get; init; }

The register’s name for the database.

property Family #

public string Family { get; init; }

The service family that owns the database.

property InterimCeilingBytes #

public long? InterimCeilingBytes { get; init; }

While set, the database’s stop line (FAIL, writer pause). The owner budget keeps setting the alarm line, so a database above its budget warns until the remediation lands.

property Remediation #

public IReadOnlyList<string>? Remediation { get; init; }

The work items that own the excess, as the register records them.

property Stop #

public decimal Stop { get; init; }

The stop line as a ratio of a budget, for every line of the database.

record CapacityDuplicationBudget

public sealed record CapacityDuplicationBudget

One duplication line’s budget, read from the register entry’s budget.duplication. Alarm and stop come from the database ratios unless the line declares both AlarmAt and StopAt (a small count, such as a generation count, where 80% and 95% of the budget round to the same integer).

Parameters

  • Table: The register entry that declares the line; the receipt line’s subject.
  • Metric: One of CapacityEvaluator.DuplicationMetrics.
  • Budget: The budget.
  • AlarmAt: The declared alarm line; with StopAt, it replaces the database ratios.
  • StopAt: The declared stop line; with AlarmAt, it replaces the database ratios.

Members

MemberKindSummary
CapacityDuplicationBudget(string, string, long, long?, long?)constructorOne duplication line’s budget, read from the register entry’s budget.duplication.
AlarmAtpropertyThe declared alarm line; with StopAt, it replaces the database ratios.
BudgetpropertyThe budget.
MetricpropertyOne of CapacityEvaluator.DuplicationMetrics.
StopAtpropertyThe declared stop line; with AlarmAt, it replaces the database ratios.
TablepropertyThe register entry that declares the line; the receipt line’s subject.

constructor CapacityDuplicationBudget(string, string, long, long?, long?) #

public CapacityDuplicationBudget(string Table, string Metric, long Budget, long? AlarmAt = null, long? StopAt = null)

One duplication line’s budget, read from the register entry’s budget.duplication. Alarm and stop come from the database ratios unless the line declares both AlarmAt and StopAt (a small count, such as a generation count, where 80% and 95% of the budget round to the same integer).

Parameters

  • Table: The register entry that declares the line; the receipt line’s subject.
  • Metric: One of CapacityEvaluator.DuplicationMetrics.
  • Budget: The budget.
  • AlarmAt: The declared alarm line; with StopAt, it replaces the database ratios.
  • StopAt: The declared stop line; with AlarmAt, it replaces the database ratios.

property AlarmAt #

public long? AlarmAt { get; init; }

The declared alarm line; with StopAt, it replaces the database ratios.

property Budget #

public long Budget { get; init; }

The budget.

property Metric #

public string Metric { get; init; }

One of CapacityEvaluator.DuplicationMetrics.

property StopAt #

public long? StopAt { get; init; }

The declared stop line; with AlarmAt, it replaces the database ratios.

property Table #

public string Table { get; init; }

The register entry that declares the line; the receipt line’s subject.

struct CapacityDuplicationCount

public readonly struct CapacityDuplicationCount : IEquatable<CapacityDuplicationCount>

A count, and whether it stopped at the cap it was given.

Parameters

  • Value: The count.
  • Capped: Whether the count stopped at the cap.

Members

MemberKindSummary
CapacityDuplicationCount(long, bool)constructorA count, and whether it stopped at the cap it was given.
CappedpropertyWhether the count stopped at the cap.
ValuepropertyThe count.

constructor CapacityDuplicationCount(long, bool) #

public CapacityDuplicationCount(long Value, bool Capped)

A count, and whether it stopped at the cap it was given.

Parameters

  • Value: The count.
  • Capped: Whether the count stopped at the cap.

property Capped #

public bool Capped { get; init; }

Whether the count stopped at the cap.

property Value #

public long Value { get; init; }

The count.

record CapacityDuplicationMeasurement

public sealed record CapacityDuplicationMeasurement

One duplication line as measured. An absent line (no count, its index missing, or a count that ran past the statement timeout) is reported, not measured.

Parameters

  • Table: The register entry that declares the line.
  • Metric: The duplication metric.
  • Present: Whether the line was counted.
  • Measured: The count.
  • Capped: The count stopped at its cap, so Measured is a lower bound.
  • TimedOut: The count ran past the statement timeout and was rolled back; the line is absent.

Members

MemberKindSummary
CapacityDuplicationMeasurement(string, string, bool, long, bool, bool)constructorOne duplication line as measured.
CappedpropertyThe count stopped at its cap, so Measured is a lower bound.
MeasuredpropertyThe count.
MetricpropertyThe duplication metric.
PresentpropertyWhether the line was counted.
TablepropertyThe register entry that declares the line.
TimedOutpropertyThe count ran past the statement timeout and was rolled back; the line is absent.

constructor CapacityDuplicationMeasurement(string, string, bool, long, bool, bool) #

public CapacityDuplicationMeasurement(string Table, string Metric, bool Present, long Measured, bool Capped = false, bool TimedOut = false)

One duplication line as measured. An absent line (no count, its index missing, or a count that ran past the statement timeout) is reported, not measured.

Parameters

  • Table: The register entry that declares the line.
  • Metric: The duplication metric.
  • Present: Whether the line was counted.
  • Measured: The count.
  • Capped: The count stopped at its cap, so Measured is a lower bound.
  • TimedOut: The count ran past the statement timeout and was rolled back; the line is absent.

property Capped #

public bool Capped { get; init; }

The count stopped at its cap, so Measured is a lower bound.

property Measured #

public long Measured { get; init; }

The count.

property Metric #

public string Metric { get; init; }

The duplication metric.

property Present #

public bool Present { get; init; }

Whether the line was counted.

property Table #

public string Table { get; init; }

The register entry that declares the line.

property TimedOut #

public bool TimedOut { get; init; }

The count ran past the statement timeout and was rolled back; the line is absent.

class CapacityEvaluator

public static class CapacityEvaluator

Turns a measurement into a receipt; pure, so a health check and the probe agree.

Members

MemberKindSummary
BytesconstantThe size metric, in bytes.
DuplicationMetricsfieldThe duplication metrics a register entry may budget (budget.duplication).
EventRateWindowfieldThe trailing window an event rate divides.
EventsPerDayconstantThe event rate metric, in events per day.
GenerationsconstantGenerations present against the declared generation count.
GrowthPerDayconstantThe growth metric, in bytes per day.
MinimumGrowthSpanfieldGrowth is the byte delta to the previous receipt, normalised to a day.
OverrideRowsconstantTenant rows stored where the global row would otherwise serve.
RowsconstantThe row count metric.
SupersededCopiesconstantD2: rows of a table beyond one per identity (superseded copies a rule still retains or has not yet reclaimed).
TombstonesPastRuleconstantSuperseded identities whose tombstone is past the entry’s reclaim rule.
DuplicationThresholds(CapacityDuplicationBudget, CapacityDatabaseBudget)methodA duplication line’s alarm and stop lines: the declared pair when the register sets one, else the database’s ratios of the budget, like every other line.
Evaluate(CapacityBudgetSet, CapacityMeasurement, CapacityReceipt, DateTimeOffset)methodBuilds a receipt from a measurement: the bytes line of the database; for each budgeted table its bytes and rows lines, and a growth line when the previous receipt is at least CapacityEvaluator.MinimumGrowthSpanolder; and the event rate and duplication lines the measurement carries.
EventsPerDayFor(long)methodEvents per day from the rows written in the trailing CapacityEvaluator.EventRateWindow.

constant Bytes #

public const string Bytes = "bytes"

The size metric, in bytes.

field DuplicationMetrics #

public static readonly IReadOnlySet<string> DuplicationMetrics

The duplication metrics a register entry may budget (budget.duplication).

field EventRateWindow #

public static readonly TimeSpan EventRateWindow

The trailing window an event rate divides. The eventing pruners never reclaim a row younger than seven days (the outbox and inbox retention minimum), so every row written in this window is still in its ledger when the probe counts it.

constant EventsPerDay #

public const string EventsPerDay = "eventsPerDay"

The event rate metric, in events per day.

constant Generations #

public const string Generations = "generations"

Generations present against the declared generation count.

constant GrowthPerDay #

public const string GrowthPerDay = "growthPerDay"

The growth metric, in bytes per day.

field MinimumGrowthSpan #

public static readonly TimeSpan MinimumGrowthSpan

Growth is the byte delta to the previous receipt, normalised to a day. Two receipts closer than this say more about a single import than about a rate.

constant OverrideRows #

public const string OverrideRows = "overrideRows"

Tenant rows stored where the global row would otherwise serve.

constant Rows #

public const string Rows = "rows"

The row count metric.

constant SupersededCopies #

public const string SupersededCopies = "supersededCopies"

D2: rows of a table beyond one per identity (superseded copies a rule still retains or has not yet reclaimed).

constant TombstonesPastRule #

public const string TombstonesPastRule = "tombstonesPastRule"

Superseded identities whose tombstone is past the entry’s reclaim rule.

method DuplicationThresholds(CapacityDuplicationBudget, CapacityDatabaseBudget) #

public static (long AlarmAt, long StopAt) DuplicationThresholds(CapacityDuplicationBudget line, CapacityDatabaseBudget database)

A duplication line’s alarm and stop lines: the declared pair when the register sets one, else the database’s ratios of the budget, like every other line. The stop line is also the cap a bounded count stops at.

method Evaluate(CapacityBudgetSet, CapacityMeasurement, CapacityReceipt, DateTimeOffset) #

public static CapacityReceipt Evaluate(CapacityBudgetSet budgets, CapacityMeasurement measurement, CapacityReceipt? previous, DateTimeOffset probedAt)

Builds a receipt from a measurement: the bytes line of the database; for each budgeted table its bytes and rows lines, and a growth line when the previous receipt is at least CapacityEvaluator.MinimumGrowthSpanolder; and the event rate and duplication lines the measurement carries. A required subject that was not measured is listed as absent.

Parameters

  • budgets: The budgets.
  • measurement: The measurement.
  • previous: The previous receipt, for growth; none when not set.
  • probedAt: When the probe measured.

Returns

The receipt, not stored yet.

method EventsPerDayFor(long) #

public static long EventsPerDayFor(long windowRows)

Events per day from the rows written in the trailing CapacityEvaluator.EventRateWindow.

record CapacityEventLedgerMeasurement

public sealed record CapacityEventLedgerMeasurement

An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.EventRateWindow. An absent ledger is reported, not measured.

Parameters

  • Ledger: The ledger.
  • Present: Whether the ledger exists.
  • WindowRows: The rows written in the trailing window.

Members

MemberKindSummary
CapacityEventLedgerMeasurement(string, bool, long)constructorAn eventing ledger as measured: the rows written in the trailing CapacityEvaluator.EventRateWindow.
LedgerpropertyThe ledger.
PresentpropertyWhether the ledger exists.
WindowRowspropertyThe rows written in the trailing window.

constructor CapacityEventLedgerMeasurement(string, bool, long) #

public CapacityEventLedgerMeasurement(string Ledger, bool Present, long WindowRows)

An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.EventRateWindow. An absent ledger is reported, not measured.

Parameters

  • Ledger: The ledger.
  • Present: Whether the ledger exists.
  • WindowRows: The rows written in the trailing window.

property Ledger #

public string Ledger { get; init; }

The ledger.

property Present #

public bool Present { get; init; }

Whether the ledger exists.

property WindowRows #

public long WindowRows { get; init; }

The rows written in the trailing window.

record CapacityEventRateBudget

public sealed record CapacityEventRateBudget

An eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.EventRateWindowdivided by its days. A sustained breach is the signal of a new churn source (an identity migration, a re-normalization storm, a writer that re-emits unchanged state). The line warns and fails; it never pauses writers.

Parameters

  • Ledger: The ledger: eventing.outbox or eventing.inbox.
  • PerDay: The events-per-day budget.
  • InterimCeilingPerDay: While set, the ledger’s stop line: the shrink-only ceiling over a window that still holds a known burst. The budget keeps the alarm line.

Members

MemberKindSummary
CapacityEventRateBudget(string, long, long?)constructorAn eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.EventRateWindowdivided by its days.
InterimCeilingPerDaypropertyWhile set, the ledger’s stop line: the shrink-only ceiling over a window that still holds a known burst.
LedgerpropertyThe ledger: eventing.outbox or eventing.inbox.
PerDaypropertyThe events-per-day budget.

constructor CapacityEventRateBudget(string, long, long?) #

public CapacityEventRateBudget(string Ledger, long PerDay, long? InterimCeilingPerDay = null)

An eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.EventRateWindowdivided by its days. A sustained breach is the signal of a new churn source (an identity migration, a re-normalization storm, a writer that re-emits unchanged state). The line warns and fails; it never pauses writers.

Parameters

  • Ledger: The ledger: eventing.outbox or eventing.inbox.
  • PerDay: The events-per-day budget.
  • InterimCeilingPerDay: While set, the ledger’s stop line: the shrink-only ceiling over a window that still holds a known burst. The budget keeps the alarm line.

property InterimCeilingPerDay #

public long? InterimCeilingPerDay { get; init; }

While set, the ledger’s stop line: the shrink-only ceiling over a window that still holds a known burst. The budget keeps the alarm line.

property Ledger #

public string Ledger { get; init; }

The ledger: eventing.outbox or eventing.inbox.

property PerDay #

public long PerDay { get; init; }

The events-per-day budget.

record CapacityLine

public sealed record CapacityLine

One measured value against its lines. Reaching the alarm line warns; reaching the stop line fails. A metric with no stop line (growth per day) can only warn.

Parameters

  • Subject: CapacityLine.DatabaseSubject, a qualified table name or an eventing ledger.
  • Metric: bytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.DuplicationMetrics).
  • Measured: The measured value.
  • Budget: The budget.
  • AlarmAt: The alarm line.
  • StopAt: The stop line; none for a metric that can only warn.
  • Interim: The stop line is an interim ceiling or a pinned measurement, not the owner budget.
  • WindowRows: For eventsPerDay: the rows written in the trailing window the rate divides.
  • Capped: For a duplication line: the count stopped at the stop line, so Measured is a lower bound.

Members

MemberKindSummary
CapacityLine(string, string, long, long, long, long?, bool, long?, bool)constructorOne measured value against its lines.
DatabaseSubjectconstantThe subject of the database line.
AlarmAtpropertyThe alarm line.
BudgetpropertyThe budget.
CappedpropertyFor a duplication line: the count stopped at the stop line, so Measured is a lower bound.
InterimpropertyThe stop line is an interim ceiling or a pinned measurement, not the owner budget.
MeasuredpropertyThe measured value.
Metricpropertybytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.DuplicationMetrics).
StopAtpropertyThe stop line; none for a metric that can only warn.
SubjectpropertyCapacityLine.DatabaseSubject, a qualified table name or an eventing ledger.
VerdictpropertyCapacityVerdict.Failat or above the stop line, CapacityVerdict.Warnat or above the alarm line, else CapacityVerdict.Pass.
WindowRowspropertyFor eventsPerDay: the rows written in the trailing window the rate divides.

constructor CapacityLine(string, string, long, long, long, long?, bool, long?, bool) #

public CapacityLine(string Subject, string Metric, long Measured, long Budget, long AlarmAt, long? StopAt, bool Interim, long? WindowRows = null, bool Capped = false)

One measured value against its lines. Reaching the alarm line warns; reaching the stop line fails. A metric with no stop line (growth per day) can only warn.

Parameters

  • Subject: CapacityLine.DatabaseSubject, a qualified table name or an eventing ledger.
  • Metric: bytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.DuplicationMetrics).
  • Measured: The measured value.
  • Budget: The budget.
  • AlarmAt: The alarm line.
  • StopAt: The stop line; none for a metric that can only warn.
  • Interim: The stop line is an interim ceiling or a pinned measurement, not the owner budget.
  • WindowRows: For eventsPerDay: the rows written in the trailing window the rate divides.
  • Capped: For a duplication line: the count stopped at the stop line, so Measured is a lower bound.

constant DatabaseSubject #

public const string DatabaseSubject = "database"

The subject of the database line.

property AlarmAt #

public long AlarmAt { get; init; }

The alarm line.

property Budget #

public long Budget { get; init; }

The budget.

property Capped #

public bool Capped { get; init; }

For a duplication line: the count stopped at the stop line, so Measured is a lower bound.

property Interim #

public bool Interim { get; init; }

The stop line is an interim ceiling or a pinned measurement, not the owner budget.

property Measured #

public long Measured { get; init; }

The measured value.

property Metric #

public string Metric { get; init; }

bytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.DuplicationMetrics).

property StopAt #

public long? StopAt { get; init; }

The stop line; none for a metric that can only warn.

property Subject #

public string Subject { get; init; }

CapacityLine.DatabaseSubject, a qualified table name or an eventing ledger.

property Verdict #

public CapacityVerdict Verdict { get; }

CapacityVerdict.Failat or above the stop line, CapacityVerdict.Warnat or above the alarm line, else CapacityVerdict.Pass.

property WindowRows #

public long? WindowRows { get; init; }

For eventsPerDay: the rows written in the trailing window the rate divides.

record CapacityMeasurement

public sealed record CapacityMeasurement

The host database and its registered tables at one instant.

Parameters

  • Database: The physical database the connection reached (current_database()).
  • DatabaseBytes: The database size, in bytes (pg_database_size).
  • Tables: The registered tables as measured.
  • EventLedgers: The eventing ledgers’ trailing-window counts; null when the caller measured no event rate.
  • Duplication: The duplication lines’ counts; null when the caller measured none.

Members

MemberKindSummary
CapacityMeasurement(string, long, IReadOnlyList<CapacityTableMeasurement>, IReadOnlyList<CapacityEventLedgerMeasurement>, IReadOnlyList<CapacityDuplicationMeasurement>)constructorThe host database and its registered tables at one instant.
DatabasepropertyThe physical database the connection reached (current_database()).
DatabaseBytespropertyThe database size, in bytes (pg_database_size).
DuplicationpropertyThe duplication lines’ counts; null when the caller measured none.
EventLedgerspropertyThe eventing ledgers’ trailing-window counts; null when the caller measured no event rate.
TablespropertyThe registered tables as measured.

constructor CapacityMeasurement(string, long, IReadOnlyList<CapacityTableMeasurement>, IReadOnlyList<CapacityEventLedgerMeasurement>, IReadOnlyList<CapacityDuplicationMeasurement>) #

public CapacityMeasurement(string Database, long DatabaseBytes, IReadOnlyList<CapacityTableMeasurement> Tables, IReadOnlyList<CapacityEventLedgerMeasurement>? EventLedgers = null, IReadOnlyList<CapacityDuplicationMeasurement>? Duplication = null)

The host database and its registered tables at one instant.

Parameters

  • Database: The physical database the connection reached (current_database()).
  • DatabaseBytes: The database size, in bytes (pg_database_size).
  • Tables: The registered tables as measured.
  • EventLedgers: The eventing ledgers’ trailing-window counts; null when the caller measured no event rate.
  • Duplication: The duplication lines’ counts; null when the caller measured none.

property Database #

public string Database { get; init; }

The physical database the connection reached (current_database()).

property DatabaseBytes #

public long DatabaseBytes { get; init; }

The database size, in bytes (pg_database_size).

property Duplication #

public IReadOnlyList<CapacityDuplicationMeasurement>? Duplication { get; init; }

The duplication lines’ counts; null when the caller measured none.

property EventLedgers #

public IReadOnlyList<CapacityEventLedgerMeasurement>? EventLedgers { get; init; }

The eventing ledgers’ trailing-window counts; null when the caller measured no event rate.

property Tables #

public IReadOnlyList<CapacityTableMeasurement> Tables { get; init; }

The registered tables as measured.

enum CapacityPauseCause

public enum CapacityPauseCause

Why a writer gate is closed.

ValueDescription
None = 0The gate is open.
StopLine = 1The newest receipt shows the database at or above its stop line.
StaleReceipt = 2The newest receipt is older than CapacityWriterGateOptions.StaleAfter.
NoReceipt = 3No receipt exists once CapacityWriterGateOptions.UnmeasuredGracehas passed.

record CapacityReceipt

public sealed record CapacityReceipt

One probe run, as written to <schema>.capacity_probe_receipt.

Parameters

  • ReceiptId: The id the store assigned; none before the receipt is stored.
  • BudgetDatabase: The register’s name for the database (the budget key).
  • PhysicalDatabase: The database the probe actually measured.
  • ProbedAt: When the probe measured.
  • RegisterSha256: The SHA-256 of the register the budgets came from.
  • Lines: The measured lines.
  • AbsentTables: The required subjects that were not measured: tables, ledgers and duplication lines.
  • Remediation: The work items the register names as owning the database’s excess.

Members

MemberKindSummary
CapacityReceipt(long?, string, string, DateTimeOffset, string, IReadOnlyList<CapacityLine>, IReadOnlyList<string>, IReadOnlyList<string>)constructorOne probe run, as written to <schema>.capacity_probe_receipt.
AbsentTablespropertyThe required subjects that were not measured: tables, ledgers and duplication lines.
BudgetDatabasepropertyThe register’s name for the database (the budget key).
DatabaseLinepropertyThe bytes line of the database.
DuplicationLinespropertyThe duplication lines, ordered by table and metric.
EventRateLinespropertyThe eventing ledgers’ events-per-day lines, ordered by ledger.
LinespropertyThe measured lines.
PhysicalDatabasepropertyThe database the probe actually measured.
ProbedAtpropertyWhen the probe measured.
ReceiptIdpropertyThe id the store assigned; none before the receipt is stored.
RegisterSha256propertyThe SHA-256 of the register the budgets came from.
RemediationpropertyThe work items the register names as owning the database’s excess.
RemediationTextpropertyThe remediation rows by name, or the statement that none owns the excess.
SummarypropertyThe one-line operator summary the probe logs and stores.
VerdictpropertyCapacityVerdict.Failwhen a required subject was not measured; otherwise the worst line verdict, and CapacityVerdict.Passwithout lines.
WriterPausepropertyThe database is at or above its stop line, so writer admission must pause.

constructor CapacityReceipt(long?, string, string, DateTimeOffset, string, IReadOnlyList<CapacityLine>, IReadOnlyList<string>, IReadOnlyList<string>) #

public CapacityReceipt(long? ReceiptId, string BudgetDatabase, string PhysicalDatabase, DateTimeOffset ProbedAt, string RegisterSha256, IReadOnlyList<CapacityLine> Lines, IReadOnlyList<string> AbsentTables, IReadOnlyList<string>? Remediation = null)

One probe run, as written to <schema>.capacity_probe_receipt.

Parameters

  • ReceiptId: The id the store assigned; none before the receipt is stored.
  • BudgetDatabase: The register’s name for the database (the budget key).
  • PhysicalDatabase: The database the probe actually measured.
  • ProbedAt: When the probe measured.
  • RegisterSha256: The SHA-256 of the register the budgets came from.
  • Lines: The measured lines.
  • AbsentTables: The required subjects that were not measured: tables, ledgers and duplication lines.
  • Remediation: The work items the register names as owning the database’s excess.

property AbsentTables #

public IReadOnlyList<string> AbsentTables { get; init; }

The required subjects that were not measured: tables, ledgers and duplication lines.

property BudgetDatabase #

public string BudgetDatabase { get; init; }

The register’s name for the database (the budget key).

property DatabaseLine #

public CapacityLine DatabaseLine { get; }

The bytes line of the database.

property DuplicationLines #

public IReadOnlyList<CapacityLine> DuplicationLines { get; }

The duplication lines, ordered by table and metric.

property EventRateLines #

public IReadOnlyList<CapacityLine> EventRateLines { get; }

The eventing ledgers’ events-per-day lines, ordered by ledger.

property Lines #

public IReadOnlyList<CapacityLine> Lines { get; init; }

The measured lines.

property PhysicalDatabase #

public string PhysicalDatabase { get; init; }

The database the probe actually measured.

property ProbedAt #

public DateTimeOffset ProbedAt { get; init; }

When the probe measured.

property ReceiptId #

public long? ReceiptId { get; init; }

The id the store assigned; none before the receipt is stored.

property RegisterSha256 #

public string RegisterSha256 { get; init; }

The SHA-256 of the register the budgets came from.

property Remediation #

public IReadOnlyList<string>? Remediation { get; init; }

The work items the register names as owning the database’s excess.

property RemediationText #

public string RemediationText { get; }

The remediation rows by name, or the statement that none owns the excess.

property Summary #

public string Summary { get; }

The one-line operator summary the probe logs and stores.

property Verdict #

public CapacityVerdict Verdict { get; }

CapacityVerdict.Failwhen a required subject was not measured; otherwise the worst line verdict, and CapacityVerdict.Passwithout lines.

property WriterPause #

public bool WriterPause { get; }

The database is at or above its stop line, so writer admission must pause. This receipt records that decision; it does not observe whether a caller enforced it. Only database bytes require a writer pause; table/event-rate stop lines fail the capacity health check.

class CapacityReceiptAssessment

public static class CapacityReceiptAssessment

Judges the newest receipt. A missing receipt and a receipt older than CapacityReceiptAssessment.MaximumReceiptAgeboth FAIL: a dead probe is a failure, not “no data”. Its age is measured on the caller’s clock, so the verdict turns red on its own when the probe stops, which is the one property a monitor without a freshness rule lacks.

Members

MemberKindSummary
MaximumReceiptAgefieldThe age after which a receipt fails: 36 hours.
Assess(string, CapacityReceipt, DateTimeOffset)methodJudges the newest receipt of a database: CapacityVerdict.Failwithout a receipt or with one older than CapacityReceiptAssessment.MaximumReceiptAge; otherwise the receipt’s verdict, with the message and the evidence an operator sees.

field MaximumReceiptAge #

public static readonly TimeSpan MaximumReceiptAge

The age after which a receipt fails: 36 hours.

method Assess(string, CapacityReceipt, DateTimeOffset) #

public static CapacityAssessment Assess(string database, CapacityReceipt? newest, DateTimeOffset now)

Judges the newest receipt of a database: CapacityVerdict.Failwithout a receipt or with one older than CapacityReceiptAssessment.MaximumReceiptAge; otherwise the receipt’s verdict, with the message and the evidence an operator sees.

Parameters

  • database: The register’s name for the database.
  • newest: The newest receipt; none when none exists.
  • now: The current time.

Returns

The assessment.

class CapacityReceiptWriterGate

public sealed class CapacityReceiptWriterGate : ICapacityWriterGate

Closes while the newest receipt shows the database at or above its stop line, while the newest receipt is older than CapacityWriterGateOptions.StaleAfter, and while no receipt exists once CapacityWriterGateOptions.UnmeasuredGraceafter the gate started has passed. A stop-line receipt is honoured whatever its age: resuming writes on an unmeasured, last-known-full database is the failure this prevents. A missing receipt table reads as no receipt, so a writer deployed before the host that runs the probe pauses with that reason once the grace has passed, and resumes on the first receipt below the stop line. One log line per transition (opened, closed, or closed for a different cause), never one per evaluation.

Members

MemberKindSummary
CapacityReceiptWriterGate(ICapacityReceiptStore, string, ILogger, TimeProvider, CapacityWriterGateOptions)constructorCreates the gate; the grace for a missing receipt counts from this moment.
EvaluateAsync(CancellationToken)methodReads the newest receipt and decides.

constructor CapacityReceiptWriterGate(ICapacityReceiptStore, string, ILogger, TimeProvider, CapacityWriterGateOptions) #

public CapacityReceiptWriterGate(ICapacityReceiptStore store, string writer, ILogger logger, TimeProvider? clock = null, CapacityWriterGateOptions? options = null)

Creates the gate; the grace for a missing receipt counts from this moment.

Parameters

  • store: The receipt store of the database.
  • writer: The writers this gate holds, as the transition log names them.
  • logger: The logger.
  • clock: The clock; the system clock when not set.
  • options: The gate options; the defaults when not set.

Exceptions

  • ArgumentNullException: The store or the logger is null.
  • ArgumentException: The writer is empty, the staleness bound is not positive or the grace is negative.

method EvaluateAsync(CancellationToken) #

public Task<CapacityWriterGateDecision> EvaluateAsync(CancellationToken cancellationToken)

Reads the newest receipt and decides. Writers pause when the database is at or above its stop line, when the newest receipt is older than StaleAfter, or when no receipt exists once UnmeasuredGrace has passed since the gate was created. A change of decision is logged.

Parameters

  • cancellationToken: Cancels the operation.

Returns

The decision.

record CapacityTableBudget

public sealed record CapacityTableBudget

One registered table’s budget, read from the data-identity register.

Parameters

  • Table: The qualified table name.
  • Bytes: The byte budget.
  • Rows: The row budget.
  • GrowthPerDay: The growth budget, in bytes per day; it is the alarm line of the growth line, which has no stop line.
  • InterimBytes: The stop line a pin that covers budget holds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plus CapacityBudgetRegister.InterimHeadroom. Applies while InterimUntil (the pin’s sunset) has not passed, so a remediation that stalls past its sunset turns the table red with no code change.
  • InterimRows: The row stop line the pin holds the table at, as for InterimBytes.
  • InterimUntil: The pin’s sunset: the interim stop lines apply through this day.

Members

MemberKindSummary
CapacityTableBudget(string, long, long, long, long?, long?, DateOnly?)constructorOne registered table’s budget, read from the data-identity register.
BytespropertyThe byte budget.
GrowthPerDaypropertyThe growth budget, in bytes per day; it is the alarm line of the growth line, which has no stop line.
InterimBytespropertyThe stop line a pin that covers budget holds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plus CapacityBudgetRegister.InterimHeadroom.
InterimRowspropertyThe row stop line the pin holds the table at, as for InterimBytes.
InterimUntilpropertyThe pin’s sunset: the interim stop lines apply through this day.
RowspropertyThe row budget.
TablepropertyThe qualified table name.

constructor CapacityTableBudget(string, long, long, long, long?, long?, DateOnly?) #

public CapacityTableBudget(string Table, long Bytes, long Rows, long GrowthPerDay, long? InterimBytes = null, long? InterimRows = null, DateOnly? InterimUntil = null)

One registered table’s budget, read from the data-identity register.

Parameters

  • Table: The qualified table name.
  • Bytes: The byte budget.
  • Rows: The row budget.
  • GrowthPerDay: The growth budget, in bytes per day; it is the alarm line of the growth line, which has no stop line.
  • InterimBytes: The stop line a pin that covers budget holds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plus CapacityBudgetRegister.InterimHeadroom. Applies while InterimUntil (the pin’s sunset) has not passed, so a remediation that stalls past its sunset turns the table red with no code change.
  • InterimRows: The row stop line the pin holds the table at, as for InterimBytes.
  • InterimUntil: The pin’s sunset: the interim stop lines apply through this day.

property Bytes #

public long Bytes { get; init; }

The byte budget.

property GrowthPerDay #

public long GrowthPerDay { get; init; }

The growth budget, in bytes per day; it is the alarm line of the growth line, which has no stop line.

property InterimBytes #

public long? InterimBytes { get; init; }

The stop line a pin that covers budget holds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plus CapacityBudgetRegister.InterimHeadroom. Applies while InterimUntil (the pin’s sunset) has not passed, so a remediation that stalls past its sunset turns the table red with no code change.

property InterimRows #

public long? InterimRows { get; init; }

The row stop line the pin holds the table at, as for InterimBytes.

property InterimUntil #

public DateOnly? InterimUntil { get; init; }

The pin’s sunset: the interim stop lines apply through this day.

property Rows #

public long Rows { get; init; }

The row budget.

property Table #

public string Table { get; init; }

The qualified table name.

record CapacityTableMeasurement

public sealed record CapacityTableMeasurement

One registered table as measured. An absent table is reported, not measured.

Parameters

  • Table: The qualified table name.
  • Present: Whether the table exists.
  • Bytes: The total size with indexes (pg_total_relation_size); a partitioned table sums its partitions.
  • Rows: The estimated row count (pg_class.reltuples).

Members

MemberKindSummary
CapacityTableMeasurement(string, bool, long, long)constructorOne registered table as measured.
BytespropertyThe total size with indexes (pg_total_relation_size); a partitioned table sums its partitions.
PresentpropertyWhether the table exists.
RowspropertyThe estimated row count (pg_class.reltuples).
TablepropertyThe qualified table name.

constructor CapacityTableMeasurement(string, bool, long, long) #

public CapacityTableMeasurement(string Table, bool Present, long Bytes, long Rows)

One registered table as measured. An absent table is reported, not measured.

Parameters

  • Table: The qualified table name.
  • Present: Whether the table exists.
  • Bytes: The total size with indexes (pg_total_relation_size); a partitioned table sums its partitions.
  • Rows: The estimated row count (pg_class.reltuples).

property Bytes #

public long Bytes { get; init; }

The total size with indexes (pg_total_relation_size); a partitioned table sums its partitions.

property Present #

public bool Present { get; init; }

Whether the table exists.

property Rows #

public long Rows { get; init; }

The estimated row count (pg_class.reltuples).

property Table #

public string Table { get; init; }

The qualified table name.

enum CapacityVerdict

public enum CapacityVerdict

The verdict of a capacity line or receipt.

ValueDescription
Pass = 0Below the alarm line.
Warn = 1At or above the alarm line, below the stop line.
Fail = 2At or above the stop line, or a required subject was not measured.

record CapacityWriterGateDecision

public sealed record CapacityWriterGateDecision

Whether a writer may start a cycle, and if not, the reason an operator reads.

Parameters

  • Paused: Whether writers must pause.
  • Reason: Why they pause; none when the gate is open.
  • Cause: The cause of the pause.

Members

MemberKindSummary
CapacityWriterGateDecision(bool, string, CapacityPauseCause)constructorWhether a writer may start a cycle, and if not, the reason an operator reads.
OpenfieldThe open gate: writers write.
CausepropertyThe cause of the pause.
PausedpropertyWhether writers must pause.
ReasonpropertyWhy they pause; none when the gate is open.

constructor CapacityWriterGateDecision(bool, string, CapacityPauseCause) #

public CapacityWriterGateDecision(bool Paused, string? Reason, CapacityPauseCause Cause = None)

Whether a writer may start a cycle, and if not, the reason an operator reads.

Parameters

  • Paused: Whether writers must pause.
  • Reason: Why they pause; none when the gate is open.
  • Cause: The cause of the pause.

field Open #

public static readonly CapacityWriterGateDecision Open

The open gate: writers write.

property Cause #

public CapacityPauseCause Cause { get; init; }

The cause of the pause.

property Paused #

public bool Paused { get; init; }

Whether writers must pause.

property Reason #

public string? Reason { get; init; }

Why they pause; none when the gate is open.

class CapacityWriterGateOptions

public sealed class CapacityWriterGateOptions

Settings of the capacity writer gate (Capacity:WriterGate).

Members

MemberKindSummary
CapacityWriterGateOptions()constructorCreates an instance of CapacityWriterGateOptions.
SectionNameconstantThe configuration section the options bind from: Capacity:WriterGate.
StaleAfterpropertyA newest receipt older than this closes the gate (“capacity unmeasured”).
UnmeasuredGracepropertyHow long after the gate starts a missing receipt leaves writers running: the probe’s startup delay (1 minute), one pass (a few catalog statements, each bounded at 60 seconds) and one retry after a failed first pass (15 minutes).
IsValid()methodWhether the options are usable: CapacityWriterGateOptions.StaleAfterpositive and CapacityWriterGateOptions.UnmeasuredGracenot negative.

constructor CapacityWriterGateOptions() #

public CapacityWriterGateOptions()

Creates an instance of CapacityWriterGateOptions.

constant SectionName #

public const string SectionName = "Capacity:WriterGate"

The configuration section the options bind from: Capacity:WriterGate.

property StaleAfter #

public TimeSpan StaleAfter { get; set; }

A newest receipt older than this closes the gate (“capacity unmeasured”). The probe writes a receipt every 24 h plus up to 1 h of jitter and retries a failed pass after 15 minutes. 48 h is two probe intervals: one missed or retried pass never pauses writers, and a dead probe cannot leave writers running unmeasured into a third day.

property UnmeasuredGrace #

public TimeSpan UnmeasuredGrace { get; set; }

How long after the gate starts a missing receipt leaves writers running: the probe’s startup delay (1 minute), one pass (a few catalog statements, each bounded at 60 seconds) and one retry after a failed first pass (15 minutes). After it, a missing receipt closes the gate.

method IsValid() #

public bool IsValid()

Whether the options are usable: CapacityWriterGateOptions.StaleAfterpositive and CapacityWriterGateOptions.UnmeasuredGracenot negative.

Returns

true when the options are usable.

class CapacityWriterGateServiceCollectionExtensions

public static class CapacityWriterGateServiceCollectionExtensions

Registers the capacity writer gate.

Members

MemberKindSummary
AddCapacityWriterGate(IServiceCollection, IConfiguration, string, Func<IServiceProvider, ICapacityReceiptStore>)extension methodRegisters the host’s writer gate over its database’s receipt store, with CapacityWriterGateOptionsbound from CapacityWriterGateOptions.SectionName.

extension method AddCapacityWriterGate(IServiceCollection, IConfiguration, string, Func<IServiceProvider, ICapacityReceiptStore>) #

public static IServiceCollection AddCapacityWriterGate(this IServiceCollection services, IConfiguration configuration, string writer, Func<IServiceProvider, ICapacityReceiptStore> receipts)

Registers the host’s writer gate over its database’s receipt store, with CapacityWriterGateOptionsbound from CapacityWriterGateOptions.SectionName. One gate per host: a service writes only its own database, so every gated writer in the host shares it and the transition log is written once.

Parameters

  • writer: The writers the gate holds, as the transition log names them.
  • receipts: The receipt store of the database those writers fill.

interface ICapacityDuplicationLine

public interface ICapacityDuplicationLine

The owning host’s count for one duplication line. A count is index-backed and bounded: it walks ICapacityDuplicationLine.RequiredIndex, and a count whose cost grows with its value stops at the cap (the line’s stop line, the smallest value that fails), so a 100 GB table and a runaway backlog cost what the stop line costs. It runs inside the probe’s READ ONLY transaction (PostgresCapacityDuplicationProbe.ApplyPostureAsync(NpgsqlConnection, NpgsqlTransaction, TimeSpan, CancellationToken)), with commands from the CapacityCountSessionit is handed, and must write nothing; it may set transaction-local settings (a tenant context) with set_config(..., true).

Members

MemberKindSummary
MetricpropertyOne of CapacityEvaluator.DuplicationMetrics.
RequiredIndexpropertyThe index the count walks, schema-qualified.
TablepropertyThe register entry that declares the line.
CountAsync(CapacityCountSession, long, DateTimeOffset, CancellationToken)methodCounts the line, stopping at the cap.

property Metric #

string Metric { get; }

One of CapacityEvaluator.DuplicationMetrics.

property RequiredIndex #

string RequiredIndex { get; }

The index the count walks, schema-qualified. While it does not exist the line is absent, never a scan.

property Table #

string Table { get; }

The register entry that declares the line.

method CountAsync(CapacityCountSession, long, DateTimeOffset, CancellationToken) #

Task<CapacityDuplicationCount> CountAsync(CapacityCountSession session, long cap, DateTimeOffset probedAt, CancellationToken cancellationToken)

Counts the line, stopping at the cap.

Parameters

  • session: The probe’s READ ONLY transaction.
  • cap: The cap: the line’s stop line.
  • probedAt: When the probe measures.
  • cancellationToken: Cancels the operation.

Returns

The count, and whether it stopped at the cap.

interface ICapacityReceiptStore

public interface ICapacityReceiptStore

Reads and writes one host database’s capacity receipts.

Members

MemberKindSummary
BudgetDatabasepropertyThe register’s name for the database these receipts describe.
AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken)methodAppends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction.
ReadNewestAsync(CancellationToken)methodThe newest receipt, or null when none exists (or the receipt table is not there yet).

property BudgetDatabase #

string BudgetDatabase { get; }

The register’s name for the database these receipts describe.

method AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken) #

Task<long> AppendAsync(CapacityReceipt receipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>? beforeCommit, CancellationToken cancellationToken)

Appends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction. beforeCommit runs inside it (the probe’s lease fence).

method ReadNewestAsync(CancellationToken) #

Task<CapacityReceipt?> ReadNewestAsync(CancellationToken cancellationToken)

The newest receipt, or null when none exists (or the receipt table is not there yet).

interface ICapacityWriterGate

public interface ICapacityWriterGate

Consulted by a writer before a write cycle. Above the stop line, or while capacity is unmeasured, the writer skips the cycle with an operator-visible reason; it never crashes and never fills the volume.

Members

MemberKindSummary
EvaluateAsync(CancellationToken)methodDecides whether writers must pause.

method EvaluateAsync(CancellationToken) #

Task<CapacityWriterGateDecision> EvaluateAsync(CancellationToken cancellationToken)

Decides whether writers must pause.

Parameters

  • cancellationToken: Cancels the operation.

Returns

The decision.

class PostgresCapacityDuplicationProbe

public static class PostgresCapacityDuplicationProbe

Measures the declared duplication lines with the owning host’s counts.

Members

MemberKindSummary
ApplyPostureAsync(NpgsqlConnection, NpgsqlTransaction, TimeSpan, CancellationToken)methodThe posture every count runs under, and the one a plan test reproduces: READ ONLY, the statement timeout, no parallel workers (a parallel hash lives in the container’s small /dev/shm) and no sequential scan where an index can serve (the count walks its index, never the table’s heap).
MeasureAsync(NpgsqlDataSource, IReadOnlyCollection<CapacityDuplicationBudget>, IEnumerable<ICapacityDuplicationLine>, CapacityDatabaseBudget, DateTimeOffset, TimeSpan, CancellationToken)methodOne READ ONLY transaction, rolled back.

method ApplyPostureAsync(NpgsqlConnection, NpgsqlTransaction, TimeSpan, CancellationToken) #

public static Task ApplyPostureAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, TimeSpan statementTimeout, CancellationToken cancellationToken)

The posture every count runs under, and the one a plan test reproduces: READ ONLY, the statement timeout, no parallel workers (a parallel hash lives in the container’s small /dev/shm) and no sequential scan where an index can serve (the count walks its index, never the table’s heap). Call it first in a fresh transaction.

method MeasureAsync(NpgsqlDataSource, IReadOnlyCollection<CapacityDuplicationBudget>, IEnumerable<ICapacityDuplicationLine>, CapacityDatabaseBudget, DateTimeOffset, TimeSpan, CancellationToken) #

public static Task<IReadOnlyList<CapacityDuplicationMeasurement>> MeasureAsync(NpgsqlDataSource dataSource, IReadOnlyCollection<CapacityDuplicationBudget> declared, IEnumerable<ICapacityDuplicationLine> lines, CapacityDatabaseBudget database, DateTimeOffset probedAt, TimeSpan statementTimeout, CancellationToken cancellationToken)

One READ ONLY transaction, rolled back. A declared line with no count, or whose required index does not exist, is absent. Each count runs under its own savepoint: one that runs past the statement timeout is rolled back and reported absent (CapacityDuplicationMeasurement.TimedOut), so a slow count never costs the receipt its database and table lines. The count’s commands come from a CapacityCountSession, so the server’s statement timeout ends a slow count before the client’s does. Two counts for one line are a composition error.

class PostgresCapacityProbe

public static class PostgresCapacityProbe

Catalog-only measurement: pg_total_relation_size and pg_class.reltuples (a partitioned table sums its partition tree, because its own size is zero and pg_partition_tree lists nothing for a plain table), plus pg_database_size. No statement reads a table’s rows, so a 100 GB table costs the same as an empty one. Runs inside one READ ONLY transaction with a statement timeout and rolls back.

Members

MemberKindSummary
DefaultStatementTimeoutfieldThe default statement timeout of a measurement: 60 seconds.
MeasureAsync(NpgsqlDataSource, IReadOnlyCollection<string>, TimeSpan, CancellationToken)methodMeasures the database and the named tables in one READ ONLY transaction under a statement timeout.

field DefaultStatementTimeout #

public static readonly TimeSpan DefaultStatementTimeout

The default statement timeout of a measurement: 60 seconds.

method MeasureAsync(NpgsqlDataSource, IReadOnlyCollection<string>, TimeSpan, CancellationToken) #

public static Task<CapacityMeasurement> MeasureAsync(NpgsqlDataSource dataSource, IReadOnlyCollection<string> tables, TimeSpan statementTimeout, CancellationToken cancellationToken)

Measures the database and the named tables in one READ ONLY transaction under a statement timeout.

Parameters

  • dataSource: The data source of the host database.
  • tables: The qualified names of the tables to measure.
  • statementTimeout: The statement timeout; positive.
  • cancellationToken: Cancels the operation.

Returns

The measurement; a table that does not exist is measured as absent.

Exceptions

  • ArgumentOutOfRangeException: The timeout is not positive.

class PostgresCapacityReceiptStore

public sealed class PostgresCapacityReceiptStore : ICapacityReceiptStore

<schema>.capacity_probe_receipt in the host’s own database. Each owning family creates the table and its prune_capacity_probe_receipts function in its own forward-only migration; the retained count is that function’s default, so it has one source.

Members

MemberKindSummary
PostgresCapacityReceiptStore(NpgsqlDataSource, string, string)constructorCreates the store for a schema of the host database.
PruneFunctionNameconstantThe function that reclaims the oldest receipts.
TableNameconstantThe receipt table.
BudgetDatabasepropertyThe register’s name for the database these receipts describe.
AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken)methodAppends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction.
ReadNewestAsync(CancellationToken)methodThe newest receipt, or null when none exists (or the receipt table is not there yet).

constructor PostgresCapacityReceiptStore(NpgsqlDataSource, string, string) #

public PostgresCapacityReceiptStore(NpgsqlDataSource dataSource, string schema, string budgetDatabase)

Creates the store for a schema of the host database.

Parameters

  • dataSource: The data source of the host database.
  • schema: The schema of the receipt table; a plain lower-case identifier.
  • budgetDatabase: The register’s name for the database.

Exceptions

  • ArgumentException: The schema is not a plain lower-case identifier, or the budget database is empty.

constant PruneFunctionName #

public const string PruneFunctionName = "prune_capacity_probe_receipts"

The function that reclaims the oldest receipts.

constant TableName #

public const string TableName = "capacity_probe_receipt"

The receipt table.

property BudgetDatabase #

public string BudgetDatabase { get; }

The register’s name for the database these receipts describe.

method AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken) #

public Task<long> AppendAsync(CapacityReceipt receipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>? beforeCommit, CancellationToken cancellationToken)

Appends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction. beforeCommit runs inside it (the probe’s lease fence).

method ReadNewestAsync(CancellationToken) #

public Task<CapacityReceipt?> ReadNewestAsync(CancellationToken cancellationToken)

The newest receipt, or null when none exists (or the receipt table is not there yet).

namespace StellaOps.Infrastructure.Postgres.Connections

TypeKindDescription
DataSourceBaseclassBase class for module-specific PostgreSQL data sources.
PostgresConnectionStringPolicyclassApplies StellaOps runtime defaults to PostgreSQL connection strings.

class DataSourceBase

public abstract class DataSourceBase : IAsyncDisposable

Base class for module-specific PostgreSQL data sources. Manages connection pooling, tenant context configuration, and session settings.

Remarks

Each module should derive from this class to create a strongly-typed data source. Example: OrdersDataSource : DataSourceBase

Members

MemberKindSummary
DataSourceBase(PostgresOptions, ILogger)constructorCreates a new data source with the specified options.
CommandTimeoutSecondspropertyCommand timeout in seconds from options.
ModuleNamepropertyModule name for logging and metrics.
OptionspropertyPostgreSQL options for this data source.
SchemaNamepropertySchema name for this module’s tables.
ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder)methodOverride to configure additional NpgsqlDataSourceBuilder options.
ConfigureSessionAsync(NpgsqlConnection, string, CancellationToken)methodOverride to add custom session configuration.
ConfigureSystemSessionAsync(NpgsqlConnection, CancellationToken)methodOverride to add custom system session configuration.
DisposeAsync()methodDisposes the data source and releases all pooled connections.
OnConnectionClosed(string)methodOverride to handle connection closed events for metrics.
OnConnectionOpened(string)methodOverride to handle connection opened events for metrics.
OpenConnectionAsync(string, CancellationToken)methodOpens a connection with tenant context configured.
OpenConnectionAsync(string, string, CancellationToken)methodOpens a connection with tenant context and role label configured.
OpenSystemConnectionAsync(CancellationToken)methodOpens a connection for system operations without tenant context.

constructor DataSourceBase(PostgresOptions, ILogger) #

protected DataSourceBase(PostgresOptions options, ILogger logger)

Creates a new data source with the specified options.

property CommandTimeoutSeconds #

public int CommandTimeoutSeconds { get; }

Command timeout in seconds from options.

property ModuleName #

protected abstract string ModuleName { get; }

Module name for logging and metrics.

property Options #

protected PostgresOptions Options { get; }

PostgreSQL options for this data source.

property SchemaName #

public string? SchemaName { get; }

Schema name for this module’s tables.

method ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder) #

protected virtual void ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder builder)

Override to configure additional NpgsqlDataSourceBuilder options.

method ConfigureSessionAsync(NpgsqlConnection, string, CancellationToken) #

protected virtual Task ConfigureSessionAsync(NpgsqlConnection connection, string tenantId, CancellationToken cancellationToken)

Override to add custom session configuration.

method ConfigureSystemSessionAsync(NpgsqlConnection, CancellationToken) #

protected virtual Task ConfigureSystemSessionAsync(NpgsqlConnection connection, CancellationToken cancellationToken)

Override to add custom system session configuration.

method DisposeAsync() #

public ValueTask DisposeAsync()

Disposes the data source and releases all pooled connections.

method OnConnectionClosed(string) #

protected virtual void OnConnectionClosed(string role)

Override to handle connection closed events for metrics.

method OnConnectionOpened(string) #

protected virtual void OnConnectionOpened(string role)

Override to handle connection opened events for metrics.

method OpenConnectionAsync(string, CancellationToken) #

public Task<NpgsqlConnection> OpenConnectionAsync(string tenantId, CancellationToken cancellationToken = default)

Opens a connection with tenant context configured.

Parameters

  • tenantId: Tenant identifier for session configuration.
  • cancellationToken: Cancellation token.

Returns

Open PostgreSQL connection with tenant context set.

method OpenConnectionAsync(string, string, CancellationToken) #

public Task<NpgsqlConnection> OpenConnectionAsync(string tenantId, string role, CancellationToken cancellationToken = default)

Opens a connection with tenant context and role label configured.

Parameters

  • tenantId: Tenant identifier for session configuration.
  • role: Role label for metrics/logging (e.g., “reader”, “writer”).
  • cancellationToken: Cancellation token.

Returns

Open PostgreSQL connection with tenant context set.

method OpenSystemConnectionAsync(CancellationToken) #

public Task<NpgsqlConnection> OpenSystemConnectionAsync(CancellationToken cancellationToken = default)

Opens a connection for system operations without tenant context. Use sparingly - only for migrations, health checks, and cross-tenant admin operations.

Parameters

  • cancellationToken: Cancellation token.

Returns

Open PostgreSQL connection without tenant context.

class PostgresConnectionStringPolicy

public static class PostgresConnectionStringPolicy

Applies StellaOps runtime defaults to PostgreSQL connection strings.

Members

MemberKindSummary
Build(PostgresOptions, string)methodApplies the attribution and pooling policy of the options to their connection string, with the options’ application name or, when they set none, the default one.
Build(string, string, bool?, int?, int?, int?)methodApplies the runtime attribution and pooling policy to a raw connection string.
BuildDefaultApplicationName(string)methodThe default application name of a module: stellaops- and the module name in lower-case kebab case.

method Build(PostgresOptions, string) #

public static string Build(PostgresOptions options, string defaultApplicationName)

Applies the attribution and pooling policy of the options to their connection string, with the options’ application name or, when they set none, the default one.

Parameters

  • options: The connection options.
  • defaultApplicationName: The application name when the options set none.

Returns

The connection string.

method Build(string, string, bool?, int?, int?, int?) #

public static string Build(string connectionString, string applicationName, bool? pooling = null, int? minPoolSize = null, int? maxPoolSize = null, int? connectionIdleLifetimeSeconds = null)

Applies the runtime attribution and pooling policy to a raw connection string. A pooling argument the caller leaves null keeps what the connection string itself says — the operator’s value — and falls back to the defaults (pooling on, min 1, max 100) only when the string carries nothing. A non-null caller value still wins.

An operator’s Maximum Pool Size in the connection string is therefore kept, so hosts that share one PostgreSQL server stay within the pool sizes the operator set for the server’s max_connections.

method BuildDefaultApplicationName(string) #

public static string BuildDefaultApplicationName(string moduleName)

The default application name of a module: stellaops- and the module name in lower-case kebab case.

Parameters

  • moduleName: The module name.

Returns

The application name.

namespace StellaOps.Infrastructure.Postgres.Exceptions

TypeKindDescription
PostgresExceptionHelperclassHelper methods for handling PostgreSQL exceptions.

class PostgresExceptionHelper

public static class PostgresExceptionHelper

Helper methods for handling PostgreSQL exceptions.

Members

MemberKindSummary
CheckViolationconstantPostgreSQL error code for check constraint violation.
DeadlockDetectedconstantPostgreSQL error code for deadlock detected (retry needed).
ForeignKeyViolationconstantPostgreSQL error code for foreign key violation.
NotNullViolationconstantPostgreSQL error code for not null violation.
SerializationFailureconstantPostgreSQL error code for serialization failure (retry needed).
UniqueViolationconstantPostgreSQL error code for unique constraint violation.
IsCheckViolation(PostgresException)methodChecks if the exception is a check constraint violation.
IsForeignKeyViolation(PostgresException)methodChecks if the exception is a foreign key violation.
IsNotNullViolation(PostgresException)methodChecks if the exception is a not null violation.
IsRetryable(Exception)methodChecks if any exception in the chain is retryable.
IsRetryable(PostgresException)methodChecks if the exception is retryable (serialization failure or deadlock).
IsUniqueViolation(PostgresException)methodChecks if the exception is a unique constraint violation.
IsUniqueViolation(PostgresException, string)methodChecks if the exception is a unique constraint violation for a specific constraint.

constant CheckViolation #

public const string CheckViolation = "23514"

PostgreSQL error code for check constraint violation.

constant DeadlockDetected #

public const string DeadlockDetected = "40P01"

PostgreSQL error code for deadlock detected (retry needed).

constant ForeignKeyViolation #

public const string ForeignKeyViolation = "23503"

PostgreSQL error code for foreign key violation.

constant NotNullViolation #

public const string NotNullViolation = "23502"

PostgreSQL error code for not null violation.

constant SerializationFailure #

public const string SerializationFailure = "40001"

PostgreSQL error code for serialization failure (retry needed).

constant UniqueViolation #

public const string UniqueViolation = "23505"

PostgreSQL error code for unique constraint violation.

method IsCheckViolation(PostgresException) #

public static bool IsCheckViolation(PostgresException ex)

Checks if the exception is a check constraint violation.

method IsForeignKeyViolation(PostgresException) #

public static bool IsForeignKeyViolation(PostgresException ex)

Checks if the exception is a foreign key violation.

method IsNotNullViolation(PostgresException) #

public static bool IsNotNullViolation(PostgresException ex)

Checks if the exception is a not null violation.

method IsRetryable(Exception) #

public static bool IsRetryable(Exception ex)

Checks if any exception in the chain is retryable.

method IsRetryable(PostgresException) #

public static bool IsRetryable(PostgresException ex)

Checks if the exception is retryable (serialization failure or deadlock).

method IsUniqueViolation(PostgresException) #

public static bool IsUniqueViolation(PostgresException ex)

Checks if the exception is a unique constraint violation.

method IsUniqueViolation(PostgresException, string) #

public static bool IsUniqueViolation(PostgresException ex, string constraintName)

Checks if the exception is a unique constraint violation for a specific constraint.

namespace StellaOps.Infrastructure.Postgres.Migrations

TypeKindDescription
AppliedMigrationDetailrecordDetails of an applied migration.
DeferredIndexBuilderclassResumes declared concurrent index builds after the host starts.
DeferredIndexDefinitionrecordOwner-reviewed deferral of exactly one index statement in an immutable startup migration.
DeferredIndexNotReadyExceptionclassAn index-dependent operation is temporarily unavailable while maintenance converges.
DeferredIndexOptionsclassBounded post-start maintenance budgets, bindable through the owner’s configuration.
IMigrationRunnerinterfaceInterface for running database migrations.
IMigrationSqlExecutorinterfaceOptional module-owned SQL execution policy.
IMigrationStatusServiceinterfaceService for querying migration status without applying migrations.
MigrationAssemblySourcerecordMigration source descriptor (assembly + optional resource prefix).
MigrationCategoryenumCategorizes migrations by when they should be executed.
MigrationCategoryExtensionsclassExtension methods for migration category operations.
MigrationChecksumclassCanonical checksum computation for migration SQL content.
MigrationChecksumReconciliationPinrecordAn owner-declared statement that one specific already-applied checksum was produced by content whose executable SQL matches the current file — used to reconcile a database whose row was written before the host recorded normalized checksums.
MigrationInfostructInformation about an applied migration.
MigrationReconciliationReasonclassWhy a recorded migration checksum was rewritten without re-running the migration.
MigrationResultclassResult of a migration execution.
MigrationRunOptionsclassOptions for migration execution.
MigrationRunnerclassRuns PostgreSQL migrations from filesystem or embedded resources with advisory-lock coordination.
MigrationServiceExtensionsclassExtension methods for registering migration services.
MigrationSqlExecutionContextrecordThe existing runner-owned connection and transaction for one immutable SQL file.
MigrationSqlNormalizerclassReduces migration SQL to a canonical form in which comments and inter-token whitespace have been removed, so that two files whose executable SQL is identical normalize to the same text even when their comments or layout differ.
MigrationStatusrecordCurrent migration status for a module.
MigrationStatusServiceclassImplementation of migration status service.
MigrationTelemetryclassOpenTelemetry instrumentation for database migrations.
MigrationValidatorclassValidates migration files for naming conventions, duplicates, and ordering issues.
MigrationValidator.ValidationErrorrecordValidation error that will block migration execution.
MigrationValidator.ValidationResultrecordValidation result for a set of migrations.
MigrationValidator.ValidationWarningrecordValidation warning that should be addressed but won’t block execution.
PendingMigrationInforecordInformation about a pending migration.
RequiredDatabaseRolerecordA PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it.
StartupMigrationHostclassHosted service that runs database migrations at application startup.
StartupMigrationOptionsclassOptions for startup migration behavior.

record AppliedMigrationDetail

public sealed record AppliedMigrationDetail

Details of an applied migration.

Parameters

  • Name: The migration file name.
  • Category: The migration category.
  • DurationMs: How long it ran, in milliseconds.
  • WasDryRun: Whether it was a dry run, which applies nothing.

Members

MemberKindSummary
AppliedMigrationDetail(string, MigrationCategory, long, bool)constructorDetails of an applied migration.
CategorypropertyThe migration category.
DurationMspropertyHow long it ran, in milliseconds.
NamepropertyThe migration file name.
WasDryRunpropertyWhether it was a dry run, which applies nothing.

constructor AppliedMigrationDetail(string, MigrationCategory, long, bool) #

public AppliedMigrationDetail(string Name, MigrationCategory Category, long DurationMs, bool WasDryRun)

Details of an applied migration.

Parameters

  • Name: The migration file name.
  • Category: The migration category.
  • DurationMs: How long it ran, in milliseconds.
  • WasDryRun: Whether it was a dry run, which applies nothing.

property Category #

public MigrationCategory Category { get; init; }

The migration category.

property DurationMs #

public long DurationMs { get; init; }

How long it ran, in milliseconds.

property Name #

public string Name { get; init; }

The migration file name.

property WasDryRun #

public bool WasDryRun { get; init; }

Whether it was a dry run, which applies nothing.

class DeferredIndexBuilder

public sealed class DeferredIndexBuilder : BackgroundService

Resumes declared concurrent index builds after the host starts. PostgreSQL session ownership fences both DDL and progress writes: losing the session terminates its work and releases its lock.

Members

MemberKindSummary
DeferredIndexBuilder(string, string, IReadOnlyList<DeferredIndexDefinition>, DeferredIndexOptions, IHostApplicationLifetime, ILogger)constructorResumes declared concurrent index builds after the host starts.
RunPassAsync(CancellationToken)methodAttempts each due declared index once; also used by disposable-database convergence tests.

constructor DeferredIndexBuilder(string, string, IReadOnlyList<DeferredIndexDefinition>, DeferredIndexOptions, IHostApplicationLifetime, ILogger) #

public DeferredIndexBuilder(string connectionString, string ledgerSchema, IReadOnlyList<DeferredIndexDefinition> definitions, DeferredIndexOptions options, IHostApplicationLifetime lifetime, ILogger logger)

Resumes declared concurrent index builds after the host starts. PostgreSQL session ownership fences both DDL and progress writes: losing the session terminates its work and releases its lock.

method RunPassAsync(CancellationToken) #

public Task RunPassAsync(CancellationToken cancellationToken)

Attempts each due declared index once; also used by disposable-database convergence tests.

record DeferredIndexDefinition

public sealed record DeferredIndexDefinition

Owner-reviewed deferral of exactly one index statement in an immutable startup migration. The original migration checksum remains the ledger identity. All other SQL still runs at startup.

Parameters

  • MigrationName: The migration that holds the index statement.
  • MigrationChecksum: The checksum of the migration, its ledger identity.
  • IndexSchema: The schema of the index.
  • IndexName: The index name.
  • TableName: The table of the index.
  • IndexStatement: The index statement, as the migration writes it.
  • CatalogDefinition: The definition the catalog reports for the built index (pg_get_indexdef).

Members

MemberKindSummary
DeferredIndexDefinition(string, string, string, string, string, string, string)constructorOwner-reviewed deferral of exactly one index statement in an immutable startup migration.
CatalogDefinitionpropertyThe definition the catalog reports for the built index (pg_get_indexdef).
IndexNamepropertyThe index name.
IndexSchemapropertyThe schema of the index.
IndexStatementpropertyThe index statement, as the migration writes it.
MigrationChecksumpropertyThe checksum of the migration, its ledger identity.
MigrationNamepropertyThe migration that holds the index statement.
TableNamepropertyThe table of the index.
IsReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken)methodChecks the actual relation, table, definition and PostgreSQL validity flags.
RemoveFrom(string)methodValidates the pinned input and returns only the non-deferred SQL.
RequireReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken)methodRefuses an index-dependent query before it can scan the unindexed table.

constructor DeferredIndexDefinition(string, string, string, string, string, string, string) #

public DeferredIndexDefinition(string MigrationName, string MigrationChecksum, string IndexSchema, string IndexName, string TableName, string IndexStatement, string CatalogDefinition)

Owner-reviewed deferral of exactly one index statement in an immutable startup migration. The original migration checksum remains the ledger identity. All other SQL still runs at startup.

Parameters

  • MigrationName: The migration that holds the index statement.
  • MigrationChecksum: The checksum of the migration, its ledger identity.
  • IndexSchema: The schema of the index.
  • IndexName: The index name.
  • TableName: The table of the index.
  • IndexStatement: The index statement, as the migration writes it.
  • CatalogDefinition: The definition the catalog reports for the built index (pg_get_indexdef).

property CatalogDefinition #

public string CatalogDefinition { get; init; }

The definition the catalog reports for the built index (pg_get_indexdef).

property IndexName #

public string IndexName { get; init; }

The index name.

property IndexSchema #

public string IndexSchema { get; init; }

The schema of the index.

property IndexStatement #

public string IndexStatement { get; init; }

The index statement, as the migration writes it.

property MigrationChecksum #

public string MigrationChecksum { get; init; }

The checksum of the migration, its ledger identity.

property MigrationName #

public string MigrationName { get; init; }

The migration that holds the index statement.

property TableName #

public string TableName { get; init; }

The table of the index.

method IsReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken) #

public Task<bool> IsReadyAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, CancellationToken cancellationToken)

Checks the actual relation, table, definition and PostgreSQL validity flags.

method RemoveFrom(string) #

public string RemoveFrom(string migrationSql)

Validates the pinned input and returns only the non-deferred SQL.

method RequireReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken) #

public Task RequireReadyAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, CancellationToken cancellationToken)

Refuses an index-dependent query before it can scan the unindexed table.

class DeferredIndexNotReadyException

public sealed class DeferredIndexNotReadyException : InvalidOperationException

An index-dependent operation is temporarily unavailable while maintenance converges.

Members

MemberKindSummary
DeferredIndexNotReadyException(string, string)constructorAn index-dependent operation is temporarily unavailable while maintenance converges.

constructor DeferredIndexNotReadyException(string, string) #

public DeferredIndexNotReadyException(string schema, string index)

An index-dependent operation is temporarily unavailable while maintenance converges.

class DeferredIndexOptions

public sealed class DeferredIndexOptions

Bounded post-start maintenance budgets, bindable through the owner’s configuration.

Members

MemberKindSummary
DeferredIndexOptions()constructorCreates an instance of DeferredIndexOptions.
BuildTimeoutSecondspropertyThe statement timeout of one index build, in seconds, from 1 to 86400.
LockTimeoutSecondspropertyThe lock timeout of one index build, in seconds, from 1 to 300.
MaxRetryDelaySecondspropertyThe longest retry delay, in seconds, from DeferredIndexOptions.RetryDelaySecondsto 86400.
PollIntervalSecondspropertyThe pause between two checks for pending index builds, in seconds, from 1 to 300.
RetryDelaySecondspropertyThe delay before the first retry of a failed build, in seconds, from 1 to 86400; it doubles for each further retry.

constructor DeferredIndexOptions() #

public DeferredIndexOptions()

Creates an instance of DeferredIndexOptions.

property BuildTimeoutSeconds #

public int BuildTimeoutSeconds { get; set; }

The statement timeout of one index build, in seconds, from 1 to 86400. The default is 3600.

property LockTimeoutSeconds #

public int LockTimeoutSeconds { get; set; }

The lock timeout of one index build, in seconds, from 1 to 300. The default is 10.

property MaxRetryDelaySeconds #

public int MaxRetryDelaySeconds { get; set; }

The longest retry delay, in seconds, from DeferredIndexOptions.RetryDelaySecondsto 86400. The default is 900.

property PollIntervalSeconds #

public int PollIntervalSeconds { get; set; }

The pause between two checks for pending index builds, in seconds, from 1 to 300. The default is 5.

property RetryDelaySeconds #

public int RetryDelaySeconds { get; set; }

The delay before the first retry of a failed build, in seconds, from 1 to 86400; it doubles for each further retry. The default is 30.

interface IMigrationRunner

public interface IMigrationRunner

Interface for running database migrations.

Members

MemberKindSummary
ModuleNamepropertyGets the module name for this migration runner.
SchemaNamepropertyGets the schema name for this migration runner.
GetAppliedMigrationInfoAsync(CancellationToken)methodGets all applied migrations.
GetCurrentVersionAsync(CancellationToken)methodGets the current migration version (latest applied migration).
RunAsync(string, MigrationRunOptions, CancellationToken)methodRuns pending migrations from the specified path.
RunFromAssemblyAsync(Assembly, string, MigrationRunOptions, CancellationToken)methodRuns pending migrations from embedded resources in an assembly.
ValidateChecksumsAsync(Assembly, string, CancellationToken)methodValidates checksums of applied migrations against source files.

property ModuleName #

string ModuleName { get; }

Gets the module name for this migration runner.

property SchemaName #

string SchemaName { get; }

Gets the schema name for this migration runner.

method GetAppliedMigrationInfoAsync(CancellationToken) #

Task<IReadOnlyList<MigrationInfo>> GetAppliedMigrationInfoAsync(CancellationToken cancellationToken = default)

Gets all applied migrations.

method GetCurrentVersionAsync(CancellationToken) #

Task<string?> GetCurrentVersionAsync(CancellationToken cancellationToken = default)

Gets the current migration version (latest applied migration).

method RunAsync(string, MigrationRunOptions, CancellationToken) #

Task<MigrationResult> RunAsync(string migrationsPath, MigrationRunOptions? options = null, CancellationToken cancellationToken = default)

Runs pending migrations from the specified path.

Parameters

  • migrationsPath: Path to directory containing SQL migration files.
  • options: Migration execution options.
  • cancellationToken: Cancellation token.

Returns

Result of migration execution.

method RunFromAssemblyAsync(Assembly, string, MigrationRunOptions, CancellationToken) #

Task<MigrationResult> RunFromAssemblyAsync(Assembly assembly, string? resourcePrefix = null, MigrationRunOptions? options = null, CancellationToken cancellationToken = default)

Runs pending migrations from embedded resources in an assembly.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • resourcePrefix: Optional prefix to filter resources.
  • options: Migration execution options.
  • cancellationToken: Cancellation token.

Returns

Result of migration execution.

method ValidateChecksumsAsync(Assembly, string, CancellationToken) #

Task<IReadOnlyList<string>> ValidateChecksumsAsync(Assembly assembly, string? resourcePrefix = null, CancellationToken cancellationToken = default)

Validates checksums of applied migrations against source files.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • resourcePrefix: Optional prefix to filter resources.
  • cancellationToken: Cancellation token.

Returns

List of checksum validation errors, empty if all valid.

interface IMigrationSqlExecutor

public interface IMigrationSqlExecutor

Optional module-owned SQL execution policy. The runner retains locks, checksums and ledger commits.

Members

MemberKindSummary
ExecuteAsync(MigrationSqlExecutionContext, CancellationToken)methodRuns the SQL of one migration on the runner’s connection and transaction.

method ExecuteAsync(MigrationSqlExecutionContext, CancellationToken) #

Task ExecuteAsync(MigrationSqlExecutionContext context, CancellationToken cancellationToken)

Runs the SQL of one migration on the runner’s connection and transaction.

Parameters

  • context: The connection, the transaction and the SQL.
  • cancellationToken: Cancels the operation.

Returns

A task that completes when the SQL has run.

interface IMigrationStatusService

public interface IMigrationStatusService

Service for querying migration status without applying migrations.

Members

MemberKindSummary
GetStatusAsync(CancellationToken)methodGets the current migration status for the module.

method GetStatusAsync(CancellationToken) #

Task<MigrationStatus> GetStatusAsync(CancellationToken cancellationToken = default)

Gets the current migration status for the module.

record MigrationAssemblySource

public sealed record MigrationAssemblySource

Migration source descriptor (assembly + optional resource prefix).

Parameters

  • MigrationsAssembly: The assembly that embeds the migrations.
  • ResourcePrefix: Only the resources whose names contain this text, ignoring case; all when not set.

Members

MemberKindSummary
MigrationAssemblySource(Assembly, string)constructorMigration source descriptor (assembly + optional resource prefix).
MigrationsAssemblypropertyThe assembly that embeds the migrations.
ResourcePrefixpropertyOnly the resources whose names contain this text, ignoring case; all when not set.

constructor MigrationAssemblySource(Assembly, string) #

public MigrationAssemblySource(Assembly MigrationsAssembly, string? ResourcePrefix = null)

Migration source descriptor (assembly + optional resource prefix).

Parameters

  • MigrationsAssembly: The assembly that embeds the migrations.
  • ResourcePrefix: Only the resources whose names contain this text, ignoring case; all when not set.

property MigrationsAssembly #

public Assembly MigrationsAssembly { get; init; }

The assembly that embeds the migrations.

property ResourcePrefix #

public string? ResourcePrefix { get; init; }

Only the resources whose names contain this text, ignoring case; all when not set.

enum MigrationCategory

public enum MigrationCategory

Categorizes migrations by when they should be executed.

ValueDescription
Startup = 0Automatic migrations that run at application startup. Must be non-breaking and complete quickly (< 60s). Prefix: 001-099
Release = 1Manual migrations that require CLI execution before deployment. Used for breaking changes that need coordination. Prefix: 100-199
Seed = 2Optional seed/demo data that is inserted only when an operator runs it explicitly. Prefix: S001-S999
Data = 3Long-running data migrations that run as background jobs. Prefix: DM001-DM999

class MigrationCategoryExtensions

public static class MigrationCategoryExtensions

Extension methods for migration category operations.

Members

MemberKindSummary
GetCategory(string)methodDetermines the category of a migration based on its filename.
IsAutomatic(MigrationCategory)extension methodReturns true if this migration should run automatically at startup.
RequiresManualExecution(MigrationCategory)extension methodReturns true if this migration requires manual CLI execution before startup may proceed.

method GetCategory(string) #

public static MigrationCategory GetCategory(string migrationName)

Determines the category of a migration based on its filename.

extension method IsAutomatic(MigrationCategory) #

public static bool IsAutomatic(this MigrationCategory category)

Returns true if this migration should run automatically at startup.

extension method RequiresManualExecution(MigrationCategory) #

public static bool RequiresManualExecution(this MigrationCategory category)

Returns true if this migration requires manual CLI execution before startup may proceed. Seed migrations are intentionally excluded because they are opt-in/manual only and must not block runtime.

class MigrationChecksum

public static class MigrationChecksum

Canonical checksum computation for migration SQL content.

Remarks

The migration host records a SHA-256 checksum of each applied migration’s SQL and re-validates it on every startup so that an accidental edit to an already-applied migration is caught (migrations are forward-only). The checksum MUST be stable across operating systems and source checkouts; otherwise a clone with CRLF line endings produces a different hash than one with LF endings for byte-identical SQL, and the host fails closed on a non-drift.

MigrationChecksum.Compute(string)therefore normalizes all line endings to \n before hashing so the same logical SQL hashes identically regardless of how it was checked out.

MigrationChecksum.ComputeRaw(string)hashes the bytes as-is (no normalization). It exists ONLY to recognize a legacy schema_migrations row whose stored checksum was written by an older host build (or a different-line-ending checkout) that hashed the raw bytes. Such a row is the same SQL, just hashed before normalization existed; the host self-heals it to the normalized value rather than treating it as drift (see MigrationChecksum.IsSelfHealableLegacyChecksum(string, string)). A genuine content change matches no line-ending rendering and still fails closed.

Members

MemberKindSummary
Compute(string)methodComputes the canonical, line-ending-normalized SHA-256 checksum (lowercase hex) of the supplied migration SQL content.
ComputeRaw(string)methodComputes the SHA-256 checksum (lowercase hex) of the supplied content WITHOUT any line-ending normalization.
IsSelfHealableLegacyChecksum(string, string)methodDetermines whether a stored checksum that does not match the canonical (MigrationChecksum.Compute(string)) checksum is nonetheless a self-healable legacy value: the raw, un-normalized hash of the SAME logical SQL under a different line-ending rendering (e.g. a CRLF checkout recorded the row, but the host now reads/normalizes LF, or vice versa).

method Compute(string) #

public static string Compute(string content)

Computes the canonical, line-ending-normalized SHA-256 checksum (lowercase hex) of the supplied migration SQL content.

Parameters

  • content: Raw SQL content as read from the embedded resource or file.

Returns

Lowercase hex SHA-256 of the LF-normalized content.

method ComputeRaw(string) #

public static string ComputeRaw(string content)

Computes the SHA-256 checksum (lowercase hex) of the supplied content WITHOUT any line-ending normalization. This reproduces the historical, pre-normalization hash form used to detect a self-healable legacy checksum.

Parameters

  • content: Raw SQL content as read from the embedded resource or file.

Returns

Lowercase hex SHA-256 of the raw content bytes.

method IsSelfHealableLegacyChecksum(string, string) #

public static bool IsSelfHealableLegacyChecksum(string content, string storedChecksum)

Determines whether a stored checksum that does not match the canonical (MigrationChecksum.Compute(string)) checksum is nonetheless a self-healable legacy value: the raw, un-normalized hash of the SAME logical SQL under a different line-ending rendering (e.g. a CRLF checkout recorded the row, but the host now reads/normalizes LF, or vice versa).

Parameters

  • content: Current SQL content for the migration (any line endings).
  • storedChecksum: Checksum recorded in schema_migrations.

Returns

true when storedChecksum equals the raw hash of either the all-LF or the all-CRLF rendering of the same SQL (and therefore differs from the canonical hash only because of historical non-normalization); false for a genuine content change or when the stored value already equals the canonical hash.

record MigrationChecksumReconciliationPin

public sealed record MigrationChecksumReconciliationPin

An owner-declared statement that one specific already-applied checksum was produced by content whose executable SQL matches the current file — used to reconcile a database whose row was written before the host recorded normalized checksums.

Parameters

  • MigrationName: File name as recorded in schema_migrations.migration_name.
  • AppliedChecksum: Whole-file checksum the database currently holds for that row.
  • AppliedNormalizedChecksum: Normalized checksum of the content that produced AppliedChecksum.
  • Justification: Short audit note (commit + what changed), persisted with the ledger row.

Remarks

A pin is not a blanket exemption. The host accepts it only when all three hold: the database’s stored checksum equals MigrationChecksumReconciliationPin.AppliedChecksumexactly; the current file normalizes successfully; and that normalized form hashes to MigrationChecksumReconciliationPin.AppliedNormalizedChecksum. So a pin is bound to one exact pair of contents: a later DDL edit on top of a pinned file changes the normalized hash and fails closed again, and a pin authored against different content never matches.

A pin also expires on use: once the row is reconciled its checksum is the file’s, so the first condition can never match again.

MigrationChecksumReconciliationPin.AppliedNormalizedChecksumis derived from the historical content — read the applied version out of source control and run it through MigrationSqlNormalizer.TryComputeNormalizedChecksum(string, out string). Deriving it from the current file instead would make the pin self-confirming and prove nothing.

Members

MemberKindSummary
MigrationChecksumReconciliationPin(string, string, string, string)constructorAn owner-declared statement that one specific already-applied checksum was produced by content whose executable SQL matches the current file — used to reconcile a database whose row was written before the host recorded normalized checksums.
AppliedChecksumpropertyWhole-file checksum the database currently holds for that row.
AppliedNormalizedChecksumpropertyNormalized checksum of the content that produced AppliedChecksum.
IsRuledEditpropertyTrue when this pin records an owner-ruled SQL edit rather than a comment-only legacy row.
JustificationpropertyShort audit note (commit + what changed), persisted with the ledger row.
MigrationNamepropertyFile name as recorded in schema_migrations.migration_name.
RuledEditNormalizedChecksumpropertySet only for a recorded exception to the forward-only rule: the normalized checksum of the ONE edited file content accepted in place of the applied content.
RulingpropertyThe ruling that authorised the edit (date and record), persisted with the justification.

constructor MigrationChecksumReconciliationPin(string, string, string, string) #

public MigrationChecksumReconciliationPin(string MigrationName, string AppliedChecksum, string AppliedNormalizedChecksum, string Justification)

An owner-declared statement that one specific already-applied checksum was produced by content whose executable SQL matches the current file — used to reconcile a database whose row was written before the host recorded normalized checksums.

Parameters

  • MigrationName: File name as recorded in schema_migrations.migration_name.
  • AppliedChecksum: Whole-file checksum the database currently holds for that row.
  • AppliedNormalizedChecksum: Normalized checksum of the content that produced AppliedChecksum.
  • Justification: Short audit note (commit + what changed), persisted with the ledger row.

Remarks

A pin is not a blanket exemption. The host accepts it only when all three hold: the database’s stored checksum equals MigrationChecksumReconciliationPin.AppliedChecksumexactly; the current file normalizes successfully; and that normalized form hashes to MigrationChecksumReconciliationPin.AppliedNormalizedChecksum. So a pin is bound to one exact pair of contents: a later DDL edit on top of a pinned file changes the normalized hash and fails closed again, and a pin authored against different content never matches.

A pin also expires on use: once the row is reconciled its checksum is the file’s, so the first condition can never match again.

MigrationChecksumReconciliationPin.AppliedNormalizedChecksumis derived from the historical content — read the applied version out of source control and run it through MigrationSqlNormalizer.TryComputeNormalizedChecksum(string, out string). Deriving it from the current file instead would make the pin self-confirming and prove nothing.

property AppliedChecksum #

public string AppliedChecksum { get; init; }

Whole-file checksum the database currently holds for that row.

property AppliedNormalizedChecksum #

public string AppliedNormalizedChecksum { get; init; }

Normalized checksum of the content that produced AppliedChecksum.

property IsRuledEdit #

public bool IsRuledEdit { get; }

True when this pin records an owner-ruled SQL edit rather than a comment-only legacy row.

property Justification #

public string Justification { get; init; }

Short audit note (commit + what changed), persisted with the ledger row.

property MigrationName #

public string MigrationName { get; init; }

File name as recorded in schema_migrations.migration_name.

property RuledEditNormalizedChecksum #

public string? RuledEditNormalizedChecksum { get; init; }

Set only for a recorded exception to the forward-only rule: the normalized checksum of the ONE edited file content accepted in place of the applied content. When set, the pin matches a row whose stored checksum is MigrationChecksumReconciliationPin.AppliedChecksumor whose recorded normalized checksum is MigrationChecksumReconciliationPin.AppliedNormalizedChecksum, and it reconciles only when the current file normalizes to this value; any further edit fails closed. Leave null for a comment-only legacy pin, whose executable SQL must be unchanged.

property Ruling #

public string? Ruling { get; init; }

The ruling that authorised the edit (date and record), persisted with the justification.

struct MigrationInfo

public readonly struct MigrationInfo : IEquatable<MigrationInfo>

Information about an applied migration.

Parameters

  • Name: The migration file name.
  • AppliedAt: When it was applied.
  • Checksum: The checksum recorded when it was applied.

Members

MemberKindSummary
MigrationInfo(string, DateTimeOffset, string)constructorInformation about an applied migration.
AppliedAtpropertyWhen it was applied.
ChecksumpropertyThe checksum recorded when it was applied.
NamepropertyThe migration file name.

constructor MigrationInfo(string, DateTimeOffset, string) #

public MigrationInfo(string Name, DateTimeOffset AppliedAt, string Checksum)

Information about an applied migration.

Parameters

  • Name: The migration file name.
  • AppliedAt: When it was applied.
  • Checksum: The checksum recorded when it was applied.

property AppliedAt #

public DateTimeOffset AppliedAt { get; init; }

When it was applied.

property Checksum #

public string Checksum { get; init; }

The checksum recorded when it was applied.

property Name #

public string Name { get; init; }

The migration file name.

class MigrationReconciliationReason

public static class MigrationReconciliationReason

Why a recorded migration checksum was rewritten without re-running the migration. Persisted verbatim in <schema>.schema_migration_reconciliations.reason.

Members

MemberKindSummary
CommentOnlyconstantThe file’s SQL is unchanged once comments and layout are removed; only comments/whitespace moved.
LegacyPinconstantThe row predates normalized-checksum tracking, and an owner-declared pin proved the applied content and the current file normalize to the same SQL.
LineEndingconstantThe stored value was the pre-normalization hash of the same SQL under different line endings.
RuledEditconstantThe executable SQL of an applied migration was changed under a recorded exception to the forward-only rule.

constant CommentOnly #

public const string CommentOnly = "comment-only-reconciliation"

The file’s SQL is unchanged once comments and layout are removed; only comments/whitespace moved.

constant LegacyPin #

public const string LegacyPin = "legacy-pin-reconciliation"

The row predates normalized-checksum tracking, and an owner-declared pin proved the applied content and the current file normalize to the same SQL.

constant LineEnding #

public const string LineEnding = "line-ending-reconciliation"

The stored value was the pre-normalization hash of the same SQL under different line endings.

constant RuledEdit #

public const string RuledEdit = "ruled-edit-reconciliation"

The executable SQL of an applied migration was changed under a recorded exception to the forward-only rule. The pin binds the historical content to the one accepted edited form; the migration is not re-run.

class MigrationResult

public sealed class MigrationResult

Result of a migration execution.

Members

MemberKindSummary
MigrationResult()constructorCreates an instance of MigrationResult.
AppliedCountpropertyNumber of migrations applied.
AppliedMigrationspropertyDetails of applied migrations.
ChecksumErrorspropertyChecksum validation errors, if any.
DurationMspropertyTotal duration in milliseconds.
ErrorMessagepropertyError message if migration failed.
FilteredCountpropertyNumber of migrations filtered out by category.
SkippedCountpropertyNumber of migrations skipped (already applied).
SuccesspropertyWhether the migration run was successful.
Failed(string, IReadOnlyList<string>)methodCreates a failed result.
Successful(int, int, int, long, IReadOnlyList<AppliedMigrationDetail>)methodCreates a successful result.

constructor MigrationResult() #

public MigrationResult()

Creates an instance of MigrationResult.

property AppliedCount #

public int AppliedCount { get; init; }

Number of migrations applied.

property AppliedMigrations #

public IReadOnlyList<AppliedMigrationDetail> AppliedMigrations { get; init; }

Details of applied migrations.

property ChecksumErrors #

public IReadOnlyList<string> ChecksumErrors { get; init; }

Checksum validation errors, if any.

property DurationMs #

public long DurationMs { get; init; }

Total duration in milliseconds.

property ErrorMessage #

public string? ErrorMessage { get; init; }

Error message if migration failed.

property FilteredCount #

public int FilteredCount { get; init; }

Number of migrations filtered out by category.

property SkippedCount #

public int SkippedCount { get; init; }

Number of migrations skipped (already applied).

property Success #

public bool Success { get; init; }

Whether the migration run was successful.

method Failed(string, IReadOnlyList<string>) #

public static MigrationResult Failed(string errorMessage, IReadOnlyList<string>? checksumErrors = null)

Creates a failed result.

method Successful(int, int, int, long, IReadOnlyList<AppliedMigrationDetail>) #

public static MigrationResult Successful(int appliedCount, int skippedCount, int filteredCount, long durationMs, IReadOnlyList<AppliedMigrationDetail> appliedMigrations)

Creates a successful result.

class MigrationRunOptions

public sealed class MigrationRunOptions

Options for migration execution.

Members

MemberKindSummary
MigrationRunOptions()constructorCreates an instance of MigrationRunOptions.
CategoryFilterpropertyFilter migrations by category.
ChecksumReconciliationPinspropertyOwner-declared reconciliations for rows written before the runner recorded normalized checksums.
DryRunpropertyIf true, only show what would be executed without applying.
FailOnChecksumMismatchpropertyIf true, fail if checksum validation errors are found.
TimeoutSecondspropertyTimeout in seconds for individual migration execution.
ValidateChecksumspropertyIf true, validate checksums before applying new migrations.

constructor MigrationRunOptions() #

public MigrationRunOptions()

Creates an instance of MigrationRunOptions.

property CategoryFilter #

public MigrationCategory? CategoryFilter { get; set; }

Filter migrations by category. If null, all categories are included.

property ChecksumReconciliationPins #

public IList<MigrationChecksumReconciliationPin> ChecksumReconciliationPins { get; }

Owner-declared reconciliations for rows written before the runner recorded normalized checksums. Same contract as StartupMigrationOptions.ChecksumReconciliationPins.

property DryRun #

public bool DryRun { get; set; }

If true, only show what would be executed without applying.

property FailOnChecksumMismatch #

public bool FailOnChecksumMismatch { get; set; }

If true, fail if checksum validation errors are found.

property TimeoutSeconds #

public int TimeoutSeconds { get; set; }

Timeout in seconds for individual migration execution. Default: 300.

property ValidateChecksums #

public bool ValidateChecksums { get; set; }

If true, validate checksums before applying new migrations.

class MigrationRunner

public sealed class MigrationRunner : IMigrationRunner

Runs PostgreSQL migrations from filesystem or embedded resources with advisory-lock coordination.

Members

MemberKindSummary
MigrationRunner(string, string, string, ILogger)constructorCreates a runner for the migrations of a module.
ModuleNamepropertyGets the module name for this migration runner.
SchemaNamepropertyGets the schema name for this migration runner.
GetAppliedMigrationInfoAsync(CancellationToken)methodGets all applied migrations.
GetCurrentVersionAsync(CancellationToken)methodGets the current migration version (latest applied migration).
RunAsync(string, MigrationRunOptions, CancellationToken)methodRuns pending migrations from the specified path.
RunFromAssemblyAsync(Assembly, string, MigrationRunOptions, CancellationToken)methodRuns pending migrations from embedded resources in an assembly.
ValidateChecksumsAsync(Assembly, string, CancellationToken)methodValidates checksums of applied migrations against source files.

constructor MigrationRunner(string, string, string, ILogger) #

public MigrationRunner(string connectionString, string schemaName, string moduleName, ILogger logger)

Creates a runner for the migrations of a module.

Parameters

  • connectionString: The connection string.
  • schemaName: The schema that holds the module’s migration ledger.
  • moduleName: The module, for the log.
  • logger: The logger.

Exceptions

  • ArgumentNullException: An argument is null.

property ModuleName #

public string ModuleName { get; }

Gets the module name for this migration runner.

property SchemaName #

public string SchemaName { get; }

Gets the schema name for this migration runner.

method GetAppliedMigrationInfoAsync(CancellationToken) #

public Task<IReadOnlyList<MigrationInfo>> GetAppliedMigrationInfoAsync(CancellationToken cancellationToken = default)

Gets all applied migrations.

method GetCurrentVersionAsync(CancellationToken) #

public Task<string?> GetCurrentVersionAsync(CancellationToken cancellationToken = default)

Gets the current migration version (latest applied migration).

method RunAsync(string, MigrationRunOptions, CancellationToken) #

public Task<MigrationResult> RunAsync(string migrationsPath, MigrationRunOptions? options = null, CancellationToken cancellationToken = default)

Runs pending migrations from the specified path.

Parameters

  • migrationsPath: Path to directory containing SQL migration files.
  • options: Migration execution options.
  • cancellationToken: Cancellation token.

Returns

Result of migration execution.

method RunFromAssemblyAsync(Assembly, string, MigrationRunOptions, CancellationToken) #

public Task<MigrationResult> RunFromAssemblyAsync(Assembly assembly, string? resourcePrefix = null, MigrationRunOptions? options = null, CancellationToken cancellationToken = default)

Runs pending migrations from embedded resources in an assembly.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • resourcePrefix: Optional prefix to filter resources.
  • options: Migration execution options.
  • cancellationToken: Cancellation token.

Returns

Result of migration execution.

method ValidateChecksumsAsync(Assembly, string, CancellationToken) #

public Task<IReadOnlyList<string>> ValidateChecksumsAsync(Assembly assembly, string? resourcePrefix = null, CancellationToken cancellationToken = default)

Validates checksums of applied migrations against source files.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • resourcePrefix: Optional prefix to filter resources.
  • cancellationToken: Cancellation token.

Returns

List of checksum validation errors, empty if all valid.

class MigrationServiceExtensions

public static class MigrationServiceExtensions

Extension methods for registering migration services.

Members

MemberKindSummary
AddMigrationRunner<TOptions>(IServiceCollection, string, string, Func<TOptions, string>)extension methodAdds a migration runner as a singleton for manual/CLI migration execution.
AddMigrationStatus<TOptions>(IServiceCollection, string, string, Assembly, Func<TOptions, string>, string)extension methodAdds the migration status service for querying migration state.
AddStartupMigrations(IServiceCollection, string, string, Assembly, Action<StartupMigrationOptions>)extension methodAdds a startup migration host using PostgresOptions.
AddStartupMigrations<TOptions>(IServiceCollection, string, string, Assembly, Func<TOptions, string>, Action<StartupMigrationOptions>)extension methodAdds a startup migration host for the specified module.

extension method AddMigrationRunner<TOptions>(IServiceCollection, string, string, Func<TOptions, string>) #

public static IServiceCollection AddMigrationRunner<TOptions>(this IServiceCollection services, string schemaName, string moduleName, Func<TOptions, string> connectionStringSelector) where TOptions : class

Adds a migration runner as a singleton for manual/CLI migration execution.

extension method AddMigrationStatus<TOptions>(IServiceCollection, string, string, Assembly, Func<TOptions, string>, string) #

public static IServiceCollection AddMigrationStatus<TOptions>(this IServiceCollection services, string schemaName, string moduleName, Assembly migrationsAssembly, Func<TOptions, string> connectionStringSelector, string? resourcePrefix = null) where TOptions : class

Adds the migration status service for querying migration state.

extension method AddStartupMigrations(IServiceCollection, string, string, Assembly, Action<StartupMigrationOptions>) #

public static IServiceCollection AddStartupMigrations(this IServiceCollection services, string schemaName, string moduleName, Assembly migrationsAssembly, Action<StartupMigrationOptions>? configureOptions = null)

Adds a startup migration host using PostgresOptions.

extension method AddStartupMigrations<TOptions>(IServiceCollection, string, string, Assembly, Func<TOptions, string>, Action<StartupMigrationOptions>) #

public static IServiceCollection AddStartupMigrations<TOptions>(this IServiceCollection services, string schemaName, string moduleName, Assembly migrationsAssembly, Func<TOptions, string> connectionStringSelector, Action<StartupMigrationOptions>? configureOptions = null) where TOptions : class

Adds a startup migration host for the specified module.

Type parameters

  • TOptions: Options type containing the connection string.

Parameters

  • services: Service collection.
  • schemaName: PostgreSQL schema name for this module.
  • moduleName: Module name for logging.
  • migrationsAssembly: Assembly containing embedded SQL migrations.
  • connectionStringSelector: Function to extract connection string from options.
  • configureOptions: Optional configuration for migration behavior.

Returns

Service collection for chaining.

record MigrationSqlExecutionContext

public sealed record MigrationSqlExecutionContext

The existing runner-owned connection and transaction for one immutable SQL file.

Parameters

  • Connection: The runner’s open connection.
  • Transaction: The runner’s transaction; none for a migration that runs outside one.
  • MigrationName: The migration.
  • Sql: The SQL of the migration file.
  • CommandTimeoutSeconds: The command timeout, in seconds.

Members

MemberKindSummary
MigrationSqlExecutionContext(NpgsqlConnection, NpgsqlTransaction, string, string, int)constructorThe existing runner-owned connection and transaction for one immutable SQL file.
CommandTimeoutSecondspropertyThe command timeout, in seconds.
ConnectionpropertyThe runner’s open connection.
MigrationNamepropertyThe migration.
SqlpropertyThe SQL of the migration file.
TransactionpropertyThe runner’s transaction; none for a migration that runs outside one.

constructor MigrationSqlExecutionContext(NpgsqlConnection, NpgsqlTransaction, string, string, int) #

public MigrationSqlExecutionContext(NpgsqlConnection Connection, NpgsqlTransaction? Transaction, string MigrationName, string Sql, int CommandTimeoutSeconds)

The existing runner-owned connection and transaction for one immutable SQL file.

Parameters

  • Connection: The runner’s open connection.
  • Transaction: The runner’s transaction; none for a migration that runs outside one.
  • MigrationName: The migration.
  • Sql: The SQL of the migration file.
  • CommandTimeoutSeconds: The command timeout, in seconds.

property CommandTimeoutSeconds #

public int CommandTimeoutSeconds { get; init; }

The command timeout, in seconds.

property Connection #

public NpgsqlConnection Connection { get; init; }

The runner’s open connection.

property MigrationName #

public string MigrationName { get; init; }

The migration.

property Sql #

public string Sql { get; init; }

The SQL of the migration file.

property Transaction #

public NpgsqlTransaction? Transaction { get; init; }

The runner’s transaction; none for a migration that runs outside one.

class MigrationSqlNormalizer

public static class MigrationSqlNormalizer

Reduces migration SQL to a canonical form in which comments and inter-token whitespace have been removed, so that two files whose executable SQL is identical normalize to the same text even when their comments or layout differ.

Remarks

Why this exists. MigrationChecksumhashes the whole file, which is correct for detecting drift but means a comment edit to an already-applied migration blocks deployment exactly as hard as an altered DDL statement: a host built after a comment-only edit would fail to start against every database that had applied the original file. The normalizer supplies the evidence needed to tell “someone changed a comment” apart from “someone changed the schema”, so the first can be reconciled forward and the second still fails closed.

It is deliberately conservative. A normalizer that is clever about ambiguous input is worse than one that refuses: a wrong answer here reconciles a real DDL change. Every construct whose extent cannot be determined without knowing server settings, and every unterminated construct, produces a refusal (MigrationSqlNormalizer.TryNormalize(string, out string, out string)returns false) and the caller must fall back to failing closed.

Rules. Line endings are normalized to \n first (matching MigrationChecksum.Compute(string)). Then, outside of string literals: -- line comments and /* */ block comments (PostgreSQL block comments nest) are replaced by a single separator, and every run of whitespace collapses to one space. Single-quoted literals, E'' escape literals, double-quoted identifiers and dollar-quoted bodies are copied through verbatim — including any whitespace and any -- or /* they contain, which are data, not comments.

Whitespace normalizes too, on the same terms: re-indenting a statement does not change what it does. Whitespace inside a literal is preserved, because 'a b' and 'a b' are different values.

Members

MemberKindSummary
TryComputeNormalizedChecksum(string, out string)methodComputes the SHA-256 (lowercase hex) of the normalized form of content.
TryNormalize(string, out string, out string)methodAttempts to reduce content to its comment-free, whitespace-collapsed form.

method TryComputeNormalizedChecksum(string, out string) #

public static string? TryComputeNormalizedChecksum(string content, out string? refusal)

Computes the SHA-256 (lowercase hex) of the normalized form of content.

Parameters

  • content: Raw SQL content as read from the embedded resource or file.
  • refusal: Populated with the reason when normalization was refused.

Returns

The normalized checksum, or null when normalization was refused.

method TryNormalize(string, out string, out string) #

public static bool TryNormalize(string content, out string normalized, out string? refusal)

Attempts to reduce content to its comment-free, whitespace-collapsed form.

Parameters

  • content: Raw SQL content as read from the embedded resource or file.
  • normalized: The canonical form when this method returns true.
  • refusal: When this method returns false, a human-readable reason including the 1-based line and column at which normalization was abandoned.

Returns

true when the content was fully understood; otherwise false.

record MigrationStatus

public sealed record MigrationStatus

Current migration status for a module.

Members

MemberKindSummary
MigrationStatus()constructorCreates an instance of MigrationStatus.
AppliedCountpropertyNumber of applied migrations.
ChecksumErrorspropertyAny checksum mismatches detected.
HasBlockingIssuespropertyWhether there are blocking issues (pending release migrations or checksum errors).
IsUpToDatepropertyWhether the database is up to date (no pending startup/release migrations).
LastAppliedAtpropertyWhen the last migration was applied.
LastAppliedMigrationpropertyLast applied migration name.
ModuleNamepropertyModule name.
PendingIndexCountpropertyIndex obligations whose post-start completion has not been recorded.
PendingMigrationspropertyList of pending migrations.
PendingReleaseCountpropertyNumber of pending release migrations.
PendingStartupCountpropertyNumber of pending startup migrations.
SchemaNamepropertySchema name.

constructor MigrationStatus() #

public MigrationStatus()

Creates an instance of MigrationStatus.

property AppliedCount #

public int AppliedCount { get; init; }

Number of applied migrations.

property ChecksumErrors #

public IReadOnlyList<string> ChecksumErrors { get; init; }

Any checksum mismatches detected.

property HasBlockingIssues #

public bool HasBlockingIssues { get; }

Whether there are blocking issues (pending release migrations or checksum errors).

property IsUpToDate #

public bool IsUpToDate { get; }

Whether the database is up to date (no pending startup/release migrations).

property LastAppliedAt #

public DateTimeOffset? LastAppliedAt { get; init; }

When the last migration was applied.

property LastAppliedMigration #

public string? LastAppliedMigration { get; init; }

Last applied migration name.

property ModuleName #

public required string ModuleName { get; init; }

Module name.

property PendingIndexCount #

public int PendingIndexCount { get; init; }

Index obligations whose post-start completion has not been recorded.

property PendingMigrations #

public IReadOnlyList<PendingMigrationInfo> PendingMigrations { get; init; }

List of pending migrations.

property PendingReleaseCount #

public int PendingReleaseCount { get; init; }

Number of pending release migrations.

property PendingStartupCount #

public int PendingStartupCount { get; init; }

Number of pending startup migrations.

property SchemaName #

public required string SchemaName { get; init; }

Schema name.

class MigrationStatusService

public sealed class MigrationStatusService : IMigrationStatusService

Implementation of migration status service.

Members

MemberKindSummary
MigrationStatusService(string, string, string, Assembly, ILogger, string)constructorCreates the status service for the migrations of one assembly.
MigrationStatusService(string, string, string, IReadOnlyList<MigrationAssemblySource>, ILogger)constructorCreates the status service for the migrations of several sources.
GetStatusAsync(CancellationToken)methodGets the current migration status for the module.

constructor MigrationStatusService(string, string, string, Assembly, ILogger, string) #

public MigrationStatusService(string connectionString, string schemaName, string moduleName, Assembly migrationsAssembly, ILogger logger, string? resourcePrefix = null)

Creates the status service for the migrations of one assembly.

Parameters

  • connectionString: The connection string.
  • schemaName: The schema that holds the module’s migration ledger.
  • moduleName: The module, for the log.
  • migrationsAssembly: The assembly that embeds the migrations.
  • logger: The logger.
  • resourcePrefix: Only the resources whose names contain this text, ignoring case; all when not set.

constructor MigrationStatusService(string, string, string, IReadOnlyList<MigrationAssemblySource>, ILogger) #

public MigrationStatusService(string connectionString, string schemaName, string moduleName, IReadOnlyList<MigrationAssemblySource> migrationSources, ILogger logger)

Creates the status service for the migrations of several sources.

Parameters

  • connectionString: The connection string.
  • schemaName: The schema that holds the module’s migration ledger.
  • moduleName: The module, for the log.
  • migrationSources: The migration sources; at least one.
  • logger: The logger.

Exceptions

  • ArgumentException: No source is given.

method GetStatusAsync(CancellationToken) #

public Task<MigrationStatus> GetStatusAsync(CancellationToken cancellationToken = default)

Gets the current migration status for the module.

class MigrationTelemetry

public static class MigrationTelemetry

OpenTelemetry instrumentation for database migrations.

Members

MemberKindSummary
ActivitySourceNameconstantThe name of the activity source for migration tracing.
MeterNameconstantThe name of the meter for migration metrics.
RecordChecksumError(string, string)methodRecords a checksum validation error.
RecordLockAcquired(string, string, double)methodRecords a successful lock acquisition.
RecordLockTimeout(string, string)methodRecords a lock acquisition timeout.
RecordMigrationApplied(string, string, MigrationCategory, double)methodRecords a successful migration application.
RecordMigrationFailed(string, string, MigrationCategory, string)methodRecords a migration failure.
SetActivityError(Activity, Exception)methodSets the error on an activity.
SetActivitySuccess(Activity, int)methodMarks an activity as successful.
StartLockAcquisition(string, string)methodStarts an activity for advisory lock acquisition.
StartMigrationApply(string, string, MigrationCategory)methodStarts an activity for a single migration.
StartMigrationRun(string, string, int)methodStarts an activity for migration execution.

constant ActivitySourceName #

public const string ActivitySourceName = "StellaOps.Infrastructure.Postgres.Migrations"

The name of the activity source for migration tracing.

constant MeterName #

public const string MeterName = "StellaOps.Infrastructure.Postgres.Migrations"

The name of the meter for migration metrics.

method RecordChecksumError(string, string) #

public static void RecordChecksumError(string moduleName, string migrationName)

Records a checksum validation error.

method RecordLockAcquired(string, string, double) #

public static void RecordLockAcquired(string moduleName, string schemaName, double waitSeconds)

Records a successful lock acquisition.

method RecordLockTimeout(string, string) #

public static void RecordLockTimeout(string moduleName, string schemaName)

Records a lock acquisition timeout.

method RecordMigrationApplied(string, string, MigrationCategory, double) #

public static void RecordMigrationApplied(string moduleName, string migrationName, MigrationCategory category, double durationSeconds)

Records a successful migration application.

method RecordMigrationFailed(string, string, MigrationCategory, string) #

public static void RecordMigrationFailed(string moduleName, string migrationName, MigrationCategory category, string errorCode)

Records a migration failure.

method SetActivityError(Activity, Exception) #

public static void SetActivityError(Activity? activity, Exception exception)

Sets the error on an activity.

method SetActivitySuccess(Activity, int) #

public static void SetActivitySuccess(Activity? activity, int appliedCount)

Marks an activity as successful.

method StartLockAcquisition(string, string) #

public static Activity? StartLockAcquisition(string moduleName, string schemaName)

Starts an activity for advisory lock acquisition.

method StartMigrationApply(string, string, MigrationCategory) #

public static Activity? StartMigrationApply(string moduleName, string migrationName, MigrationCategory category)

Starts an activity for a single migration.

method StartMigrationRun(string, string, int) #

public static Activity? StartMigrationRun(string moduleName, string schemaName, int pendingCount)

Starts an activity for migration execution.

class MigrationValidator

public static class MigrationValidator

Validates migration files for naming conventions, duplicates, and ordering issues.

Members

MemberKindSummary
DetectDuplicatePrefixes(IEnumerable<string>)methodDetects migrations with duplicate numeric prefixes.
ExtractNumericPrefix(string)methodExtracts the numeric prefix from a migration name.
Validate(IEnumerable<string>)methodValidates a collection of migration file names.

method DetectDuplicatePrefixes(IEnumerable<string>) #

public static IReadOnlyList<(string Prefix, IReadOnlyList<string> Names)> DetectDuplicatePrefixes(IEnumerable<string> migrationNames)

Detects migrations with duplicate numeric prefixes.

method ExtractNumericPrefix(string) #

public static string? ExtractNumericPrefix(string migrationName)

Extracts the numeric prefix from a migration name.

method Validate(IEnumerable<string>) #

public static MigrationValidator.ValidationResult Validate(IEnumerable<string> migrationNames)

Validates a collection of migration file names.

record MigrationValidator.ValidationError

public sealed record ValidationError

Validation error that will block migration execution.

Parameters

  • Code: The error code.
  • Message: The message.
  • MigrationName: The migration the error concerns; none when it concerns the set.

Members

MemberKindSummary
ValidationError(string, string, string)constructorValidation error that will block migration execution.
CodepropertyThe error code.
MessagepropertyThe message.
MigrationNamepropertyThe migration the error concerns; none when it concerns the set.

constructor ValidationError(string, string, string) #

public ValidationError(string Code, string Message, string? MigrationName = null)

Validation error that will block migration execution.

Parameters

  • Code: The error code.
  • Message: The message.
  • MigrationName: The migration the error concerns; none when it concerns the set.

property Code #

public string Code { get; init; }

The error code.

property Message #

public string Message { get; init; }

The message.

property MigrationName #

public string? MigrationName { get; init; }

The migration the error concerns; none when it concerns the set.

record MigrationValidator.ValidationResult

public sealed record ValidationResult

Validation result for a set of migrations.

Members

MemberKindSummary
ValidationResult()constructorCreates an instance of MigrationValidator.ValidationResult.
ErrorspropertyThe errors.
IsValidpropertyWhether there is no error.
WarningspropertyThe warnings.
Failed(IReadOnlyList<MigrationValidator.ValidationError>, IReadOnlyList<MigrationValidator.ValidationWarning>)methodA result with errors.
Success(IReadOnlyList<MigrationValidator.ValidationWarning>)methodA result without errors.

constructor ValidationResult() #

public ValidationResult()

Creates an instance of MigrationValidator.ValidationResult.

property Errors #

public IReadOnlyList<MigrationValidator.ValidationError> Errors { get; init; }

The errors.

property IsValid #

public bool IsValid { get; }

Whether there is no error.

property Warnings #

public IReadOnlyList<MigrationValidator.ValidationWarning> Warnings { get; init; }

The warnings.

method Failed(IReadOnlyList<MigrationValidator.ValidationError>, IReadOnlyList<MigrationValidator.ValidationWarning>) #

public static MigrationValidator.ValidationResult Failed(IReadOnlyList<MigrationValidator.ValidationError> errors, IReadOnlyList<MigrationValidator.ValidationWarning>? warnings = null)

A result with errors.

Parameters

  • errors: The errors.
  • warnings: The warnings; none when not set.

Returns

The result.

method Success(IReadOnlyList<MigrationValidator.ValidationWarning>) #

public static MigrationValidator.ValidationResult Success(IReadOnlyList<MigrationValidator.ValidationWarning>? warnings = null)

A result without errors.

Parameters

  • warnings: The warnings; none when not set.

Returns

The result.

record MigrationValidator.ValidationWarning

public sealed record ValidationWarning

Validation warning that should be addressed but won’t block execution.

Parameters

  • Code: The warning code.
  • Message: The message.
  • MigrationName: The migration the warning concerns; none when it concerns the set.

Members

MemberKindSummary
ValidationWarning(string, string, string)constructorValidation warning that should be addressed but won’t block execution.
CodepropertyThe warning code.
MessagepropertyThe message.
MigrationNamepropertyThe migration the warning concerns; none when it concerns the set.

constructor ValidationWarning(string, string, string) #

public ValidationWarning(string Code, string Message, string? MigrationName = null)

Validation warning that should be addressed but won’t block execution.

Parameters

  • Code: The warning code.
  • Message: The message.
  • MigrationName: The migration the warning concerns; none when it concerns the set.

property Code #

public string Code { get; init; }

The warning code.

property Message #

public string Message { get; init; }

The message.

property MigrationName #

public string? MigrationName { get; init; }

The migration the warning concerns; none when it concerns the set.

record PendingMigrationInfo

public sealed record PendingMigrationInfo

Information about a pending migration.

Parameters

  • Name: The migration file name.
  • Category: The migration category.

Members

MemberKindSummary
PendingMigrationInfo(string, MigrationCategory)constructorInformation about a pending migration.
CategorypropertyThe migration category.
NamepropertyThe migration file name.

constructor PendingMigrationInfo(string, MigrationCategory) #

public PendingMigrationInfo(string Name, MigrationCategory Category)

Information about a pending migration.

Parameters

  • Name: The migration file name.
  • Category: The migration category.

property Category #

public MigrationCategory Category { get; init; }

The migration category.

property Name #

public string Name { get; init; }

The migration file name.

record RequiredDatabaseRole

public sealed record RequiredDatabaseRole

A PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it.

Parameters

  • Name: The role name, exactly as the module’s SQL expects it (for example orders_admin).
  • Provisioning: One sentence naming the install step that creates the role. It is shown verbatim to the operator in the startup failure, so it must point at a real, current artifact.

Remarks

A schema migration runs as the service’s OWN role, and that role is provisioned NOSUPERUSER NOCREATEDB NOCREATEROLE. It therefore cannot create a role, so a migration must never provision one: role creation belongs to the install/bootstrap path, which runs as the superuser.

An applied migration is immutable (migrations are forward-only), so a migration that carries a guarded IF NOT EXISTS … CREATE ROLE block keeps it. The block is inert wherever the role already exists, and it is a hard boot failure on a from-scratch install whose service role is least-privileged: PostgreSQL answers 42501 permission denied to create role and the host stops at app.Run().

Declaring the role here converts that into a named, actionable startup failure raised BEFORE the baseline is reached, and — because the guard short-circuits once the role exists — pre-creating the role from the install path means the CREATE ROLE statement is never executed at all.

Members

MemberKindSummary
RequiredDatabaseRole(string, string)constructorA PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it.
FailurePrefixconstantThe stable prefix every missing-role failure carries, so operators, log scrapes and tests can tell this apart from the raw 42501 it replaces.
NamepropertyThe role name, exactly as the module’s SQL expects it (for example orders_admin).
ProvisioningpropertyOne sentence naming the install step that creates the role.
FormatMissingMessage(string)methodBuilds the operator-facing message for a role that is absent.

constructor RequiredDatabaseRole(string, string) #

public RequiredDatabaseRole(string Name, string Provisioning)

A PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it.

Parameters

  • Name: The role name, exactly as the module’s SQL expects it (for example orders_admin).
  • Provisioning: One sentence naming the install step that creates the role. It is shown verbatim to the operator in the startup failure, so it must point at a real, current artifact.

Remarks

A schema migration runs as the service’s OWN role, and that role is provisioned NOSUPERUSER NOCREATEDB NOCREATEROLE. It therefore cannot create a role, so a migration must never provision one: role creation belongs to the install/bootstrap path, which runs as the superuser.

An applied migration is immutable (migrations are forward-only), so a migration that carries a guarded IF NOT EXISTS … CREATE ROLE block keeps it. The block is inert wherever the role already exists, and it is a hard boot failure on a from-scratch install whose service role is least-privileged: PostgreSQL answers 42501 permission denied to create role and the host stops at app.Run().

Declaring the role here converts that into a named, actionable startup failure raised BEFORE the baseline is reached, and — because the guard short-circuits once the role exists — pre-creating the role from the install path means the CREATE ROLE statement is never executed at all.

constant FailurePrefix #

public const string FailurePrefix = "Migration preflight"

The stable prefix every missing-role failure carries, so operators, log scrapes and tests can tell this apart from the raw 42501 it replaces.

property Name #

public string Name { get; init; }

The role name, exactly as the module’s SQL expects it (for example orders_admin).

property Provisioning #

public string Provisioning { get; init; }

One sentence naming the install step that creates the role. It is shown verbatim to the operator in the startup failure, so it must point at a real, current artifact.

method FormatMissingMessage(string) #

public string FormatMissingMessage(string moduleName)

Builds the operator-facing message for a role that is absent.

class StartupMigrationHost

public abstract class StartupMigrationHost : IHostedService

Hosted service that runs database migrations at application startup. Uses advisory locks to prevent race conditions in multi-instance deployments.

Remarks

This service: - Acquires an advisory lock to prevent concurrent migrations - Validates checksums of already-applied migrations - Blocks startup if pending release/data migrations exist - Runs only startup migrations automatically; seed migrations remain operator-invoked

Members

MemberKindSummary
StartupMigrationHost(string, string, string, Assembly, ILogger, IHostApplicationLifetime, StartupMigrationOptions)constructorCreates a new startup migration host.
OpenConnectionAsync(CancellationToken)methodOpens the PostgreSQL connection used by the startup migration pass.
StartAsync(CancellationToken)methodSee IHostedService.StartAsync(CancellationToken).
StopAsync(CancellationToken)methodSee IHostedService.StopAsync(CancellationToken).

constructor StartupMigrationHost(string, string, string, Assembly, ILogger, IHostApplicationLifetime, StartupMigrationOptions) #

protected StartupMigrationHost(string connectionString, string schemaName, string moduleName, Assembly migrationsAssembly, ILogger logger, IHostApplicationLifetime lifetime, StartupMigrationOptions? options = null)

Creates a new startup migration host.

method OpenConnectionAsync(CancellationToken) #

protected virtual Task<NpgsqlConnection> OpenConnectionAsync(CancellationToken cancellationToken)

Opens the PostgreSQL connection used by the startup migration pass.

Remarks

This seam keeps transient-startup retry behavior directly testable without weakening the fail-closed handling of migration and authentication errors.

method StartAsync(CancellationToken) #

public Task StartAsync(CancellationToken cancellationToken)

See IHostedService.StartAsync(CancellationToken).

method StopAsync(CancellationToken) #

public Task StopAsync(CancellationToken cancellationToken)

See IHostedService.StopAsync(CancellationToken).

class StartupMigrationOptions

public sealed class StartupMigrationOptions

Options for startup migration behavior.

Members

MemberKindSummary
StartupMigrationOptions()constructorCreates an instance of StartupMigrationOptions.
ChecksumReconciliationPinspropertyOwner-declared reconciliations for databases whose schema_migrations rows were written before the host recorded normalized checksums.
ConnectionRetryDelayMillisecondspropertyDelay between transient PostgreSQL connection attempts.
ConnectionRetryTimeoutSecondspropertyMaximum time to retry transient PostgreSQL connection failures while the database is recovering or starting.
DeferredIndexBuildpropertyOwner-configured budgets for the resumable concurrent index builder.
DeferredIndexespropertyExplicit immutable migration/index contracts whose builds continue after startup.
EnabledpropertyWhether to run migrations at startup.
FailOnChecksumMismatchpropertyWhether to fail startup if checksum validation fails.
FailOnLockTimeoutpropertyWhether to fail startup if lock cannot be acquired.
FailOnMigrationErrorpropertyWhether to fail startup if migration execution fails.
FailOnPendingReleaseMigrationspropertyWhether to fail startup if there are pending release migrations.
LockTimeoutSecondspropertyTimeout in seconds for acquiring the advisory lock.
MigrationTimeoutSecondspropertyTimeout in seconds for individual migration execution.
RequiredRolespropertyPostgreSQL roles the module’s SQL expects to already exist.
ResourcePrefixpropertyOptional embedded-resource prefix used to isolate one migration stream when an assembly contains SQL for multiple modules.
RunSeedMigrationspropertyWhether to apply pending Seed-category migrations at startup.
SqlExecutorpropertyOptional module policy for SQL execution; it never owns migration-ledger or transaction completion.

constructor StartupMigrationOptions() #

public StartupMigrationOptions()

Creates an instance of StartupMigrationOptions.

property ChecksumReconciliationPins #

public IList<MigrationChecksumReconciliationPin> ChecksumReconciliationPins { get; }

Owner-declared reconciliations for databases whose schema_migrations rows were written before the host recorded normalized checksums. Default: none.

Remarks

Only needed for a migration that was edited between the applying build and this one. Comment-only edits made from here on reconcile without a pin, because the applying host records the normalized checksum alongside the whole-file one. Each pin is checked against the file before it is honoured — see MigrationChecksumReconciliationPin.

property ConnectionRetryDelayMilliseconds #

public int ConnectionRetryDelayMilliseconds { get; set; }

Delay between transient PostgreSQL connection attempts. Default: 1000 ms.

property ConnectionRetryTimeoutSeconds #

public int ConnectionRetryTimeoutSeconds { get; set; }

Maximum time to retry transient PostgreSQL connection failures while the database is recovering or starting. Default: 60 seconds. Set to zero to retain single-attempt behavior.

property DeferredIndexBuild #

public DeferredIndexOptions DeferredIndexBuild { get; set; }

Owner-configured budgets for the resumable concurrent index builder.

property DeferredIndexes #

public IList<DeferredIndexDefinition> DeferredIndexes { get; }

Explicit immutable migration/index contracts whose builds continue after startup.

property Enabled #

public bool Enabled { get; set; }

Whether to run migrations at startup. Default: true.

property FailOnChecksumMismatch #

public bool FailOnChecksumMismatch { get; set; }

Whether to fail startup if checksum validation fails. Default: true.

property FailOnLockTimeout #

public bool FailOnLockTimeout { get; set; }

Whether to fail startup if lock cannot be acquired. Default: true.

property FailOnMigrationError #

public bool FailOnMigrationError { get; set; }

Whether to fail startup if migration execution fails. Default: true.

property FailOnPendingReleaseMigrations #

public bool FailOnPendingReleaseMigrations { get; set; }

Whether to fail startup if there are pending release migrations. Default: true.

property LockTimeoutSeconds #

public int LockTimeoutSeconds { get; set; }

Timeout in seconds for acquiring the advisory lock. Default: 120.

property MigrationTimeoutSeconds #

public int MigrationTimeoutSeconds { get; set; }

Timeout in seconds for individual migration execution. Default: 300.

property RequiredRoles #

public IList<RequiredDatabaseRole> RequiredRoles { get; }

PostgreSQL roles the module’s SQL expects to already exist. Verified before any migration runs; an absent role fails startup with the message RequiredDatabaseRole.FormatMissingMessage(string)produces. Default: none.

Remarks

See RequiredDatabaseRolefor why a migration may not provision a role itself. Declaring one here is a fail-closed assertion, never a creation: the host has no more privilege than the service role it connects as.

property ResourcePrefix #

public string? ResourcePrefix { get; set; }

Optional embedded-resource prefix used to isolate one migration stream when an assembly contains SQL for multiple modules. Default: no filter.

property RunSeedMigrations #

public bool RunSeedMigrations { get; set; }

Whether to apply pending Seed-category migrations at startup. Default: false.

Remarks

Seed migrations are normally run only by an operator, so that production deployments do not silently load demonstration data. A host whose seeds are for development or bootstrap only may opt in by setting this to true when it detects an explicit bootstrap-enabled setting of its own. When the flag is left at the default false, the host does not apply seed migrations and logs the “Run manually when needed” guidance line.

property SqlExecutor #

public IMigrationSqlExecutor? SqlExecutor { get; set; }

Optional module policy for SQL execution; it never owns migration-ledger or transaction completion.

namespace StellaOps.Infrastructure.Postgres.Options

TypeKindDescription
PostgresOptionsclassPostgreSQL connection and behavior options.

class PostgresOptions

public sealed class PostgresOptions

PostgreSQL connection and behavior options.

Members

MemberKindSummary
PostgresOptions()constructorCreates an instance of PostgresOptions.
ApplicationNamepropertyStable PostgreSQL application name used for runtime attribution.
AutoMigratepropertyEnable automatic migration on startup.
CommandTimeoutSecondspropertyCommand timeout in seconds.
ConnectionIdleLifetimeSecondspropertyConnection idle lifetime in seconds.
ConnectionStringpropertyPostgreSQL connection string.
MaxPoolSizepropertyMaximum number of connections in the pool.
MigrationsPathpropertyPath to SQL migration files.
MinPoolSizepropertyMinimum number of connections in the pool.
PoolingpropertyEnable connection pooling.
SchemaNamepropertySchema name for module-specific tables.

constructor PostgresOptions() #

public PostgresOptions()

Creates an instance of PostgresOptions.

property ApplicationName #

public string? ApplicationName { get; set; }

Stable PostgreSQL application name used for runtime attribution.

property AutoMigrate #

public bool AutoMigrate { get; set; }

Enable automatic migration on startup. Default is false for production safety.

property CommandTimeoutSeconds #

public int CommandTimeoutSeconds { get; set; }

Command timeout in seconds. Default is 30 seconds.

property ConnectionIdleLifetimeSeconds #

public int ConnectionIdleLifetimeSeconds { get; set; }

Connection idle lifetime in seconds. Default is 300 seconds (5 minutes).

property ConnectionString #

public required string ConnectionString { get; set; }

PostgreSQL connection string.

property MaxPoolSize #

public int MaxPoolSize { get; set; }

Maximum number of connections in the pool. Default is 100.

property MigrationsPath #

public string? MigrationsPath { get; set; }

Path to SQL migration files. Required if AutoMigrate is true.

property MinPoolSize #

public int MinPoolSize { get; set; }

Minimum number of connections in the pool. Default is 1.

property Pooling #

public bool Pooling { get; set; }

Enable connection pooling. Default is true.

property SchemaName #

public string? SchemaName { get; set; }

Schema name for module-specific tables. If null, uses public schema.

namespace StellaOps.Infrastructure.Postgres.Repositories

TypeKindDescription
RepositoryBase<TDataSource>classBase class for PostgreSQL repositories providing common patterns and utilities.

class RepositoryBase<TDataSource>

public abstract class RepositoryBase<TDataSource> where TDataSource : DataSourceBase

Base class for PostgreSQL repositories providing common patterns and utilities.

Type parameters

  • TDataSource: The module-specific data source type.

Members

MemberKindSummary
RepositoryBase(TDataSource, ILogger)constructorCreates a new repository with the specified data source and logger.
CommandTimeoutSecondspropertyCommand timeout from data source options.
DataSourcepropertyThe data source for database connections.
LoggerpropertyLogger for this repository.
AddJsonbParameter(NpgsqlCommand, string, string)methodAdds a typed JSONB parameter to the command.
AddParameter(NpgsqlCommand, string, object)methodAdds a parameter to the command, handling null values.
AddTextArrayParameter(NpgsqlCommand, string, string[])methodAdds a text array parameter to the command.
AddUuidArrayParameter(NpgsqlCommand, string, Guid[])methodAdds a UUID array parameter to the command.
BuildOrderByClause(string, bool, string)methodBuilds ORDER BY clause with deterministic ordering.
BuildPaginationClause(int, int)methodBuilds LIMIT/OFFSET clause for pagination.
BuildWhereClause(params (string condition, string paramName, object value, bool include)[])methodBuilds a dynamic WHERE clause with the specified conditions.
CreateCommand(string, NpgsqlConnection)methodCreates a command with timeout configured.
ExecuteAsync(string, string, Action<NpgsqlCommand>, CancellationToken, string)methodExecutes a non-query command and returns the number of affected rows.
ExecuteInBatchAsync<TResult>(string, Func<NpgsqlConnection, NpgsqlTransaction, Task<TResult>>, CancellationToken, string)methodOpens a single writer connection with the tenant session configured exactly once and begins one transaction, then hands both to body so a caller can run many statements (a batch) on the same connection/transaction instead of paying a connection open + tenant set_config + auto-commit round-trip per statement.
ExecuteScalarAsync<T>(string, string, Action<NpgsqlCommand>, CancellationToken, string)methodExecutes a scalar query and returns the result.
GetNullableBoolean(NpgsqlDataReader, int)methodGets a nullable bool from the reader.
GetNullableDateTimeOffset(NpgsqlDataReader, int)methodGets a nullable DateTimeOffset from the reader.
GetNullableDecimal(NpgsqlDataReader, int)methodGets a nullable decimal from the reader.
GetNullableGuid(NpgsqlDataReader, int)methodGets a nullable Guid from the reader.
GetNullableInt32(NpgsqlDataReader, int)methodGets a nullable int from the reader.
GetNullableInt64(NpgsqlDataReader, int)methodGets a nullable long from the reader.
GetNullableString(NpgsqlDataReader, int)methodGets a nullable string from the reader.
QueryAsync<T>(string, string, Action<NpgsqlCommand>, Func<NpgsqlDataReader, T>, CancellationToken, string)methodExecutes a query and returns all results as a list.
QuerySingleOrDefaultAsync<T>(string, string, Action<NpgsqlCommand>, Func<NpgsqlDataReader, T>, CancellationToken, string)methodExecutes a query and returns a single result or null.

constructor RepositoryBase(TDataSource, ILogger) #

protected RepositoryBase(TDataSource dataSource, ILogger logger)

Creates a new repository with the specified data source and logger.

property CommandTimeoutSeconds #

protected int CommandTimeoutSeconds { get; }

Command timeout from data source options.

property DataSource #

protected TDataSource DataSource { get; }

The data source for database connections.

property Logger #

protected ILogger Logger { get; }

Logger for this repository.

method AddJsonbParameter(NpgsqlCommand, string, string) #

protected static void AddJsonbParameter(NpgsqlCommand command, string name, string? jsonValue)

Adds a typed JSONB parameter to the command.

method AddParameter(NpgsqlCommand, string, object) #

protected static void AddParameter(NpgsqlCommand command, string name, object? value)

Adds a parameter to the command, handling null values.

method AddTextArrayParameter(NpgsqlCommand, string, string[]) #

protected static void AddTextArrayParameter(NpgsqlCommand command, string name, string[]? values)

Adds a text array parameter to the command.

method AddUuidArrayParameter(NpgsqlCommand, string, Guid[]) #

protected static void AddUuidArrayParameter(NpgsqlCommand command, string name, Guid[]? values)

Adds a UUID array parameter to the command.

method BuildOrderByClause(string, bool, string) #

protected static string BuildOrderByClause(string primaryColumn, bool descending = false, string? tiebreaker = "id")

Builds ORDER BY clause with deterministic ordering. Always includes a unique column (typically id) as tiebreaker for pagination stability.

method BuildPaginationClause(int, int) #

protected static string BuildPaginationClause(int limit, int offset)

Builds LIMIT/OFFSET clause for pagination.

method BuildWhereClause(params (string condition, string paramName, object value, bool include)[]) #

protected static (string whereClause, List<(string name, object value)> parameters) BuildWhereClause(params (string condition, string paramName, object? value, bool include)[] conditions)

Builds a dynamic WHERE clause with the specified conditions.

method CreateCommand(string, NpgsqlConnection) #

protected NpgsqlCommand CreateCommand(string sql, NpgsqlConnection connection)

Creates a command with timeout configured.

method ExecuteAsync(string, string, Action<NpgsqlCommand>, CancellationToken, string) #

protected Task<int> ExecuteAsync(string tenantId, string sql, Action<NpgsqlCommand>? configureCommand, CancellationToken cancellationToken, string? callerName = null)

Executes a non-query command and returns the number of affected rows.

method ExecuteInBatchAsync<TResult>(string, Func<NpgsqlConnection, NpgsqlTransaction, Task<TResult>>, CancellationToken, string) #

protected Task<TResult> ExecuteInBatchAsync<TResult>(string tenantId, Func<NpgsqlConnection, NpgsqlTransaction, Task<TResult>> body, CancellationToken cancellationToken, string? callerName = null)

Opens a single writer connection with the tenant session configured exactly once and begins one transaction, then hands both to body so a caller can run many statements (a batch) on the same connection/transaction instead of paying a connection open + tenant set_config + auto-commit round-trip per statement.

Remarks

This is an additive batched path; the per-statement helpers (RepositoryBase<TDataSource>.QueryAsync<T>(string, string, Action<NpgsqlCommand>, Func<NpgsqlDataReader, T>, CancellationToken, string), RepositoryBase<TDataSource>.ExecuteAsync(string, string, Action<NpgsqlCommand>, CancellationToken, string), …) are unchanged and remain the default for single-statement callers. The transaction is committed when body returns and rolled back if it throws, so the caller is responsible for per-item fault isolation (e.g. via savepoints) when a single bad row must not abort the whole batch.

method ExecuteScalarAsync<T>(string, string, Action<NpgsqlCommand>, CancellationToken, string) #

protected Task<T?> ExecuteScalarAsync<T>(string tenantId, string sql, Action<NpgsqlCommand>? configureCommand, CancellationToken cancellationToken, string? callerName = null)

Executes a scalar query and returns the result.

method GetNullableBoolean(NpgsqlDataReader, int) #

protected static bool? GetNullableBoolean(NpgsqlDataReader reader, int ordinal)

Gets a nullable bool from the reader.

method GetNullableDateTimeOffset(NpgsqlDataReader, int) #

protected static DateTimeOffset? GetNullableDateTimeOffset(NpgsqlDataReader reader, int ordinal)

Gets a nullable DateTimeOffset from the reader.

method GetNullableDecimal(NpgsqlDataReader, int) #

protected static decimal? GetNullableDecimal(NpgsqlDataReader reader, int ordinal)

Gets a nullable decimal from the reader.

method GetNullableGuid(NpgsqlDataReader, int) #

protected static Guid? GetNullableGuid(NpgsqlDataReader reader, int ordinal)

Gets a nullable Guid from the reader.

method GetNullableInt32(NpgsqlDataReader, int) #

protected static int? GetNullableInt32(NpgsqlDataReader reader, int ordinal)

Gets a nullable int from the reader.

method GetNullableInt64(NpgsqlDataReader, int) #

protected static long? GetNullableInt64(NpgsqlDataReader reader, int ordinal)

Gets a nullable long from the reader.

method GetNullableString(NpgsqlDataReader, int) #

protected static string? GetNullableString(NpgsqlDataReader reader, int ordinal)

Gets a nullable string from the reader.

method QueryAsync<T>(string, string, Action<NpgsqlCommand>, Func<NpgsqlDataReader, T>, CancellationToken, string) #

protected Task<IReadOnlyList<T>> QueryAsync<T>(string tenantId, string sql, Action<NpgsqlCommand>? configureCommand, Func<NpgsqlDataReader, T> mapRow, CancellationToken cancellationToken, string? callerName = null)

Executes a query and returns all results as a list.

method QuerySingleOrDefaultAsync<T>(string, string, Action<NpgsqlCommand>, Func<NpgsqlDataReader, T>, CancellationToken, string) #

protected Task<T?> QuerySingleOrDefaultAsync<T>(string tenantId, string sql, Action<NpgsqlCommand>? configureCommand, Func<NpgsqlDataReader, T> mapRow, CancellationToken cancellationToken, string? callerName = null) where T : class

Executes a query and returns a single result or null.

namespace StellaOps.Infrastructure.Postgres.Testing

TypeKindDescription
PostgresFixtureclassTest fixture for PostgreSQL integration tests.
PostgresFixtureFactoryclassFactory for creating PostgreSQL test fixtures.

class PostgresFixture

public sealed class PostgresFixture : IAsyncDisposable

Test fixture for PostgreSQL integration tests. Provides connection management and schema setup for tests.

Remarks

Use with Testcontainers or a local PostgreSQL instance. Each test class should create its own schema for isolation.

Members

MemberKindSummary
PostgresFixture(string, string, ILogger)constructorCreates a new PostgreSQL test fixture.
ConnectionStringpropertyConnection string for the test database.
SchemaNamepropertySchema name for test isolation.
CreateOptions()methodCreates PostgreSQL options for the test fixture.
DisposeAsync()methodCleans up the test schema.
ExecuteSqlAsync(string, CancellationToken)methodExecutes raw SQL for test setup.
InitializeAsync(CancellationToken)methodInitializes the test schema.
RunMigrationsAsync(string, string, CancellationToken)methodRuns migrations for the test schema from filesystem path.
RunMigrationsFromAssemblyAsync(Assembly, string, string, CancellationToken)methodRuns migrations for the test schema from embedded resources in an assembly.
RunMigrationsFromAssemblyAsync(Assembly, string, string, MigrationRunOptions, CancellationToken)methodRuns migrations for the test schema from embedded resources in an assembly, with run options.
RunMigrationsFromAssemblyAsync<TAssemblyMarker>(string, string, CancellationToken)methodRuns migrations for the test schema from embedded resources using a type from the assembly.
TruncateAllTablesAsync(CancellationToken)methodTruncates all tables in the test schema for test isolation.

constructor PostgresFixture(string, string, ILogger) #

public PostgresFixture(string connectionString, string schemaName, ILogger? logger = null)

Creates a new PostgreSQL test fixture.

Parameters

  • connectionString: PostgreSQL connection string.
  • schemaName: Unique schema name for test isolation.
  • logger: Optional logger.

property ConnectionString #

public string ConnectionString { get; }

Connection string for the test database.

property SchemaName #

public string SchemaName { get; }

Schema name for test isolation.

method CreateOptions() #

public PostgresOptions CreateOptions()

Creates PostgreSQL options for the test fixture.

method DisposeAsync() #

public ValueTask DisposeAsync()

Cleans up the test schema.

method ExecuteSqlAsync(string, CancellationToken) #

public Task ExecuteSqlAsync(string sql, CancellationToken cancellationToken = default)

Executes raw SQL for test setup.

method InitializeAsync(CancellationToken) #

public Task InitializeAsync(CancellationToken cancellationToken = default)

Initializes the test schema.

method RunMigrationsAsync(string, string, CancellationToken) #

public Task RunMigrationsAsync(string migrationsPath, string moduleName, CancellationToken cancellationToken = default)

Runs migrations for the test schema from filesystem path.

Parameters

  • migrationsPath: Path to migration SQL files.
  • moduleName: Module name for logging.
  • cancellationToken: Cancellation token.

method RunMigrationsFromAssemblyAsync(Assembly, string, string, CancellationToken) #

public Task RunMigrationsFromAssemblyAsync(Assembly assembly, string moduleName, string? resourcePrefix = null, CancellationToken cancellationToken = default)

Runs migrations for the test schema from embedded resources in an assembly.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • moduleName: Module name for logging.
  • resourcePrefix: Optional prefix to filter resources.
  • cancellationToken: Cancellation token.

method RunMigrationsFromAssemblyAsync(Assembly, string, string, MigrationRunOptions, CancellationToken) #

public Task RunMigrationsFromAssemblyAsync(Assembly assembly, string moduleName, string? resourcePrefix, MigrationRunOptions? options, CancellationToken cancellationToken = default)

Runs migrations for the test schema from embedded resources in an assembly, with run options.

Parameters

  • assembly: Assembly containing embedded migration resources.
  • moduleName: Module name for logging.
  • resourcePrefix: Optional text the resource names must contain.
  • options: The run options; the defaults when not set.
  • cancellationToken: Cancellation token.

Returns

A task that completes when the migrations have run.

Exceptions

  • InvalidOperationException: The migrations failed.

method RunMigrationsFromAssemblyAsync<TAssemblyMarker>(string, string, CancellationToken) #

public Task RunMigrationsFromAssemblyAsync<TAssemblyMarker>(string moduleName, string? resourcePrefix = null, CancellationToken cancellationToken = default)

Runs migrations for the test schema from embedded resources using a type from the assembly.

Type parameters

  • TAssemblyMarker: Type from the assembly containing migrations.

Parameters

  • moduleName: Module name for logging.
  • resourcePrefix: Optional prefix to filter resources.
  • cancellationToken: Cancellation token.

method TruncateAllTablesAsync(CancellationToken) #

public Task TruncateAllTablesAsync(CancellationToken cancellationToken = default)

Truncates all tables in the test schema for test isolation.

class PostgresFixtureFactory

public static class PostgresFixtureFactory

Factory for creating PostgreSQL test fixtures.

Members

MemberKindSummary
Create(string, string, ILogger)methodCreates a fixture with a unique schema name based on the test class name.
CreateRandom(string, ILogger)methodCreates a fixture with a random schema name.

method Create(string, string, ILogger) #

public static PostgresFixture Create(string connectionString, string testClassName, ILogger? logger = null)

Creates a fixture with a unique schema name based on the test class name.

Parameters

  • connectionString: PostgreSQL connection string.
  • testClassName: Test class name for schema naming.
  • logger: Optional logger.

method CreateRandom(string, ILogger) #

public static PostgresFixture CreateRandom(string connectionString, ILogger? logger = null)

Creates a fixture with a random schema name.