Class SqlServerMaterializedViewStore
- Namespace
- Excalibur.EventSourcing.SqlServer
- Assembly
- Excalibur.EventSourcing.SqlServer.dll
SQL Server implementation of IMaterializedViewStore.
public sealed class SqlServerMaterializedViewStore : IAtomicMaterializedViewStore, IMaterializedViewStore
- Inheritance
-
SqlServerMaterializedViewStore
- Implements
- Inherited Members
Remarks
Stores materialized views as JSON documents in SQL Server with the following schema:
MaterializedViewstable for view dataMaterializedViewPositionstable for position tracking
Both tables are partitioned by tenant. The tenant term is part of each table's uniqueness constraint rather than a filter applied over it, so two tenants projecting the same named view hold distinct rows and distinct checkpoints. See EnsureSchemaAsync(CancellationToken) for the emitted DDL and for why the natural key is a UNIQUE constraint rather than the clustered key.
Performance Note: Methods return ValueTask<TResult> to avoid heap allocations for common patterns where the operation completes synchronously or is already cached.
Constructors
SqlServerMaterializedViewStore(Func<SqlConnection>, ILogger<SqlServerMaterializedViewStore>, ITenantContext, string?, string?, JsonSerializerOptions?, string)
Initializes a new instance of the SqlServerMaterializedViewStore class with a connection factory.
public SqlServerMaterializedViewStore(Func<SqlConnection> connectionFactory, ILogger<SqlServerMaterializedViewStore> logger, ITenantContext tenantContext, string? viewTableName = null, string? positionTableName = null, JsonSerializerOptions? jsonOptions = null, string schemaName = "dbo")
Parameters
connectionFactoryFunc<SqlConnection>A factory function that creates SqlConnection instances.
loggerILogger<SqlServerMaterializedViewStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions rows by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.
viewTableNamestringOptional view table name. Defaults to "MaterializedViews".
positionTableNamestringOptional position table name. Defaults to "MaterializedViewPositions".
jsonOptionsJsonSerializerOptionsOptional JSON serializer options.
schemaNamestringThe schema holding both tables. Defaults to
dbo. Honoured by every statement this store runs, including the DDL it emits: a schema setting the data access does not use reads as supported and does nothing.
SqlServerMaterializedViewStore(string, ILogger<SqlServerMaterializedViewStore>, ITenantContext, string?, string?, JsonSerializerOptions?, string)
Initializes a new instance of the SqlServerMaterializedViewStore class.
public SqlServerMaterializedViewStore(string connectionString, ILogger<SqlServerMaterializedViewStore> logger, ITenantContext tenantContext, string? viewTableName = null, string? positionTableName = null, JsonSerializerOptions? jsonOptions = null, string schemaName = "dbo")
Parameters
connectionStringstringThe SQL Server connection string.
loggerILogger<SqlServerMaterializedViewStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions rows by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.
viewTableNamestringOptional view table name. Defaults to "MaterializedViews".
positionTableNamestringOptional position table name. Defaults to "MaterializedViewPositions".
jsonOptionsJsonSerializerOptionsOptional JSON serializer options.
schemaNamestringThe schema holding both tables. Defaults to
dbo. Honoured by every statement this store runs, including the DDL it emits: a schema setting the data access does not use reads as supported and does nothing.
Properties
SupportsAtomicWrites
Gets a value indicating whether this store instance can currently perform atomic view+position writes.
public bool SupportsAtomicWrites { get; }
Property Value
- bool
true when SaveViewAndPositionAsync<TView>(string, string, TView, long, CancellationToken) commits both writes as one unit; otherwise false.
Remarks
Implementing the interface states the store is capable of atomic writes; this property states whether the current configuration enables them. A store whose atomicity is unconditional returns true constantly. A store whose atomicity requires an opt-in — a transaction mode, a replica set — returns the value of that setting, so the check reads the option that actually governs the behaviour rather than a proxy for it.
Methods
DeleteAsync(string, string, CancellationToken)
Deletes a materialized view.
public ValueTask DeleteAsync(string viewName, string viewId, CancellationToken cancellationToken)
Parameters
viewNamestringThe view name (typically the view type name).
viewIdstringThe view identifier.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task representing the asynchronous operation.
Remarks
Confined to the ambient tenant, like every other operation on this store: a view stored under
another tenant with the same viewName and viewId is not
deleted, and the call succeeds silently because that view is not visible to this caller. An
implementation that omits the tenant term here deletes another tenant's view -- silent data loss
rather than a disclosure, and the projector that rebuilt it will not notice.
EnsureSchemaAsync(CancellationToken)
Ensures the materialized view tables exist in the database. Creates them if they do not exist.
public Task EnsureSchemaAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancellation token.
Returns
- Task
A task representing the asynchronous operation.
Remarks
Creates two tables:
-
[ViewTableName]— Stores serialized view data with composite key (ViewName, ViewId). -
[PositionTableName]— Tracks the last processed global stream position per view, enabling catch-up and rebuild scenarios.
This method is idempotent — it uses IF NOT EXISTS guards and can be called
safely at application startup.
GetAsync<TView>(string, string, CancellationToken)
Gets a materialized view by its identifier.
[RequiresUnreferencedCode("JSON deserialization might require types that cannot be statically analyzed.")]
[RequiresDynamicCode("JSON deserialization might require runtime code generation.")]
public ValueTask<TView?> GetAsync<TView>(string viewName, string viewId, CancellationToken cancellationToken) where TView : class
Parameters
viewNamestringThe view name (typically the view type name).
viewIdstringThe view identifier.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask<TView>
The view if found, or null if not found.
Type Parameters
TViewThe view type.
GetPositionAsync(string, CancellationToken)
Gets the last processed position for a view.
public ValueTask<long?> GetPositionAsync(string viewName, CancellationToken cancellationToken)
Parameters
viewNamestringThe view name for position tracking.
cancellationTokenCancellationTokenCancellation token.
Returns
Remarks
The position is used to track which events have been processed for a view, enabling catch-up subscriptions and rebuild scenarios.
ResetPositionAsync(string, CancellationToken)
Clears the recorded position for a view, so the next read reports no checkpoint at all.
public ValueTask ResetPositionAsync(string viewName, CancellationToken cancellationToken)
Parameters
viewNamestringThe view name for position tracking.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task representing the asynchronous operation.
Remarks
Unconditional by contract. This is the operation a rebuild needs, and it is deliberately not subject to the monotonic guard that governs SavePositionAsync(string, long, CancellationToken) — a guard whose whole purpose is to refuse exactly this.
It clears rather than zeroes. GetPositionAsync(string, CancellationToken) already returns null for a view with no checkpoint, so absence is the existing representation of "start from the beginning" and needs no second encoding. Writing zero would also be indistinguishable from a view legitimately checkpointed at position zero.
It returns no outcome because it cannot refuse. Clearing an already-absent checkpoint is success, not a refusal. A store that cannot clear throws.
SaveAsync<TView>(string, string, TView, CancellationToken)
Saves a materialized view.
[RequiresUnreferencedCode("JSON serialization might require types that cannot be statically analyzed.")]
[RequiresDynamicCode("JSON serialization might require runtime code generation.")]
public ValueTask SaveAsync<TView>(string viewName, string viewId, TView view, CancellationToken cancellationToken) where TView : class
Parameters
viewNamestringThe view name (typically the view type name).
viewIdstringThe view identifier.
viewTViewThe view to save.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task representing the asynchronous operation.
Type Parameters
TViewThe view type.
SavePositionAsync(string, long, CancellationToken)
Advances the last processed position for a view, and reports whether the advance was taken.
public ValueTask<ViewPositionSaveOutcome> SavePositionAsync(string viewName, long position, CancellationToken cancellationToken)
Parameters
viewNamestringThe view name for position tracking.
positionlongThe position to advance to.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask<ViewPositionSaveOutcome>
Advanced when the checkpoint moved to
position; RefusedAsStale when the stored checkpoint was already at or beyond it and nothing was written.
Remarks
This advance is MONOTONIC in every implementation, and the refusal is a normal outcome rather than an error. A delayed or retried write carrying an older position must not rewind the checkpoint, because the projection would then replay events it has already applied. Every store enforces that server-side.
The return value exists because the refusal used to be unobservable. This member returned ValueTask — a caller could not tell a taken advance from a refused one, and every implementation logged a successful save either way. That hid a real defect for as long as the monotonic guard existed: a caller that needed the position to go BACKWARDS was silently refused and reported success. An operation that can decline to act must say so in its signature.
To move a checkpoint backwards, use ResetPositionAsync(string, CancellationToken). Lowering a position is a different operation from advancing one, so it is a different member rather than a flag — this method cannot express it and must not be asked to.
SaveViewAndPositionAsync<TView>(string, string, TView, long, CancellationToken)
Persists a view and advances the processed position for its view name in a single durable operation.
[RequiresUnreferencedCode("JSON serialization might require types that cannot be statically analyzed.")]
[RequiresDynamicCode("JSON serialization might require runtime code generation.")]
public ValueTask SaveViewAndPositionAsync<TView>(string viewName, string viewId, TView view, long position, CancellationToken cancellationToken) where TView : class
Parameters
viewNamestringThe logical view name the position belongs to.
viewIdstringThe identifier of the view instance being written.
viewTViewThe view to persist.
positionlongThe global stream position that produced
view.cancellationTokenCancellationTokenCancellation token.
Returns
Type Parameters
TViewThe materialized view type.
Remarks
Both writes commit, or neither does. The position advance is monotonic: a lower position never overwrites a higher one, so a delayed or retried write cannot rewind the checkpoint and replay events that were already applied.
Exceptions
- ArgumentException
viewNameorviewIdis null, empty, or white space.- ArgumentNullException
viewis null.