StellaOps.Infrastructure.Postgres
Shared PostgreSQL infrastructure for StellaOps modules Install Installing Stella Ops packagesWorkflow downloads and signaturesnet10.01.0.1-20261118T121708Zdotnet add package StellaOps.
Namespaces
namespace StellaOps.Infrastructure.Postgres
| Type | Kind | Description |
|---|---|---|
ServiceCollectionExtensions | class | Extension methods for configuring PostgreSQL infrastructure services. |
class ServiceCollectionExtensions
public static class ServiceCollectionExtensions
Extension methods for configuring PostgreSQL infrastructure services.
Members
| Member | Kind | Summary |
|---|---|---|
AddPostgresInfrastructure( | extension method | Adds PostgreSQL infrastructure with the specified options. |
AddPostgresOptions( | extension method | Adds PostgreSQL infrastructure options from configuration. |
extension method AddPostgresInfrastructure(IServiceCollection, Action<PostgresOptions>) #
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) #
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
| Type | Kind | Description |
|---|---|---|
CapacityAssessment | record | The capacity verdict an operator sees, with its evidence. |
CapacityBudgetRegister | class | Reads budgets from the data identity register, the one source of truth for them. |
CapacityBudgetSet | record | Everything one host’s probe measures against, with the register version it came from. |
CapacityCountSession | class | The probe’s READ ONLY transaction as a count sees it. |
CapacityDatabaseBudget | record | A service database’s byte budget, with its shrink-only interim ceiling. |
CapacityDuplicationBudget | record | One duplication line’s budget, read from the register entry’s budget.duplication. |
CapacityDuplicationCount | struct | A count, and whether it stopped at the cap it was given. |
CapacityDuplicationMeasurement | record | One duplication line as measured. |
CapacityEvaluator | class | Turns a measurement into a receipt; pure, so a health check and the probe agree. |
CapacityEventLedgerMeasurement | record | An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.. |
CapacityEventRateBudget | record | An eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.divided by its days. |
CapacityLine | record | One measured value against its lines. |
CapacityMeasurement | record | The host database and its registered tables at one instant. |
CapacityPauseCause | enum | Why a writer gate is closed. |
CapacityReceipt | record | One probe run, as written to <. |
CapacityReceiptAssessment | class | Judges the newest receipt. |
CapacityReceiptWriterGate | class | Closes while the newest receipt shows the database at or above its stop line, while the newest receipt is older than CapacityWriterGateOptions., and while no receipt exists once CapacityWriterGateOptions.after the gate started has passed. |
CapacityTableBudget | record | One registered table’s budget, read from the data-identity register. |
CapacityTableMeasurement | record | One registered table as measured. |
CapacityVerdict | enum | The verdict of a capacity line or receipt. |
CapacityWriterGateDecision | record | Whether a writer may start a cycle, and if not, the reason an operator reads. |
CapacityWriterGateOptions | class | Settings of the capacity writer gate (Capacity:WriterGate). |
CapacityWriterGateServiceCollectionExtensions | class | Registers the capacity writer gate. |
ICapacityDuplicationLine | interface | The owning host’s count for one duplication line. |
ICapacityReceiptStore | interface | Reads and writes one host database’s capacity receipts. |
ICapacityWriterGate | interface | Consulted by a writer before a write cycle. |
PostgresCapacityDuplicationProbe | class | Measures the declared duplication lines with the owning host’s counts. |
PostgresCapacityProbe | class | Catalog-only measurement: pg_ 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. |
PostgresCapacityReceiptStore | class | < 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
| Member | Kind | Summary |
|---|---|---|
CapacityAssessment( | constructor | The capacity verdict an operator sees, with its evidence. |
Evidence | property | The evidence, by key, in key order. |
Message | property | The operator message. |
Verdict | property | The verdict. |
constructor CapacityAssessment(CapacityVerdict, string, IReadOnlyDictionary<string, string>) #
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 #
Evidence #public IReadOnlyDictionary<string, string> Evidence { get; init; }
The evidence, by key, in key order.
property Message #
Message #public string Message { get; init; }
The operator message.
property Verdict #
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.; nothing copies a budget into code or configuration.
Members
| Member | Kind | Summary |
|---|---|---|
InterimHeadroom | constant | Headroom above a pinned measurement before a pinned table reaches its stop line. |
ResourceName | constant | The logical name every host embeds the register under. |
LoadEmbedded( | method | Reads the budgets of a database from the register an assembly embeds under CapacityBudgetRegister.. |
Parse( | method | 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. |
constant InterimHeadroom #
InterimHeadroom #public const readonly decimal InterimHeadroom = 1.05
Headroom above a pinned measurement before a pinned table reaches its stop line.
constant ResourceName #
ResourceName #public const string ResourceName = "StellaOps.Capacity.DataIdentityRegister.json"
The logical name every host embeds the register under.
method LoadEmbedded(Assembly, string) #
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..
Parameters
assembly: The assembly.database: The register’s name for the database.
Returns
The budgets.
Exceptions
Invalid: The assembly does not embed the register, or the register declares no budget for the database.Operation Exception
method Parse(byte[], string) #
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
Invalid: The register declares no budget, or more than one, for the database.Operation Exception
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
| Member | Kind | Summary |
|---|---|---|
CapacityBudgetSet( | constructor | Everything one host’s probe measures against, with the register version it came from. |
Database | property | The database budget. |
Duplication | property | The family’s duplication line budgets, ordered by table and metric. |
EventRates | property | The database’s eventing ledger budgets, ordered by ledger; empty when the register declares none. |
RegisterSha256 | property | The SHA-256 of the register the budgets came from. |
Tables | property | The table budgets, ordered by table. |
constructor CapacityBudgetSet(CapacityDatabaseBudget, IReadOnlyList<CapacityTableBudget>, string, IReadOnlyList<CapacityEventRateBudget>, IReadOnlyList<CapacityDuplicationBudget>) #
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 #
Database #public CapacityDatabaseBudget Database { get; init; }
The database budget.
property Duplication #
Duplication #public IReadOnlyList<CapacityDuplicationBudget>? Duplication { get; init; }
The family’s duplication line budgets, ordered by table and metric.
property EventRates #
EventRates #public IReadOnlyList<CapacityEventRateBudget>? EventRates { get; init; }
The database’s eventing ledger budgets, ordered by ledger; empty when the register declares none.
property RegisterSha256 #
RegisterSha256 #public string RegisterSha256 { get; init; }
The SHA-256 of the register the budgets came from.
property Tables #
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
| Member | Kind | Summary |
|---|---|---|
ClientTimeoutMargin | field | How long a command’s client timeout outlasts the statement timeout, so the server cancels first. |
CommandTimeoutSeconds | property | The client timeout, in whole seconds, every command of this session carries. |
ClientTimeoutSeconds( | method | The statement timeout rounded up to whole seconds, plus CapacityCountSession.. |
CreateCommand( | method | A command in the probe’s transaction whose client timeout outlasts the statement timeout. |
field ClientTimeoutMargin #
ClientTimeoutMargin #public static readonly TimeSpan ClientTimeoutMargin
How long a command’s client timeout outlasts the statement timeout, so the server cancels first.
property CommandTimeoutSeconds #
CommandTimeoutSeconds #public int CommandTimeoutSeconds { get; }
The client timeout, in whole seconds, every command of this session carries.
method ClientTimeoutSeconds(TimeSpan) #
ClientTimeoutSeconds(TimeSpan) #public static int ClientTimeoutSeconds(TimeSpan statementTimeout)
The statement timeout rounded up to whole seconds, plus CapacityCountSession..
method CreateCommand(string) #
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
| Member | Kind | Summary |
|---|---|---|
CapacityDatabaseBudget( | constructor | A service database’s byte budget, with its shrink-only interim ceiling. |
Alarm | property | The alarm line as a ratio of a budget, for every line of the database. |
Bytes | property | The byte budget of the database. |
Database | property | The register’s name for the database. |
Family | property | The service family that owns the database. |
InterimCeilingBytes | property | While set, the database’s stop line (FAIL, writer pause). |
Remediation | property | The work items that own the excess, as the register records them. |
Stop | property | The stop line as a ratio of a budget, for every line of the database. |
constructor CapacityDatabaseBudget(string, string, long, decimal, decimal, long?, IReadOnlyList<string>) #
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 #
Alarm #public decimal Alarm { get; init; }
The alarm line as a ratio of a budget, for every line of the database.
property Bytes #
Bytes #public long Bytes { get; init; }
The byte budget of the database.
property Database #
Database #public string Database { get; init; }
The register’s name for the database.
property Family #
Family #public string Family { get; init; }
The service family that owns the database.
property InterimCeilingBytes #
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 #
Remediation #public IReadOnlyList<string>? Remediation { get; init; }
The work items that own the excess, as the register records them.
property Stop #
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 ofCapacityEvaluator..DuplicationMetrics Budget: The budget.AlarmAt: The declared alarm line; withStopAt, it replaces the database ratios.StopAt: The declared stop line; withAlarmAt, it replaces the database ratios.
Members
| Member | Kind | Summary |
|---|---|---|
CapacityDuplicationBudget( | constructor | One duplication line’s budget, read from the register entry’s budget.duplication. |
AlarmAt | property | The declared alarm line; with StopAt, it replaces the database ratios. |
Budget | property | The budget. |
Metric | property | One of CapacityEvaluator.. |
StopAt | property | The declared stop line; with AlarmAt, it replaces the database ratios. |
Table | property | The register entry that declares the line; the receipt line’s subject. |
constructor CapacityDuplicationBudget(string, string, long, long?, long?) #
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 ofCapacityEvaluator..DuplicationMetrics Budget: The budget.AlarmAt: The declared alarm line; withStopAt, it replaces the database ratios.StopAt: The declared stop line; withAlarmAt, it replaces the database ratios.
property AlarmAt #
AlarmAt #public long? AlarmAt { get; init; }
The declared alarm line; with StopAt, it replaces the database ratios.
property Budget #
Budget #public long Budget { get; init; }
The budget.
property Metric #
Metric #public string Metric { get; init; }
property StopAt #
StopAt #public long? StopAt { get; init; }
The declared stop line; with AlarmAt, it replaces the database ratios.
property Table #
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
| Member | Kind | Summary |
|---|---|---|
CapacityDuplicationCount( | constructor | A count, and whether it stopped at the cap it was given. |
Capped | property | Whether the count stopped at the cap. |
Value | property | The count. |
constructor CapacityDuplicationCount(long, bool) #
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 #
Capped #public bool Capped { get; init; }
Whether the count stopped at the cap.
property Value #
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, soMeasuredis a lower bound.TimedOut: The count ran past the statement timeout and was rolled back; the line is absent.
Members
| Member | Kind | Summary |
|---|---|---|
CapacityDuplicationMeasurement( | constructor | One duplication line as measured. |
Capped | property | The count stopped at its cap, so Measured is a lower bound. |
Measured | property | The count. |
Metric | property | The duplication metric. |
Present | property | Whether the line was counted. |
Table | property | The register entry that declares the line. |
TimedOut | property | The count ran past the statement timeout and was rolled back; the line is absent. |
constructor CapacityDuplicationMeasurement(string, string, bool, long, bool, bool) #
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, soMeasuredis a lower bound.TimedOut: The count ran past the statement timeout and was rolled back; the line is absent.
property Capped #
Capped #public bool Capped { get; init; }
The count stopped at its cap, so Measured is a lower bound.
property Measured #
Measured #public long Measured { get; init; }
The count.
property Metric #
Metric #public string Metric { get; init; }
The duplication metric.
property Present #
Present #public bool Present { get; init; }
Whether the line was counted.
property Table #
Table #public string Table { get; init; }
The register entry that declares the line.
property TimedOut #
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
| Member | Kind | Summary |
|---|---|---|
Bytes | constant | The size metric, in bytes. |
DuplicationMetrics | field | The duplication metrics a register entry may budget (budget.duplication). |
EventRateWindow | field | The trailing window an event rate divides. |
EventsPerDay | constant | The event rate metric, in events per day. |
Generations | constant | Generations present against the declared generation count. |
GrowthPerDay | constant | The growth metric, in bytes per day. |
MinimumGrowthSpan | field | Growth is the byte delta to the previous receipt, normalised to a day. |
OverrideRows | constant | Tenant rows stored where the global row would otherwise serve. |
Rows | constant | The row count metric. |
SupersededCopies | constant | D2: rows of a table beyond one per identity (superseded copies a rule still retains or has not yet reclaimed). |
TombstonesPastRule | constant | Superseded identities whose tombstone is past the entry’s reclaim rule. |
DuplicationThresholds( | method | 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. |
Evaluate( | method | 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.older; and the event rate and duplication lines the measurement carries. |
EventsPerDayFor( | method | Events per day from the rows written in the trailing CapacityEvaluator.. |
constant Bytes #
Bytes #public const string Bytes = "bytes"
The size metric, in bytes.
field DuplicationMetrics #
DuplicationMetrics #public static readonly IReadOnlySet<string> DuplicationMetrics
The duplication metrics a register entry may budget (budget.duplication).
field EventRateWindow #
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 #
EventsPerDay #public const string EventsPerDay = "eventsPerDay"
The event rate metric, in events per day.
constant Generations #
Generations #public const string Generations = "generations"
Generations present against the declared generation count.
constant GrowthPerDay #
GrowthPerDay #public const string GrowthPerDay = "growthPerDay"
The growth metric, in bytes per day.
field MinimumGrowthSpan #
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 #
OverrideRows #public const string OverrideRows = "overrideRows"
Tenant rows stored where the global row would otherwise serve.
constant Rows #
Rows #public const string Rows = "rows"
The row count metric.
constant SupersededCopies #
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 #
TombstonesPastRule #public const string TombstonesPastRule = "tombstonesPastRule"
Superseded identities whose tombstone is past the entry’s reclaim rule.
method DuplicationThresholds(CapacityDuplicationBudget, CapacityDatabaseBudget) #
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) #
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.older; 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) #
EventsPerDayFor(long) #public static long EventsPerDayFor(long windowRows)
Events per day from the rows written in the trailing CapacityEvaluator..
record CapacityEventLedgerMeasurement
public sealed record CapacityEventLedgerMeasurement
An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.. 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
| Member | Kind | Summary |
|---|---|---|
CapacityEventLedgerMeasurement( | constructor | An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.. |
Ledger | property | The ledger. |
Present | property | Whether the ledger exists. |
WindowRows | property | The rows written in the trailing window. |
constructor CapacityEventLedgerMeasurement(string, bool, long) #
CapacityEventLedgerMeasurement(string, bool, long) #public CapacityEventLedgerMeasurement(string Ledger, bool Present, long WindowRows)
An eventing ledger as measured: the rows written in the trailing CapacityEvaluator.. 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 #
Ledger #public string Ledger { get; init; }
The ledger.
property Present #
Present #public bool Present { get; init; }
Whether the ledger exists.
property WindowRows #
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.divided 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.outboxoreventing.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
| Member | Kind | Summary |
|---|---|---|
CapacityEventRateBudget( | constructor | An eventing ledger’s events-per-day budget: eventing.outbox or eventing.inbox, measured as the rows written in the trailing CapacityEvaluator.divided by its days. |
InterimCeilingPerDay | property | While set, the ledger’s stop line: the shrink-only ceiling over a window that still holds a known burst. |
Ledger | property | The ledger: eventing.outbox or eventing.inbox. |
PerDay | property | The events-per-day budget. |
constructor CapacityEventRateBudget(string, long, long?) #
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.divided 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.outboxoreventing.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 #
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 #
Ledger #public string Ledger { get; init; }
The ledger: eventing.outbox or eventing.inbox.
property PerDay #
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., a qualified table name or an eventing ledger.DatabaseSubject Metric:bytes,rows,growthPerDay(bytes per day),eventsPerDayor 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: ForeventsPerDay: the rows written in the trailing window the rate divides.Capped: For a duplication line: the count stopped at the stop line, soMeasuredis a lower bound.
Members
| Member | Kind | Summary |
|---|---|---|
CapacityLine( | constructor | One measured value against its lines. |
DatabaseSubject | constant | The subject of the database line. |
AlarmAt | property | The alarm line. |
Budget | property | The budget. |
Capped | property | For a duplication line: the count stopped at the stop line, so Measured is a lower bound. |
Interim | property | The stop line is an interim ceiling or a pinned measurement, not the owner budget. |
Measured | property | The measured value. |
Metric | property | bytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.). |
StopAt | property | The stop line; none for a metric that can only warn. |
Subject | property | CapacityLine., a qualified table name or an eventing ledger. |
Verdict | property | CapacityVerdict.at or above the stop line, CapacityVerdict.at or above the alarm line, else CapacityVerdict.. |
WindowRows | property | For eventsPerDay: the rows written in the trailing window the rate divides. |
constructor CapacityLine(string, string, long, long, long, long?, bool, long?, bool) #
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., a qualified table name or an eventing ledger.DatabaseSubject Metric:bytes,rows,growthPerDay(bytes per day),eventsPerDayor 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: ForeventsPerDay: the rows written in the trailing window the rate divides.Capped: For a duplication line: the count stopped at the stop line, soMeasuredis a lower bound.
constant DatabaseSubject #
DatabaseSubject #public const string DatabaseSubject = "database"
The subject of the database line.
property AlarmAt #
AlarmAt #public long AlarmAt { get; init; }
The alarm line.
property Budget #
Budget #public long Budget { get; init; }
The budget.
property Capped #
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 #
Interim #public bool Interim { get; init; }
The stop line is an interim ceiling or a pinned measurement, not the owner budget.
property Measured #
Measured #public long Measured { get; init; }
The measured value.
property Metric #
Metric #public string Metric { get; init; }
bytes, rows, growthPerDay (bytes per day), eventsPerDay or a duplication metric (CapacityEvaluator.).
property StopAt #
StopAt #public long? StopAt { get; init; }
The stop line; none for a metric that can only warn.
property Subject #
Subject #public string Subject { get; init; }
CapacityLine., a qualified table name or an eventing ledger.
property Verdict #
Verdict #public CapacityVerdict Verdict { get; }
CapacityVerdict.at or above the stop line, CapacityVerdict.at or above the alarm line, else CapacityVerdict..
property WindowRows #
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
| Member | Kind | Summary |
|---|---|---|
CapacityMeasurement( | constructor | The host database and its registered tables at one instant. |
Database | property | The physical database the connection reached (current_database()). |
DatabaseBytes | property | The database size, in bytes (pg_database_size). |
Duplication | property | The duplication lines’ counts; null when the caller measured none. |
EventLedgers | property | The eventing ledgers’ trailing-window counts; null when the caller measured no event rate. |
Tables | property | The registered tables as measured. |
constructor CapacityMeasurement(string, long, IReadOnlyList<CapacityTableMeasurement>, IReadOnlyList<CapacityEventLedgerMeasurement>, IReadOnlyList<CapacityDuplicationMeasurement>) #
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 #
Database #public string Database { get; init; }
The physical database the connection reached (current_database()).
property DatabaseBytes #
DatabaseBytes #public long DatabaseBytes { get; init; }
The database size, in bytes (pg_database_size).
property Duplication #
Duplication #public IReadOnlyList<CapacityDuplicationMeasurement>? Duplication { get; init; }
The duplication lines’ counts; null when the caller measured none.
property EventLedgers #
EventLedgers #public IReadOnlyList<CapacityEventLedgerMeasurement>? EventLedgers { get; init; }
The eventing ledgers’ trailing-window counts; null when the caller measured no event rate.
property Tables #
Tables #public IReadOnlyList<CapacityTableMeasurement> Tables { get; init; }
The registered tables as measured.
enum CapacityPauseCause
public enum CapacityPauseCause
Why a writer gate is closed.
| Value | Description |
|---|---|
None = 0 | The gate is open. |
StopLine = 1 | The newest receipt shows the database at or above its stop line. |
StaleReceipt = 2 | The newest receipt is older than CapacityWriterGateOptions.. |
NoReceipt = 3 | No receipt exists once CapacityWriterGateOptions.has passed. |
record CapacityReceipt
public sealed record CapacityReceipt
One probe run, as written to <.
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
| Member | Kind | Summary |
|---|---|---|
CapacityReceipt( | constructor | One probe run, as written to <. |
AbsentTables | property | The required subjects that were not measured: tables, ledgers and duplication lines. |
BudgetDatabase | property | The register’s name for the database (the budget key). |
DatabaseLine | property | The bytes line of the database. |
DuplicationLines | property | The duplication lines, ordered by table and metric. |
EventRateLines | property | The eventing ledgers’ events-per-day lines, ordered by ledger. |
Lines | property | The measured lines. |
PhysicalDatabase | property | The database the probe actually measured. |
ProbedAt | property | When the probe measured. |
ReceiptId | property | The id the store assigned; none before the receipt is stored. |
RegisterSha256 | property | The SHA-256 of the register the budgets came from. |
Remediation | property | The work items the register names as owning the database’s excess. |
RemediationText | property | The remediation rows by name, or the statement that none owns the excess. |
Summary | property | The one-line operator summary the probe logs and stores. |
Verdict | property | CapacityVerdict.when a required subject was not measured; otherwise the worst line verdict, and CapacityVerdict.without lines. |
WriterPause | property | The 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>) #
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 <.
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 #
AbsentTables #public IReadOnlyList<string> AbsentTables { get; init; }
The required subjects that were not measured: tables, ledgers and duplication lines.
property BudgetDatabase #
BudgetDatabase #public string BudgetDatabase { get; init; }
The register’s name for the database (the budget key).
property DatabaseLine #
DatabaseLine #public CapacityLine DatabaseLine { get; }
The bytes line of the database.
property DuplicationLines #
DuplicationLines #public IReadOnlyList<CapacityLine> DuplicationLines { get; }
The duplication lines, ordered by table and metric.
property EventRateLines #
EventRateLines #public IReadOnlyList<CapacityLine> EventRateLines { get; }
The eventing ledgers’ events-per-day lines, ordered by ledger.
property Lines #
Lines #public IReadOnlyList<CapacityLine> Lines { get; init; }
The measured lines.
property PhysicalDatabase #
PhysicalDatabase #public string PhysicalDatabase { get; init; }
The database the probe actually measured.
property ProbedAt #
ProbedAt #public DateTimeOffset ProbedAt { get; init; }
When the probe measured.
property ReceiptId #
ReceiptId #public long? ReceiptId { get; init; }
The id the store assigned; none before the receipt is stored.
property RegisterSha256 #
RegisterSha256 #public string RegisterSha256 { get; init; }
The SHA-256 of the register the budgets came from.
property Remediation #
Remediation #public IReadOnlyList<string>? Remediation { get; init; }
The work items the register names as owning the database’s excess.
property RemediationText #
RemediationText #public string RemediationText { get; }
The remediation rows by name, or the statement that none owns the excess.
property Summary #
Summary #public string Summary { get; }
The one-line operator summary the probe logs and stores.
property Verdict #
Verdict #public CapacityVerdict Verdict { get; }
CapacityVerdict.when a required subject was not measured; otherwise the worst line verdict, and CapacityVerdict.without lines.
property WriterPause #
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.both 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
| Member | Kind | Summary |
|---|---|---|
MaximumReceiptAge | field | The age after which a receipt fails: 36 hours. |
Assess( | method | Judges the newest receipt of a database: CapacityVerdict.without a receipt or with one older than CapacityReceiptAssessment.; otherwise the receipt’s verdict, with the message and the evidence an operator sees. |
field MaximumReceiptAge #
MaximumReceiptAge #public static readonly TimeSpan MaximumReceiptAge
The age after which a receipt fails: 36 hours.
method Assess(string, CapacityReceipt, DateTimeOffset) #
Assess(string, CapacityReceipt, DateTimeOffset) #public static CapacityAssessment Assess(string database, CapacityReceipt? newest, DateTimeOffset now)
Judges the newest receipt of a database: CapacityVerdict.without a receipt or with one older than CapacityReceiptAssessment.; 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., and while no receipt exists once CapacityWriterGateOptions.after 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
| Member | Kind | Summary |
|---|---|---|
CapacityReceiptWriterGate( | constructor | Creates the gate; the grace for a missing receipt counts from this moment. |
EvaluateAsync( | method | Reads the newest receipt and decides. |
constructor CapacityReceiptWriterGate(ICapacityReceiptStore, string, ILogger, TimeProvider, CapacityWriterGateOptions) #
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
Argument: The store or the logger is null.Null Exception ArgumentException: The writer is empty, the staleness bound is not positive or the grace is negative.
method EvaluateAsync(CancellationToken) #
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 coversbudgetholds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plusCapacityBudgetRegister.. Applies whileInterimHeadroom 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 forInterimBytes.InterimUntil: The pin’s sunset: the interim stop lines apply through this day.
Members
| Member | Kind | Summary |
|---|---|---|
CapacityTableBudget( | constructor | One registered table’s budget, read from the data-identity register. |
Bytes | property | The byte budget. |
GrowthPerDay | property | The growth budget, in bytes per day; it is the alarm line of the growth line, which has no stop line. |
InterimBytes | property | 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.. |
InterimRows | property | The row stop line the pin holds the table at, as for InterimBytes. |
InterimUntil | property | The pin’s sunset: the interim stop lines apply through this day. |
Rows | property | The row budget. |
Table | property | The qualified table name. |
constructor CapacityTableBudget(string, long, long, long, long?, long?, DateOnly?) #
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 coversbudgetholds the table at: the pin’s declared interim ceiling (for example a designed generation peak), else its pinned measurement plusCapacityBudgetRegister.. Applies whileInterimHeadroom 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 forInterimBytes.InterimUntil: The pin’s sunset: the interim stop lines apply through this day.
property Bytes #
Bytes #public long Bytes { get; init; }
The byte budget.
property GrowthPerDay #
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 #
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.. 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 #
InterimRows #public long? InterimRows { get; init; }
The row stop line the pin holds the table at, as for InterimBytes.
property InterimUntil #
InterimUntil #public DateOnly? InterimUntil { get; init; }
The pin’s sunset: the interim stop lines apply through this day.
property Rows #
Rows #public long Rows { get; init; }
The row budget.
property Table #
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_); a partitioned table sums its partitions.total_ relation_ size Rows: The estimated row count (pg_class.reltuples).
Members
| Member | Kind | Summary |
|---|---|---|
CapacityTableMeasurement( | constructor | One registered table as measured. |
Bytes | property | The total size with indexes (pg_); a partitioned table sums its partitions. |
Present | property | Whether the table exists. |
Rows | property | The estimated row count (pg_class.reltuples). |
Table | property | The qualified table name. |
constructor CapacityTableMeasurement(string, bool, long, long) #
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_); a partitioned table sums its partitions.total_ relation_ size Rows: The estimated row count (pg_class.reltuples).
property Bytes #
Bytes #public long Bytes { get; init; }
The total size with indexes (pg_); a partitioned table sums its partitions.
property Present #
Present #public bool Present { get; init; }
Whether the table exists.
property Rows #
Rows #public long Rows { get; init; }
The estimated row count (pg_class.reltuples).
property Table #
Table #public string Table { get; init; }
The qualified table name.
enum CapacityVerdict
public enum CapacityVerdict
The verdict of a capacity line or receipt.
| Value | Description |
|---|---|
Pass = 0 | Below the alarm line. |
Warn = 1 | At or above the alarm line, below the stop line. |
Fail = 2 | At 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
| Member | Kind | Summary |
|---|---|---|
CapacityWriterGateDecision( | constructor | Whether a writer may start a cycle, and if not, the reason an operator reads. |
Open | field | The open gate: writers write. |
Cause | property | The cause of the pause. |
Paused | property | Whether writers must pause. |
Reason | property | Why they pause; none when the gate is open. |
constructor CapacityWriterGateDecision(bool, string, CapacityPauseCause) #
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 #
Open #public static readonly CapacityWriterGateDecision Open
The open gate: writers write.
property Cause #
Cause #public CapacityPauseCause Cause { get; init; }
The cause of the pause.
property Paused #
Paused #public bool Paused { get; init; }
Whether writers must pause.
property Reason #
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
| Member | Kind | Summary |
|---|---|---|
CapacityWriterGateOptions( | constructor | Creates an instance of Capacity. |
SectionName | constant | The configuration section the options bind from: Capacity:WriterGate. |
StaleAfter | property | A newest receipt older than this closes the gate (“capacity unmeasured”). |
UnmeasuredGrace | property | 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). |
IsValid( | method | Whether the options are usable: CapacityWriterGateOptions.positive and CapacityWriterGateOptions.not negative. |
constructor CapacityWriterGateOptions() #
CapacityWriterGateOptions() #public CapacityWriterGateOptions()
Creates an instance of Capacity.
constant SectionName #
SectionName #public const string SectionName = "Capacity:WriterGate"
The configuration section the options bind from: Capacity:WriterGate.
property StaleAfter #
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 #
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() #
IsValid() #public bool IsValid()
Whether the options are usable: CapacityWriterGateOptions.positive and CapacityWriterGateOptions.not negative.
Returns
true when the options are usable.
class CapacityWriterGateServiceCollectionExtensions
public static class CapacityWriterGateServiceCollectionExtensions
Registers the capacity writer gate.
Members
| Member | Kind | Summary |
|---|---|---|
AddCapacityWriterGate( | extension method | Registers the host’s writer gate over its database’s receipt store, with CapacityWriterGateOptionsbound from CapacityWriterGateOptions.. |
extension method AddCapacityWriterGate(IServiceCollection, IConfiguration, string, Func<IServiceProvider, ICapacityReceiptStore>) #
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.. 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., 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.), with commands from the CapacityCountSessionit is handed, and must write nothing; it may set transaction-local settings (a tenant context) with set_.
Members
| Member | Kind | Summary |
|---|---|---|
Metric | property | One of CapacityEvaluator.. |
RequiredIndex | property | The index the count walks, schema-qualified. |
Table | property | The register entry that declares the line. |
CountAsync( | method | Counts the line, stopping at the cap. |
property Metric #
Metric #string Metric { get; }
property RequiredIndex #
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 #
Table #string Table { get; }
The register entry that declares the line.
method CountAsync(CapacityCountSession, long, DateTimeOffset, CancellationToken) #
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
| Member | Kind | Summary |
|---|---|---|
BudgetDatabase | property | The register’s name for the database these receipts describe. |
AppendAsync( | method | Appends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction. |
ReadNewestAsync( | method | The newest receipt, or null when none exists (or the receipt table is not there yet). |
property BudgetDatabase #
BudgetDatabase #string BudgetDatabase { get; }
The register’s name for the database these receipts describe.
method AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
EvaluateAsync( | method | Decides whether writers must pause. |
method EvaluateAsync(CancellationToken) #
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
| Member | Kind | Summary |
|---|---|---|
ApplyPostureAsync( | method | 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). |
MeasureAsync( | method | One READ ONLY transaction, rolled back. |
method ApplyPostureAsync(NpgsqlConnection, NpgsqlTransaction, TimeSpan, CancellationToken) #
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) #
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.), 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_ 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
| Member | Kind | Summary |
|---|---|---|
DefaultStatementTimeout | field | The default statement timeout of a measurement: 60 seconds. |
MeasureAsync( | method | Measures the database and the named tables in one READ ONLY transaction under a statement timeout. |
field DefaultStatementTimeout #
DefaultStatementTimeout #public static readonly TimeSpan DefaultStatementTimeout
The default statement timeout of a measurement: 60 seconds.
method MeasureAsync(NpgsqlDataSource, IReadOnlyCollection<string>, TimeSpan, CancellationToken) #
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
Argument: The timeout is not positive.Out Of Range Exception
class PostgresCapacityReceiptStore
public sealed class PostgresCapacityReceiptStore : ICapacityReceiptStore
< in the host’s own database. Each owning family creates the table and its prune_ function in its own forward-only migration; the retained count is that function’s default, so it has one source.
Members
| Member | Kind | Summary |
|---|---|---|
PostgresCapacityReceiptStore( | constructor | Creates the store for a schema of the host database. |
PruneFunctionName | constant | The function that reclaims the oldest receipts. |
TableName | constant | The receipt table. |
BudgetDatabase | property | The register’s name for the database these receipts describe. |
AppendAsync( | method | Appends a receipt and reclaims the oldest beyond the family migration’s retained count, in one transaction. |
ReadNewestAsync( | method | The newest receipt, or null when none exists (or the receipt table is not there yet). |
constructor PostgresCapacityReceiptStore(NpgsqlDataSource, string, string) #
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 #
PruneFunctionName #public const string PruneFunctionName = "prune_capacity_probe_receipts"
The function that reclaims the oldest receipts.
constant TableName #
TableName #public const string TableName = "capacity_probe_receipt"
The receipt table.
property BudgetDatabase #
BudgetDatabase #public string BudgetDatabase { get; }
The register’s name for the database these receipts describe.
method AppendAsync(CapacityReceipt, Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, Task>, CancellationToken) #
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) #
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
| Type | Kind | Description |
|---|---|---|
DataSourceBase | class | Base class for module-specific PostgreSQL data sources. |
PostgresConnectionStringPolicy | class | Applies 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: Orders
Members
| Member | Kind | Summary |
|---|---|---|
DataSourceBase( | constructor | Creates a new data source with the specified options. |
CommandTimeoutSeconds | property | Command timeout in seconds from options. |
ModuleName | property | Module name for logging and metrics. |
Options | property | PostgreSQL options for this data source. |
SchemaName | property | Schema name for this module’s tables. |
ConfigureDataSourceBuilder( | method | Override to configure additional NpgsqlDataSourceBuilder options. |
ConfigureSessionAsync( | method | Override to add custom session configuration. |
ConfigureSystemSessionAsync( | method | Override to add custom system session configuration. |
DisposeAsync( | method | Disposes the data source and releases all pooled connections. |
OnConnectionClosed( | method | Override to handle connection closed events for metrics. |
OnConnectionOpened( | method | Override to handle connection opened events for metrics. |
OpenConnectionAsync( | method | Opens a connection with tenant context configured. |
OpenConnectionAsync( | method | Opens a connection with tenant context and role label configured. |
OpenSystemConnectionAsync( | method | Opens a connection for system operations without tenant context. |
constructor DataSourceBase(PostgresOptions, ILogger) #
DataSourceBase(PostgresOptions, ILogger) #protected DataSourceBase(PostgresOptions options, ILogger logger)
Creates a new data source with the specified options.
property CommandTimeoutSeconds #
CommandTimeoutSeconds #public int CommandTimeoutSeconds { get; }
Command timeout in seconds from options.
property ModuleName #
ModuleName #protected abstract string ModuleName { get; }
Module name for logging and metrics.
property Options #
Options #protected PostgresOptions Options { get; }
PostgreSQL options for this data source.
property SchemaName #
SchemaName #public string? SchemaName { get; }
Schema name for this module’s tables.
method ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder) #
ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder) #protected virtual void ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder builder)
Override to configure additional NpgsqlDataSourceBuilder options.
method ConfigureSessionAsync(NpgsqlConnection, string, CancellationToken) #
ConfigureSessionAsync(NpgsqlConnection, string, CancellationToken) #protected virtual Task ConfigureSessionAsync(NpgsqlConnection connection, string tenantId, CancellationToken cancellationToken)
Override to add custom session configuration.
method ConfigureSystemSessionAsync(NpgsqlConnection, CancellationToken) #
ConfigureSystemSessionAsync(NpgsqlConnection, CancellationToken) #protected virtual Task ConfigureSystemSessionAsync(NpgsqlConnection connection, CancellationToken cancellationToken)
Override to add custom system session configuration.
method DisposeAsync() #
DisposeAsync() #public ValueTask DisposeAsync()
Disposes the data source and releases all pooled connections.
method OnConnectionClosed(string) #
OnConnectionClosed(string) #protected virtual void OnConnectionClosed(string role)
Override to handle connection closed events for metrics.
method OnConnectionOpened(string) #
OnConnectionOpened(string) #protected virtual void OnConnectionOpened(string role)
Override to handle connection opened events for metrics.
method OpenConnectionAsync(string, CancellationToken) #
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) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
Build( | method | 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. |
Build( | method | Applies the runtime attribution and pooling policy to a raw connection string. |
BuildDefaultApplicationName( | method | The default application name of a module: stellaops- and the module name in lower-case kebab case. |
method Build(PostgresOptions, string) #
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.default: The application name when the options set none.Application Name
Returns
The connection string.
method Build(string, string, bool?, int?, int?, int?) #
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) #
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
| Type | Kind | Description |
|---|---|---|
PostgresExceptionHelper | class | Helper methods for handling PostgreSQL exceptions. |
class PostgresExceptionHelper
public static class PostgresExceptionHelper
Helper methods for handling PostgreSQL exceptions.
Members
| Member | Kind | Summary |
|---|---|---|
CheckViolation | constant | PostgreSQL error code for check constraint violation. |
DeadlockDetected | constant | PostgreSQL error code for deadlock detected (retry needed). |
ForeignKeyViolation | constant | PostgreSQL error code for foreign key violation. |
NotNullViolation | constant | PostgreSQL error code for not null violation. |
SerializationFailure | constant | PostgreSQL error code for serialization failure (retry needed). |
UniqueViolation | constant | PostgreSQL error code for unique constraint violation. |
IsCheckViolation( | method | Checks if the exception is a check constraint violation. |
IsForeignKeyViolation( | method | Checks if the exception is a foreign key violation. |
IsNotNullViolation( | method | Checks if the exception is a not null violation. |
IsRetryable( | method | Checks if any exception in the chain is retryable. |
IsRetryable( | method | Checks if the exception is retryable (serialization failure or deadlock). |
IsUniqueViolation( | method | Checks if the exception is a unique constraint violation. |
IsUniqueViolation( | method | Checks if the exception is a unique constraint violation for a specific constraint. |
constant CheckViolation #
CheckViolation #public const string CheckViolation = "23514"
PostgreSQL error code for check constraint violation.
constant DeadlockDetected #
DeadlockDetected #public const string DeadlockDetected = "40P01"
PostgreSQL error code for deadlock detected (retry needed).
constant ForeignKeyViolation #
ForeignKeyViolation #public const string ForeignKeyViolation = "23503"
PostgreSQL error code for foreign key violation.
constant NotNullViolation #
NotNullViolation #public const string NotNullViolation = "23502"
PostgreSQL error code for not null violation.
constant SerializationFailure #
SerializationFailure #public const string SerializationFailure = "40001"
PostgreSQL error code for serialization failure (retry needed).
constant UniqueViolation #
UniqueViolation #public const string UniqueViolation = "23505"
PostgreSQL error code for unique constraint violation.
method IsCheckViolation(PostgresException) #
IsCheckViolation(PostgresException) #public static bool IsCheckViolation(PostgresException ex)
Checks if the exception is a check constraint violation.
method IsForeignKeyViolation(PostgresException) #
IsForeignKeyViolation(PostgresException) #public static bool IsForeignKeyViolation(PostgresException ex)
Checks if the exception is a foreign key violation.
method IsNotNullViolation(PostgresException) #
IsNotNullViolation(PostgresException) #public static bool IsNotNullViolation(PostgresException ex)
Checks if the exception is a not null violation.
method IsRetryable(Exception) #
IsRetryable(Exception) #public static bool IsRetryable(Exception ex)
Checks if any exception in the chain is retryable.
method IsRetryable(PostgresException) #
IsRetryable(PostgresException) #public static bool IsRetryable(PostgresException ex)
Checks if the exception is retryable (serialization failure or deadlock).
method IsUniqueViolation(PostgresException) #
IsUniqueViolation(PostgresException) #public static bool IsUniqueViolation(PostgresException ex)
Checks if the exception is a unique constraint violation.
method IsUniqueViolation(PostgresException, string) #
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
| Type | Kind | Description |
|---|---|---|
AppliedMigrationDetail | record | Details of an applied migration. |
DeferredIndexBuilder | class | Resumes declared concurrent index builds after the host starts. |
DeferredIndexDefinition | record | Owner-reviewed deferral of exactly one index statement in an immutable startup migration. |
DeferredIndexNotReadyException | class | An index-dependent operation is temporarily unavailable while maintenance converges. |
DeferredIndexOptions | class | Bounded post-start maintenance budgets, bindable through the owner’s configuration. |
IMigrationRunner | interface | Interface for running database migrations. |
IMigrationSqlExecutor | interface | Optional module-owned SQL execution policy. |
IMigrationStatusService | interface | Service for querying migration status without applying migrations. |
MigrationAssemblySource | record | Migration source descriptor (assembly + optional resource prefix). |
MigrationCategory | enum | Categorizes migrations by when they should be executed. |
MigrationCategoryExtensions | class | Extension methods for migration category operations. |
MigrationChecksum | class | Canonical checksum computation for migration SQL content. |
MigrationChecksumReconciliationPin | record | 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. |
MigrationInfo | struct | Information about an applied migration. |
MigrationReconciliationReason | class | Why a recorded migration checksum was rewritten without re-running the migration. |
MigrationResult | class | Result of a migration execution. |
MigrationRunOptions | class | Options for migration execution. |
MigrationRunner | class | Runs PostgreSQL migrations from filesystem or embedded resources with advisory-lock coordination. |
MigrationServiceExtensions | class | Extension methods for registering migration services. |
MigrationSqlExecutionContext | record | The existing runner-owned connection and transaction for one immutable SQL file. |
MigrationSqlNormalizer | class | 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. |
MigrationStatus | record | Current migration status for a module. |
MigrationStatusService | class | Implementation of migration status service. |
MigrationTelemetry | class | OpenTelemetry instrumentation for database migrations. |
MigrationValidator | class | Validates migration files for naming conventions, duplicates, and ordering issues. |
MigrationValidator. | record | Validation error that will block migration execution. |
MigrationValidator. | record | Validation result for a set of migrations. |
MigrationValidator. | record | Validation warning that should be addressed but won’t block execution. |
PendingMigrationInfo | record | Information about a pending migration. |
RequiredDatabaseRole | record | A PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it. |
StartupMigrationHost | class | Hosted service that runs database migrations at application startup. |
StartupMigrationOptions | class | Options 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
| Member | Kind | Summary |
|---|---|---|
AppliedMigrationDetail( | constructor | Details of an applied migration. |
Category | property | The migration category. |
DurationMs | property | How long it ran, in milliseconds. |
Name | property | The migration file name. |
WasDryRun | property | Whether it was a dry run, which applies nothing. |
constructor AppliedMigrationDetail(string, MigrationCategory, long, bool) #
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 #
Category #public MigrationCategory Category { get; init; }
The migration category.
property DurationMs #
DurationMs #public long DurationMs { get; init; }
How long it ran, in milliseconds.
property Name #
Name #public string Name { get; init; }
The migration file name.
property WasDryRun #
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
| Member | Kind | Summary |
|---|---|---|
DeferredIndexBuilder( | constructor | Resumes declared concurrent index builds after the host starts. |
RunPassAsync( | method | Attempts each due declared index once; also used by disposable-database convergence tests. |
constructor DeferredIndexBuilder(string, string, IReadOnlyList<DeferredIndexDefinition>, DeferredIndexOptions, IHostApplicationLifetime, ILogger) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
DeferredIndexDefinition( | constructor | Owner-reviewed deferral of exactly one index statement in an immutable startup migration. |
CatalogDefinition | property | The definition the catalog reports for the built index (pg_get_indexdef). |
IndexName | property | The index name. |
IndexSchema | property | The schema of the index. |
IndexStatement | property | The index statement, as the migration writes it. |
MigrationChecksum | property | The checksum of the migration, its ledger identity. |
MigrationName | property | The migration that holds the index statement. |
TableName | property | The table of the index. |
IsReadyAsync( | method | Checks the actual relation, table, definition and PostgreSQL validity flags. |
RemoveFrom( | method | Validates the pinned input and returns only the non-deferred SQL. |
RequireReadyAsync( | method | Refuses an index-dependent query before it can scan the unindexed table. |
constructor DeferredIndexDefinition(string, string, string, string, string, string, string) #
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 #
CatalogDefinition #public string CatalogDefinition { get; init; }
The definition the catalog reports for the built index (pg_get_indexdef).
property IndexName #
IndexName #public string IndexName { get; init; }
The index name.
property IndexSchema #
IndexSchema #public string IndexSchema { get; init; }
The schema of the index.
property IndexStatement #
IndexStatement #public string IndexStatement { get; init; }
The index statement, as the migration writes it.
property MigrationChecksum #
MigrationChecksum #public string MigrationChecksum { get; init; }
The checksum of the migration, its ledger identity.
property MigrationName #
MigrationName #public string MigrationName { get; init; }
The migration that holds the index statement.
property TableName #
TableName #public string TableName { get; init; }
The table of the index.
method IsReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken) #
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) #
RemoveFrom(string) #public string RemoveFrom(string migrationSql)
Validates the pinned input and returns only the non-deferred SQL.
method RequireReadyAsync(NpgsqlConnection, NpgsqlTransaction, CancellationToken) #
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
| Member | Kind | Summary |
|---|---|---|
DeferredIndexNotReadyException( | constructor | An index-dependent operation is temporarily unavailable while maintenance converges. |
constructor DeferredIndexNotReadyException(string, string) #
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
| Member | Kind | Summary |
|---|---|---|
DeferredIndexOptions( | constructor | Creates an instance of DeferredIndexOptions. |
BuildTimeoutSeconds | property | The statement timeout of one index build, in seconds, from 1 to 86400. |
LockTimeoutSeconds | property | The lock timeout of one index build, in seconds, from 1 to 300. |
MaxRetryDelaySeconds | property | The longest retry delay, in seconds, from DeferredIndexOptions.to 86400. |
PollIntervalSeconds | property | The pause between two checks for pending index builds, in seconds, from 1 to 300. |
RetryDelaySeconds | property | The delay before the first retry of a failed build, in seconds, from 1 to 86400; it doubles for each further retry. |
constructor DeferredIndexOptions() #
DeferredIndexOptions() #public DeferredIndexOptions()
Creates an instance of DeferredIndexOptions.
property BuildTimeoutSeconds #
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 #
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 #
MaxRetryDelaySeconds #public int MaxRetryDelaySeconds { get; set; }
The longest retry delay, in seconds, from DeferredIndexOptions.to 86400. The default is 900.
property PollIntervalSeconds #
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 #
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
| Member | Kind | Summary |
|---|---|---|
ModuleName | property | Gets the module name for this migration runner. |
SchemaName | property | Gets the schema name for this migration runner. |
GetAppliedMigrationInfoAsync( | method | Gets all applied migrations. |
GetCurrentVersionAsync( | method | Gets the current migration version (latest applied migration). |
RunAsync( | method | Runs pending migrations from the specified path. |
RunFromAssemblyAsync( | method | Runs pending migrations from embedded resources in an assembly. |
ValidateChecksumsAsync( | method | Validates checksums of applied migrations against source files. |
property ModuleName #
ModuleName #string ModuleName { get; }
Gets the module name for this migration runner.
property SchemaName #
SchemaName #string SchemaName { get; }
Gets the schema name for this migration runner.
method GetAppliedMigrationInfoAsync(CancellationToken) #
GetAppliedMigrationInfoAsync(CancellationToken) #Task<IReadOnlyList<MigrationInfo>> GetAppliedMigrationInfoAsync(CancellationToken cancellationToken = default)
Gets all applied migrations.
method GetCurrentVersionAsync(CancellationToken) #
GetCurrentVersionAsync(CancellationToken) #Task<string?> GetCurrentVersionAsync(CancellationToken cancellationToken = default)
Gets the current migration version (latest applied migration).
method RunAsync(string, MigrationRunOptions, CancellationToken) #
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) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
ExecuteAsync( | method | Runs the SQL of one migration on the runner’s connection and transaction. |
method ExecuteAsync(MigrationSqlExecutionContext, CancellationToken) #
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
| Member | Kind | Summary |
|---|---|---|
GetStatusAsync( | method | Gets the current migration status for the module. |
method GetStatusAsync(CancellationToken) #
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
| Member | Kind | Summary |
|---|---|---|
MigrationAssemblySource( | constructor | Migration source descriptor (assembly + optional resource prefix). |
MigrationsAssembly | property | The assembly that embeds the migrations. |
ResourcePrefix | property | Only the resources whose names contain this text, ignoring case; all when not set. |
constructor MigrationAssemblySource(Assembly, string) #
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 #
MigrationsAssembly #public Assembly MigrationsAssembly { get; init; }
The assembly that embeds the migrations.
property ResourcePrefix #
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.
class MigrationCategoryExtensions
public static class MigrationCategoryExtensions
Extension methods for migration category operations.
Members
| Member | Kind | Summary |
|---|---|---|
GetCategory( | method | Determines the category of a migration based on its filename. |
IsAutomatic( | extension method | Returns true if this migration should run automatically at startup. |
RequiresManualExecution( | extension method | Returns true if this migration requires manual CLI execution before startup may proceed. |
method GetCategory(string) #
GetCategory(string) #public static MigrationCategory GetCategory(string migrationName)
Determines the category of a migration based on its filename.
extension method IsAutomatic(MigrationCategory) #
IsAutomatic(MigrationCategory) #public static bool IsAutomatic(this MigrationCategory category)
Returns true if this migration should run automatically at startup.
extension method RequiresManualExecution(MigrationCategory) #
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.therefore normalizes all line endings to \n before hashing so the same logical SQL hashes identically regardless of how it was checked out.
MigrationChecksum.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.). A genuine content change matches no line-ending rendering and still fails closed.
Members
| Member | Kind | Summary |
|---|---|---|
Compute( | method | Computes the canonical, line-ending-normalized SHA-256 checksum (lowercase hex) of the supplied migration SQL content. |
ComputeRaw( | method | Computes the SHA-256 checksum (lowercase hex) of the supplied content WITHOUT any line-ending normalization. |
IsSelfHealableLegacyChecksum( | method | Determines whether a stored checksum that does not match the canonical (MigrationChecksum.) 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) #
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) #
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) #
IsSelfHealableLegacyChecksum(string, string) #public static bool IsSelfHealableLegacyChecksum(string content, string storedChecksum)
Determines whether a stored checksum that does not match the canonical (MigrationChecksum.) 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 inschema_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 inschema_.migrations. migration_ name AppliedChecksum: Whole-file checksum the database currently holds for that row.Applied: Normalized checksum of the content that producedNormalized Checksum 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.exactly; the current file normalizes successfully; and that normalized form hashes to MigrationChecksumReconciliationPin.. 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.is derived from the historical content — read the applied version out of source control and run it through MigrationSqlNormalizer.. Deriving it from the current file instead would make the pin self-confirming and prove nothing.
Members
| Member | Kind | Summary |
|---|---|---|
MigrationChecksumReconciliationPin( | constructor | 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. |
AppliedChecksum | property | Whole-file checksum the database currently holds for that row. |
AppliedNormalizedChecksum | property | Normalized checksum of the content that produced AppliedChecksum. |
IsRuledEdit | property | True when this pin records an owner-ruled SQL edit rather than a comment-only legacy row. |
Justification | property | Short audit note (commit + what changed), persisted with the ledger row. |
MigrationName | property | File name as recorded in schema_. |
RuledEditNormalizedChecksum | property | 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. |
Ruling | property | The ruling that authorised the edit (date and record), persisted with the justification. |
constructor MigrationChecksumReconciliationPin(string, string, string, string) #
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 inschema_.migrations. migration_ name AppliedChecksum: Whole-file checksum the database currently holds for that row.Applied: Normalized checksum of the content that producedNormalized Checksum 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.exactly; the current file normalizes successfully; and that normalized form hashes to MigrationChecksumReconciliationPin.. 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.is derived from the historical content — read the applied version out of source control and run it through MigrationSqlNormalizer.. Deriving it from the current file instead would make the pin self-confirming and prove nothing.
property AppliedChecksum #
AppliedChecksum #public string AppliedChecksum { get; init; }
Whole-file checksum the database currently holds for that row.
property AppliedNormalizedChecksum #
AppliedNormalizedChecksum #public string AppliedNormalizedChecksum { get; init; }
Normalized checksum of the content that produced AppliedChecksum.
property IsRuledEdit #
IsRuledEdit #public bool IsRuledEdit { get; }
True when this pin records an owner-ruled SQL edit rather than a comment-only legacy row.
property Justification #
Justification #public string Justification { get; init; }
Short audit note (commit + what changed), persisted with the ledger row.
property MigrationName #
MigrationName #public string MigrationName { get; init; }
File name as recorded in schema_.
property RuledEditNormalizedChecksum #
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.or whose recorded normalized checksum is MigrationChecksumReconciliationPin., 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 #
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
| Member | Kind | Summary |
|---|---|---|
MigrationInfo( | constructor | Information about an applied migration. |
AppliedAt | property | When it was applied. |
Checksum | property | The checksum recorded when it was applied. |
Name | property | The migration file name. |
constructor MigrationInfo(string, DateTimeOffset, string) #
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 #
AppliedAt #public DateTimeOffset AppliedAt { get; init; }
When it was applied.
property Checksum #
Checksum #public string Checksum { get; init; }
The checksum recorded when it was applied.
property Name #
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 <.
Members
| Member | Kind | Summary |
|---|---|---|
CommentOnly | constant | The file’s SQL is unchanged once comments and layout are removed; only comments/whitespace moved. |
LegacyPin | constant | The row predates normalized-checksum tracking, and an owner-declared pin proved the applied content and the current file normalize to the same SQL. |
LineEnding | constant | The stored value was the pre-normalization hash of the same SQL under different line endings. |
RuledEdit | constant | The executable SQL of an applied migration was changed under a recorded exception to the forward-only rule. |
constant CommentOnly #
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 #
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 #
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 #
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
| Member | Kind | Summary |
|---|---|---|
MigrationResult( | constructor | Creates an instance of MigrationResult. |
AppliedCount | property | Number of migrations applied. |
AppliedMigrations | property | Details of applied migrations. |
ChecksumErrors | property | Checksum validation errors, if any. |
DurationMs | property | Total duration in milliseconds. |
ErrorMessage | property | Error message if migration failed. |
FilteredCount | property | Number of migrations filtered out by category. |
SkippedCount | property | Number of migrations skipped (already applied). |
Success | property | Whether the migration run was successful. |
Failed( | method | Creates a failed result. |
Successful( | method | Creates a successful result. |
constructor MigrationResult() #
MigrationResult() #public MigrationResult()
Creates an instance of MigrationResult.
property AppliedCount #
AppliedCount #public int AppliedCount { get; init; }
Number of migrations applied.
property AppliedMigrations #
AppliedMigrations #public IReadOnlyList<AppliedMigrationDetail> AppliedMigrations { get; init; }
Details of applied migrations.
property ChecksumErrors #
ChecksumErrors #public IReadOnlyList<string> ChecksumErrors { get; init; }
Checksum validation errors, if any.
property DurationMs #
DurationMs #public long DurationMs { get; init; }
Total duration in milliseconds.
property ErrorMessage #
ErrorMessage #public string? ErrorMessage { get; init; }
Error message if migration failed.
property FilteredCount #
FilteredCount #public int FilteredCount { get; init; }
Number of migrations filtered out by category.
property SkippedCount #
SkippedCount #public int SkippedCount { get; init; }
Number of migrations skipped (already applied).
property Success #
Success #public bool Success { get; init; }
Whether the migration run was successful.
method Failed(string, IReadOnlyList<string>) #
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>) #
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
| Member | Kind | Summary |
|---|---|---|
MigrationRunOptions( | constructor | Creates an instance of MigrationRunOptions. |
CategoryFilter | property | Filter migrations by category. |
ChecksumReconciliationPins | property | Owner-declared reconciliations for rows written before the runner recorded normalized checksums. |
DryRun | property | If true, only show what would be executed without applying. |
FailOnChecksumMismatch | property | If true, fail if checksum validation errors are found. |
TimeoutSeconds | property | Timeout in seconds for individual migration execution. |
ValidateChecksums | property | If true, validate checksums before applying new migrations. |
constructor MigrationRunOptions() #
MigrationRunOptions() #public MigrationRunOptions()
Creates an instance of MigrationRunOptions.
property CategoryFilter #
CategoryFilter #public MigrationCategory? CategoryFilter { get; set; }
Filter migrations by category. If null, all categories are included.
property ChecksumReconciliationPins #
ChecksumReconciliationPins #public IList<MigrationChecksumReconciliationPin> ChecksumReconciliationPins { get; }
Owner-declared reconciliations for rows written before the runner recorded normalized checksums. Same contract as StartupMigrationOptions..
property DryRun #
DryRun #public bool DryRun { get; set; }
If true, only show what would be executed without applying.
property FailOnChecksumMismatch #
FailOnChecksumMismatch #public bool FailOnChecksumMismatch { get; set; }
If true, fail if checksum validation errors are found.
property TimeoutSeconds #
TimeoutSeconds #public int TimeoutSeconds { get; set; }
Timeout in seconds for individual migration execution. Default: 300.
property ValidateChecksums #
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
| Member | Kind | Summary |
|---|---|---|
MigrationRunner( | constructor | Creates a runner for the migrations of a module. |
ModuleName | property | Gets the module name for this migration runner. |
SchemaName | property | Gets the schema name for this migration runner. |
GetAppliedMigrationInfoAsync( | method | Gets all applied migrations. |
GetCurrentVersionAsync( | method | Gets the current migration version (latest applied migration). |
RunAsync( | method | Runs pending migrations from the specified path. |
RunFromAssemblyAsync( | method | Runs pending migrations from embedded resources in an assembly. |
ValidateChecksumsAsync( | method | Validates checksums of applied migrations against source files. |
constructor MigrationRunner(string, string, string, ILogger) #
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
Argument: An argument is null.Null Exception
property ModuleName #
ModuleName #public string ModuleName { get; }
Gets the module name for this migration runner.
property SchemaName #
SchemaName #public string SchemaName { get; }
Gets the schema name for this migration runner.
method GetAppliedMigrationInfoAsync(CancellationToken) #
GetAppliedMigrationInfoAsync(CancellationToken) #public Task<IReadOnlyList<MigrationInfo>> GetAppliedMigrationInfoAsync(CancellationToken cancellationToken = default)
Gets all applied migrations.
method GetCurrentVersionAsync(CancellationToken) #
GetCurrentVersionAsync(CancellationToken) #public Task<string?> GetCurrentVersionAsync(CancellationToken cancellationToken = default)
Gets the current migration version (latest applied migration).
method RunAsync(string, MigrationRunOptions, CancellationToken) #
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) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
AddMigrationRunner< | extension method | Adds a migration runner as a singleton for manual/CLI migration execution. |
AddMigrationStatus< | extension method | Adds the migration status service for querying migration state. |
AddStartupMigrations( | extension method | Adds a startup migration host using PostgresOptions. |
AddStartupMigrations< | extension method | Adds a startup migration host for the specified module. |
extension method AddMigrationRunner<TOptions>(IServiceCollection, string, string, Func<TOptions, string>) #
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) #
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>) #
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>) #
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.connection: Function to extract connection string from options.String Selector 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.Command: The command timeout, in seconds.Timeout Seconds
Members
| Member | Kind | Summary |
|---|---|---|
MigrationSqlExecutionContext( | constructor | The existing runner-owned connection and transaction for one immutable SQL file. |
CommandTimeoutSeconds | property | The command timeout, in seconds. |
Connection | property | The runner’s open connection. |
MigrationName | property | The migration. |
Sql | property | The SQL of the migration file. |
Transaction | property | The runner’s transaction; none for a migration that runs outside one. |
constructor MigrationSqlExecutionContext(NpgsqlConnection, NpgsqlTransaction, string, string, int) #
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.Command: The command timeout, in seconds.Timeout Seconds
property CommandTimeoutSeconds #
CommandTimeoutSeconds #public int CommandTimeoutSeconds { get; init; }
The command timeout, in seconds.
property Connection #
Connection #public NpgsqlConnection Connection { get; init; }
The runner’s open connection.
property MigrationName #
MigrationName #public string MigrationName { get; init; }
The migration.
property Sql #
Sql #public string Sql { get; init; }
The SQL of the migration file.
property Transaction #
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.returns false) and the caller must fall back to failing closed.
Rules. Line endings are normalized to \n first (matching MigrationChecksum.). 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
| Member | Kind | Summary |
|---|---|---|
TryComputeNormalizedChecksum( | method | Computes the SHA-256 (lowercase hex) of the normalized form of content. |
TryNormalize( | method | Attempts to reduce content to its comment-free, whitespace-collapsed form. |
method TryComputeNormalizedChecksum(string, out string) #
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) #
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 returnstrue.refusal: When this method returnsfalse, 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
| Member | Kind | Summary |
|---|---|---|
MigrationStatus( | constructor | Creates an instance of MigrationStatus. |
AppliedCount | property | Number of applied migrations. |
ChecksumErrors | property | Any checksum mismatches detected. |
HasBlockingIssues | property | Whether there are blocking issues (pending release migrations or checksum errors). |
IsUpToDate | property | Whether the database is up to date (no pending startup/release migrations). |
LastAppliedAt | property | When the last migration was applied. |
LastAppliedMigration | property | Last applied migration name. |
ModuleName | property | Module name. |
PendingIndexCount | property | Index obligations whose post-start completion has not been recorded. |
PendingMigrations | property | List of pending migrations. |
PendingReleaseCount | property | Number of pending release migrations. |
PendingStartupCount | property | Number of pending startup migrations. |
SchemaName | property | Schema name. |
constructor MigrationStatus() #
MigrationStatus() #public MigrationStatus()
Creates an instance of MigrationStatus.
property AppliedCount #
AppliedCount #public int AppliedCount { get; init; }
Number of applied migrations.
property ChecksumErrors #
ChecksumErrors #public IReadOnlyList<string> ChecksumErrors { get; init; }
Any checksum mismatches detected.
property HasBlockingIssues #
HasBlockingIssues #public bool HasBlockingIssues { get; }
Whether there are blocking issues (pending release migrations or checksum errors).
property IsUpToDate #
IsUpToDate #public bool IsUpToDate { get; }
Whether the database is up to date (no pending startup/release migrations).
property LastAppliedAt #
LastAppliedAt #public DateTimeOffset? LastAppliedAt { get; init; }
When the last migration was applied.
property LastAppliedMigration #
LastAppliedMigration #public string? LastAppliedMigration { get; init; }
Last applied migration name.
property ModuleName #
ModuleName #public required string ModuleName { get; init; }
Module name.
property PendingIndexCount #
PendingIndexCount #public int PendingIndexCount { get; init; }
Index obligations whose post-start completion has not been recorded.
property PendingMigrations #
PendingMigrations #public IReadOnlyList<PendingMigrationInfo> PendingMigrations { get; init; }
List of pending migrations.
property PendingReleaseCount #
PendingReleaseCount #public int PendingReleaseCount { get; init; }
Number of pending release migrations.
property PendingStartupCount #
PendingStartupCount #public int PendingStartupCount { get; init; }
Number of pending startup migrations.
property SchemaName #
SchemaName #public required string SchemaName { get; init; }
Schema name.
class MigrationStatusService
public sealed class MigrationStatusService : IMigrationStatusService
Implementation of migration status service.
Members
| Member | Kind | Summary |
|---|---|---|
MigrationStatusService( | constructor | Creates the status service for the migrations of one assembly. |
MigrationStatusService( | constructor | Creates the status service for the migrations of several sources. |
GetStatusAsync( | method | Gets the current migration status for the module. |
constructor MigrationStatusService(string, string, string, Assembly, ILogger, string) #
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) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
ActivitySourceName | constant | The name of the activity source for migration tracing. |
MeterName | constant | The name of the meter for migration metrics. |
RecordChecksumError( | method | Records a checksum validation error. |
RecordLockAcquired( | method | Records a successful lock acquisition. |
RecordLockTimeout( | method | Records a lock acquisition timeout. |
RecordMigrationApplied( | method | Records a successful migration application. |
RecordMigrationFailed( | method | Records a migration failure. |
SetActivityError( | method | Sets the error on an activity. |
SetActivitySuccess( | method | Marks an activity as successful. |
StartLockAcquisition( | method | Starts an activity for advisory lock acquisition. |
StartMigrationApply( | method | Starts an activity for a single migration. |
StartMigrationRun( | method | Starts an activity for migration execution. |
constant ActivitySourceName #
ActivitySourceName #public const string ActivitySourceName = "StellaOps.Infrastructure.Postgres.Migrations"
The name of the activity source for migration tracing.
constant MeterName #
MeterName #public const string MeterName = "StellaOps.Infrastructure.Postgres.Migrations"
The name of the meter for migration metrics.
method RecordChecksumError(string, string) #
RecordChecksumError(string, string) #public static void RecordChecksumError(string moduleName, string migrationName)
Records a checksum validation error.
method RecordLockAcquired(string, string, double) #
RecordLockAcquired(string, string, double) #public static void RecordLockAcquired(string moduleName, string schemaName, double waitSeconds)
Records a successful lock acquisition.
method RecordLockTimeout(string, string) #
RecordLockTimeout(string, string) #public static void RecordLockTimeout(string moduleName, string schemaName)
Records a lock acquisition timeout.
method RecordMigrationApplied(string, string, MigrationCategory, double) #
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) #
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) #
SetActivityError(Activity, Exception) #public static void SetActivityError(Activity? activity, Exception exception)
Sets the error on an activity.
method SetActivitySuccess(Activity, int) #
SetActivitySuccess(Activity, int) #public static void SetActivitySuccess(Activity? activity, int appliedCount)
Marks an activity as successful.
method StartLockAcquisition(string, string) #
StartLockAcquisition(string, string) #public static Activity? StartLockAcquisition(string moduleName, string schemaName)
Starts an activity for advisory lock acquisition.
method StartMigrationApply(string, string, MigrationCategory) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
DetectDuplicatePrefixes( | method | Detects migrations with duplicate numeric prefixes. |
ExtractNumericPrefix( | method | Extracts the numeric prefix from a migration name. |
Validate( | method | Validates a collection of migration file names. |
method DetectDuplicatePrefixes(IEnumerable<string>) #
DetectDuplicatePrefixes(IEnumerable<string>) #public static IReadOnlyList<(string Prefix, IReadOnlyList<string> Names)> DetectDuplicatePrefixes(IEnumerable<string> migrationNames)
Detects migrations with duplicate numeric prefixes.
method ExtractNumericPrefix(string) #
ExtractNumericPrefix(string) #public static string? ExtractNumericPrefix(string migrationName)
Extracts the numeric prefix from a migration name.
method Validate(IEnumerable<string>) #
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
| Member | Kind | Summary |
|---|---|---|
ValidationError( | constructor | Validation error that will block migration execution. |
Code | property | The error code. |
Message | property | The message. |
MigrationName | property | The migration the error concerns; none when it concerns the set. |
constructor ValidationError(string, string, string) #
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 #
Code #public string Code { get; init; }
The error code.
property Message #
Message #public string Message { get; init; }
The message.
property MigrationName #
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
| Member | Kind | Summary |
|---|---|---|
ValidationResult( | constructor | Creates an instance of Migration. |
Errors | property | The errors. |
IsValid | property | Whether there is no error. |
Warnings | property | The warnings. |
Failed( | method | A result with errors. |
Success( | method | A result without errors. |
constructor ValidationResult() #
ValidationResult() #public ValidationResult()
Creates an instance of Migration.
property Errors #
Errors #public IReadOnlyList<MigrationValidator.ValidationError> Errors { get; init; }
The errors.
property IsValid #
IsValid #public bool IsValid { get; }
Whether there is no error.
property Warnings #
Warnings #public IReadOnlyList<MigrationValidator.ValidationWarning> Warnings { get; init; }
The warnings.
method Failed(IReadOnlyList<MigrationValidator.ValidationError>, IReadOnlyList<MigrationValidator.ValidationWarning>) #
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>) #
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
| Member | Kind | Summary |
|---|---|---|
ValidationWarning( | constructor | Validation warning that should be addressed but won’t block execution. |
Code | property | The warning code. |
Message | property | The message. |
MigrationName | property | The migration the warning concerns; none when it concerns the set. |
constructor ValidationWarning(string, string, string) #
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 #
Code #public string Code { get; init; }
The warning code.
property Message #
Message #public string Message { get; init; }
The message.
property MigrationName #
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
| Member | Kind | Summary |
|---|---|---|
PendingMigrationInfo( | constructor | Information about a pending migration. |
Category | property | The migration category. |
Name | property | The migration file name. |
constructor PendingMigrationInfo(string, MigrationCategory) #
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 #
Category #public MigrationCategory Category { get; init; }
The migration category.
property Name #
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 exampleorders_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
| Member | Kind | Summary |
|---|---|---|
RequiredDatabaseRole( | constructor | A PostgreSQL role that must already exist before a module’s migrations run, together with the install step that provisions it. |
FailurePrefix | constant | The stable prefix every missing-role failure carries, so operators, log scrapes and tests can tell this apart from the raw 42501 it replaces. |
Name | property | The role name, exactly as the module’s SQL expects it (for example orders_admin). |
Provisioning | property | One sentence naming the install step that creates the role. |
FormatMissingMessage( | method | Builds the operator-facing message for a role that is absent. |
constructor RequiredDatabaseRole(string, string) #
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 exampleorders_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 #
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 #
Name #public string Name { get; init; }
The role name, exactly as the module’s SQL expects it (for example orders_admin).
property Provisioning #
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) #
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
| Member | Kind | Summary |
|---|---|---|
StartupMigrationHost( | constructor | Creates a new startup migration host. |
OpenConnectionAsync( | method | Opens the PostgreSQL connection used by the startup migration pass. |
StartAsync( | method | See IHosted. |
StopAsync( | method | See IHosted. |
constructor StartupMigrationHost(string, string, string, Assembly, ILogger, IHostApplicationLifetime, StartupMigrationOptions) #
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) #
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) #
StartAsync(CancellationToken) #public Task StartAsync(CancellationToken cancellationToken)
See IHosted.
method StopAsync(CancellationToken) #
StopAsync(CancellationToken) #public Task StopAsync(CancellationToken cancellationToken)
See IHosted.
class StartupMigrationOptions
public sealed class StartupMigrationOptions
Options for startup migration behavior.
Members
| Member | Kind | Summary |
|---|---|---|
StartupMigrationOptions( | constructor | Creates an instance of Startup. |
ChecksumReconciliationPins | property | Owner-declared reconciliations for databases whose schema_migrations rows were written before the host recorded normalized checksums. |
ConnectionRetryDelayMilliseconds | property | Delay between transient PostgreSQL connection attempts. |
ConnectionRetryTimeoutSeconds | property | Maximum time to retry transient PostgreSQL connection failures while the database is recovering or starting. |
DeferredIndexBuild | property | Owner-configured budgets for the resumable concurrent index builder. |
DeferredIndexes | property | Explicit immutable migration/index contracts whose builds continue after startup. |
Enabled | property | Whether to run migrations at startup. |
FailOnChecksumMismatch | property | Whether to fail startup if checksum validation fails. |
FailOnLockTimeout | property | Whether to fail startup if lock cannot be acquired. |
FailOnMigrationError | property | Whether to fail startup if migration execution fails. |
FailOnPendingReleaseMigrations | property | Whether to fail startup if there are pending release migrations. |
LockTimeoutSeconds | property | Timeout in seconds for acquiring the advisory lock. |
MigrationTimeoutSeconds | property | Timeout in seconds for individual migration execution. |
RequiredRoles | property | PostgreSQL roles the module’s SQL expects to already exist. |
ResourcePrefix | property | Optional embedded-resource prefix used to isolate one migration stream when an assembly contains SQL for multiple modules. |
RunSeedMigrations | property | Whether to apply pending Seed-category migrations at startup. |
SqlExecutor | property | Optional module policy for SQL execution; it never owns migration-ledger or transaction completion. |
constructor StartupMigrationOptions() #
StartupMigrationOptions() #public StartupMigrationOptions()
Creates an instance of Startup.
property ChecksumReconciliationPins #
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 #
ConnectionRetryDelayMilliseconds #public int ConnectionRetryDelayMilliseconds { get; set; }
Delay between transient PostgreSQL connection attempts. Default: 1000 ms.
property ConnectionRetryTimeoutSeconds #
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 #
DeferredIndexBuild #public DeferredIndexOptions DeferredIndexBuild { get; set; }
Owner-configured budgets for the resumable concurrent index builder.
property DeferredIndexes #
DeferredIndexes #public IList<DeferredIndexDefinition> DeferredIndexes { get; }
Explicit immutable migration/index contracts whose builds continue after startup.
property Enabled #
Enabled #public bool Enabled { get; set; }
Whether to run migrations at startup. Default: true.
property FailOnChecksumMismatch #
FailOnChecksumMismatch #public bool FailOnChecksumMismatch { get; set; }
Whether to fail startup if checksum validation fails. Default: true.
property FailOnLockTimeout #
FailOnLockTimeout #public bool FailOnLockTimeout { get; set; }
Whether to fail startup if lock cannot be acquired. Default: true.
property FailOnMigrationError #
FailOnMigrationError #public bool FailOnMigrationError { get; set; }
Whether to fail startup if migration execution fails. Default: true.
property FailOnPendingReleaseMigrations #
FailOnPendingReleaseMigrations #public bool FailOnPendingReleaseMigrations { get; set; }
Whether to fail startup if there are pending release migrations. Default: true.
property LockTimeoutSeconds #
LockTimeoutSeconds #public int LockTimeoutSeconds { get; set; }
Timeout in seconds for acquiring the advisory lock. Default: 120.
property MigrationTimeoutSeconds #
MigrationTimeoutSeconds #public int MigrationTimeoutSeconds { get; set; }
Timeout in seconds for individual migration execution. Default: 300.
property RequiredRoles #
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.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 #
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 #
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 #
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
| Type | Kind | Description |
|---|---|---|
PostgresOptions | class | PostgreSQL connection and behavior options. |
class PostgresOptions
public sealed class PostgresOptions
PostgreSQL connection and behavior options.
Members
| Member | Kind | Summary |
|---|---|---|
PostgresOptions( | constructor | Creates an instance of PostgresOptions. |
ApplicationName | property | Stable PostgreSQL application name used for runtime attribution. |
AutoMigrate | property | Enable automatic migration on startup. |
CommandTimeoutSeconds | property | Command timeout in seconds. |
ConnectionIdleLifetimeSeconds | property | Connection idle lifetime in seconds. |
ConnectionString | property | PostgreSQL connection string. |
MaxPoolSize | property | Maximum number of connections in the pool. |
MigrationsPath | property | Path to SQL migration files. |
MinPoolSize | property | Minimum number of connections in the pool. |
Pooling | property | Enable connection pooling. |
SchemaName | property | Schema name for module-specific tables. |
constructor PostgresOptions() #
PostgresOptions() #public PostgresOptions()
Creates an instance of PostgresOptions.
property ApplicationName #
ApplicationName #public string? ApplicationName { get; set; }
Stable PostgreSQL application name used for runtime attribution.
property AutoMigrate #
AutoMigrate #public bool AutoMigrate { get; set; }
Enable automatic migration on startup. Default is false for production safety.
property CommandTimeoutSeconds #
CommandTimeoutSeconds #public int CommandTimeoutSeconds { get; set; }
Command timeout in seconds. Default is 30 seconds.
property ConnectionIdleLifetimeSeconds #
ConnectionIdleLifetimeSeconds #public int ConnectionIdleLifetimeSeconds { get; set; }
Connection idle lifetime in seconds. Default is 300 seconds (5 minutes).
property ConnectionString #
ConnectionString #public required string ConnectionString { get; set; }
PostgreSQL connection string.
property MaxPoolSize #
MaxPoolSize #public int MaxPoolSize { get; set; }
Maximum number of connections in the pool. Default is 100.
property MigrationsPath #
MigrationsPath #public string? MigrationsPath { get; set; }
Path to SQL migration files. Required if AutoMigrate is true.
property MinPoolSize #
MinPoolSize #public int MinPoolSize { get; set; }
Minimum number of connections in the pool. Default is 1.
property Pooling #
Pooling #public bool Pooling { get; set; }
Enable connection pooling. Default is true.
property SchemaName #
SchemaName #public string? SchemaName { get; set; }
Schema name for module-specific tables. If null, uses public schema.
namespace StellaOps.Infrastructure.Postgres.Repositories
| Type | Kind | Description |
|---|---|---|
RepositoryBase< | class | Base 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
| Member | Kind | Summary |
|---|---|---|
RepositoryBase( | constructor | Creates a new repository with the specified data source and logger. |
CommandTimeoutSeconds | property | Command timeout from data source options. |
DataSource | property | The data source for database connections. |
Logger | property | Logger for this repository. |
AddJsonbParameter( | method | Adds a typed JSONB parameter to the command. |
AddParameter( | method | Adds a parameter to the command, handling null values. |
AddTextArrayParameter( | method | Adds a text array parameter to the command. |
AddUuidArrayParameter( | method | Adds a UUID array parameter to the command. |
BuildOrderByClause( | method | Builds ORDER BY clause with deterministic ordering. |
BuildPaginationClause( | method | Builds LIMIT/OFFSET clause for pagination. |
BuildWhereClause( | method | Builds a dynamic WHERE clause with the specified conditions. |
CreateCommand( | method | Creates a command with timeout configured. |
ExecuteAsync( | method | Executes a non-query command and returns the number of affected rows. |
ExecuteInBatchAsync< | method | 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. |
ExecuteScalarAsync< | method | Executes a scalar query and returns the result. |
GetNullableBoolean( | method | Gets a nullable bool from the reader. |
GetNullableDateTimeOffset( | method | Gets a nullable DateTimeOffset from the reader. |
GetNullableDecimal( | method | Gets a nullable decimal from the reader. |
GetNullableGuid( | method | Gets a nullable Guid from the reader. |
GetNullableInt32( | method | Gets a nullable int from the reader. |
GetNullableInt64( | method | Gets a nullable long from the reader. |
GetNullableString( | method | Gets a nullable string from the reader. |
QueryAsync< | method | Executes a query and returns all results as a list. |
QuerySingleOrDefaultAsync< | method | Executes a query and returns a single result or null. |
constructor RepositoryBase(TDataSource, ILogger) #
RepositoryBase(TDataSource, ILogger) #protected RepositoryBase(TDataSource dataSource, ILogger logger)
Creates a new repository with the specified data source and logger.
property CommandTimeoutSeconds #
CommandTimeoutSeconds #protected int CommandTimeoutSeconds { get; }
Command timeout from data source options.
property DataSource #
DataSource #protected TDataSource DataSource { get; }
The data source for database connections.
property Logger #
Logger #protected ILogger Logger { get; }
Logger for this repository.
method AddJsonbParameter(NpgsqlCommand, string, string) #
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) #
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[]) #
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[]) #
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) #
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) #
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)[]) #
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) #
CreateCommand(string, NpgsqlConnection) #protected NpgsqlCommand CreateCommand(string sql, NpgsqlConnection connection)
Creates a command with timeout configured.
method ExecuteAsync(string, string, Action<NpgsqlCommand>, CancellationToken, string) #
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) #
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<, RepositoryBase<, …) 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) #
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) #
GetNullableBoolean(NpgsqlDataReader, int) #protected static bool? GetNullableBoolean(NpgsqlDataReader reader, int ordinal)
Gets a nullable bool from the reader.
method GetNullableDateTimeOffset(NpgsqlDataReader, int) #
GetNullableDateTimeOffset(NpgsqlDataReader, int) #protected static DateTimeOffset? GetNullableDateTimeOffset(NpgsqlDataReader reader, int ordinal)
Gets a nullable DateTimeOffset from the reader.
method GetNullableDecimal(NpgsqlDataReader, int) #
GetNullableDecimal(NpgsqlDataReader, int) #protected static decimal? GetNullableDecimal(NpgsqlDataReader reader, int ordinal)
Gets a nullable decimal from the reader.
method GetNullableGuid(NpgsqlDataReader, int) #
GetNullableGuid(NpgsqlDataReader, int) #protected static Guid? GetNullableGuid(NpgsqlDataReader reader, int ordinal)
Gets a nullable Guid from the reader.
method GetNullableInt32(NpgsqlDataReader, int) #
GetNullableInt32(NpgsqlDataReader, int) #protected static int? GetNullableInt32(NpgsqlDataReader reader, int ordinal)
Gets a nullable int from the reader.
method GetNullableInt64(NpgsqlDataReader, int) #
GetNullableInt64(NpgsqlDataReader, int) #protected static long? GetNullableInt64(NpgsqlDataReader reader, int ordinal)
Gets a nullable long from the reader.
method GetNullableString(NpgsqlDataReader, int) #
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) #
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) #
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
| Type | Kind | Description |
|---|---|---|
PostgresFixture | class | Test fixture for PostgreSQL integration tests. |
PostgresFixtureFactory | class | Factory 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
| Member | Kind | Summary |
|---|---|---|
PostgresFixture( | constructor | Creates a new PostgreSQL test fixture. |
ConnectionString | property | Connection string for the test database. |
SchemaName | property | Schema name for test isolation. |
CreateOptions( | method | Creates PostgreSQL options for the test fixture. |
DisposeAsync( | method | Cleans up the test schema. |
ExecuteSqlAsync( | method | Executes raw SQL for test setup. |
InitializeAsync( | method | Initializes the test schema. |
RunMigrationsAsync( | method | Runs migrations for the test schema from filesystem path. |
RunMigrationsFromAssemblyAsync( | method | Runs migrations for the test schema from embedded resources in an assembly. |
RunMigrationsFromAssemblyAsync( | method | Runs migrations for the test schema from embedded resources in an assembly, with run options. |
RunMigrationsFromAssemblyAsync< | method | Runs migrations for the test schema from embedded resources using a type from the assembly. |
TruncateAllTablesAsync( | method | Truncates all tables in the test schema for test isolation. |
constructor PostgresFixture(string, string, ILogger) #
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 #
ConnectionString #public string ConnectionString { get; }
Connection string for the test database.
property SchemaName #
SchemaName #public string SchemaName { get; }
Schema name for test isolation.
method CreateOptions() #
CreateOptions() #public PostgresOptions CreateOptions()
Creates PostgreSQL options for the test fixture.
method DisposeAsync() #
DisposeAsync() #public ValueTask DisposeAsync()
Cleans up the test schema.
method ExecuteSqlAsync(string, CancellationToken) #
ExecuteSqlAsync(string, CancellationToken) #public Task ExecuteSqlAsync(string sql, CancellationToken cancellationToken = default)
Executes raw SQL for test setup.
method InitializeAsync(CancellationToken) #
InitializeAsync(CancellationToken) #public Task InitializeAsync(CancellationToken cancellationToken = default)
Initializes the test schema.
method RunMigrationsAsync(string, string, CancellationToken) #
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) #
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) #
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
Invalid: The migrations failed.Operation Exception
method RunMigrationsFromAssemblyAsync<TAssemblyMarker>(string, string, CancellationToken) #
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) #
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
| Member | Kind | Summary |
|---|---|---|
Create( | method | Creates a fixture with a unique schema name based on the test class name. |
CreateRandom( | method | Creates a fixture with a random schema name. |
method Create(string, string, ILogger) #
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) #
CreateRandom(string, ILogger) #public static PostgresFixture CreateRandom(string connectionString, ILogger? logger = null)
Creates a fixture with a random schema name.