Table of Contents

Class PostgresMaterializedViewStore

Namespace
Excalibur.EventSourcing.Postgres
Assembly
Excalibur.EventSourcing.Postgres.dll

Postgres implementation of IMaterializedViewStore.

public sealed class PostgresMaterializedViewStore : IAtomicMaterializedViewStore, IMaterializedViewStore
Inheritance
PostgresMaterializedViewStore
Implements
Inherited Members

Remarks

Stores materialized views as JSONB documents in Postgres with the following schema:

  • materialized_views table for view data
  • materialized_view_positions table for position tracking

Both tables are partitioned by tenant. The tenant term is part of each table's key rather than a filter applied over it, so two tenants projecting the same named view hold distinct rows and distinct checkpoints: Both tables live in the configured schema (public unless set), and every statement this store runs names that schema explicitly, so provision them there rather than relying on the connection's search_path:

CREATE TABLE public.materialized_views (
    tenant_id  VARCHAR(64) NOT NULL,
    view_name  VARCHAR(255) NOT NULL,
    view_id    VARCHAR(255) NOT NULL,
    data       JSONB        NOT NULL,
    created_at TIMESTAMPTZ  NOT NULL,
    updated_at TIMESTAMPTZ  NOT NULL,
    CONSTRAINT pk_materialized_views PRIMARY KEY (tenant_id, view_name, view_id)
);

CREATE TABLE public.materialized_view_positions (
    tenant_id  VARCHAR(64) NOT NULL,
    view_name  VARCHAR(255) NOT NULL,
    position   BIGINT       NOT NULL,
    created_at TIMESTAMPTZ  NOT NULL,
    updated_at TIMESTAMPTZ  NOT NULL,
    CONSTRAINT pk_materialized_view_positions PRIMARY KEY (tenant_id, view_name)
);

Uses INSERT ... ON CONFLICT for thread-safe upsert operations and JSONB for efficient JSON storage and querying.

Performance Note: Methods return ValueTask<TResult> to avoid heap allocations for common patterns where the operation completes synchronously or is already cached.

Constructors

PostgresMaterializedViewStore(NpgsqlDataSource, ILogger<PostgresMaterializedViewStore>, ITenantContext, string?, string?, JsonSerializerOptions?, string)

Initializes a new instance of the PostgresMaterializedViewStore class with an NpgsqlDataSource.

public PostgresMaterializedViewStore(NpgsqlDataSource dataSource, ILogger<PostgresMaterializedViewStore> logger, ITenantContext tenantContext, string? viewTableName = null, string? positionTableName = null, JsonSerializerOptions? jsonOptions = null, string schemaName = "public")

Parameters

dataSource NpgsqlDataSource

An Npgsql.NpgsqlDataSource that manages connection pooling. Using NpgsqlDataSource is the recommended pattern per Npgsql documentation.

logger ILogger<PostgresMaterializedViewStore>

The logger instance.

tenantContext ITenantContext

The 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.

viewTableName string

Optional view table name. Defaults to "materialized_views".

positionTableName string

Optional position table name. Defaults to "materialized_view_positions".

jsonOptions JsonSerializerOptions

Optional JSON serializer options.

schemaName string

The schema holding both tables. Defaults to public. Honoured by every statement this store runs: a schema setting the data access does not use reads as supported and does nothing. All identifiers are quoted, so their case is preserved exactly as configured.

PostgresMaterializedViewStore(string, ILogger<PostgresMaterializedViewStore>, ITenantContext, string?, string?, JsonSerializerOptions?, string)

Initializes a new instance of the PostgresMaterializedViewStore class.

public PostgresMaterializedViewStore(string connectionString, ILogger<PostgresMaterializedViewStore> logger, ITenantContext tenantContext, string? viewTableName = null, string? positionTableName = null, JsonSerializerOptions? jsonOptions = null, string schemaName = "public")

Parameters

connectionString string

The Postgres connection string.

logger ILogger<PostgresMaterializedViewStore>

The logger instance.

tenantContext ITenantContext

The 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.

viewTableName string

Optional view table name. Defaults to "materialized_views".

positionTableName string

Optional position table name. Defaults to "materialized_view_positions".

jsonOptions JsonSerializerOptions

Optional JSON serializer options.

schemaName string

The schema holding both tables. Defaults to public. Honoured by every statement this store runs: a schema setting the data access does not use reads as supported and does nothing. All identifiers are quoted, so their case is preserved exactly as configured.

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

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

cancellationToken CancellationToken

Cancellation 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.

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

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<TView>

The view if found, or null if not found.

Type Parameters

TView

The view type.

GetPositionAsync(string, CancellationToken)

Gets the last processed position for a view.

public ValueTask<long?> GetPositionAsync(string viewName, CancellationToken cancellationToken)

Parameters

viewName string

The view name for position tracking.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<long?>

The last processed position, or null if no position has been recorded.

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

viewName string

The view name for position tracking.

cancellationToken CancellationToken

Cancellation 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

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

view TView

The view to save.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

A task representing the asynchronous operation.

Type Parameters

TView

The 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

viewName string

The view name for position tracking.

position long

The position to advance to.

cancellationToken CancellationToken

Cancellation 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

viewName string

The logical view name the position belongs to.

viewId string

The identifier of the view instance being written.

view TView

The view to persist.

position long

The global stream position that produced view.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

Type Parameters

TView

The 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

viewName or viewId is null, empty, or white space.

ArgumentNullException

view is null.