postgres

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

haistack-postgres (pkg/postgres)

Server-side PostgreSQL storage for haistack — the authoritative backend for multi-tenant cloud and edge deployments.

What it does

This package stores FHIR resources and related data in PostgreSQL when you need a shared backend that many clients can talk to. It is the server counterpart to pkg/sqlite, which is for a single device’s local offline database.

In simple terms, it is the source of truth on the server:

  1. Stores FHIR resources — current state, version history, search indexes, binaries, audit logs, jobs, and more.
  2. Isolates tenants — every operation is scoped to one tenant; tenant A never sees tenant B’s data through this API.
  3. Handles writes atomically — a create, update, or delete either fully succeeds or fully rolls back (resource + history + events + search + audit together).
  4. Assigns server metadata — on accepted writes it generates version IDs and global event sequence numbers; callers do not assign those.
  5. Records failures safely — rejected or conflicted writes go to audit (and conflict tables) without changing the stored resource.

It does not parse FHIR, run FHIRPath, or implement HTTP APIs. It is pure persistence: open a database, then read and write through small interfaces defined in pkg/store.

SQLite vs Postgres

Postgres (pkg/postgres) SQLite (pkg/sqlite)
Role Shared server, many clients One device, offline-first
Tenancy Explicit per-tenant Single local database
Versions Server assigns version IDs Caller supplies version IDs
Events Global event_log sequence Local sync_outbox
When to use Cloud / edge service Tablet, workstation, embedded node

Mental model

postgres.DB              ← one connection pool to Postgres
    └── Tenant("acme")   ← everything for one customer
            ├── ResourceStore()   read/write current Patient/Observation/…
            ├── HistoryStore()    past versions
            ├── EventStore()      ordered change stream (for sync/replay)
            ├── SearchStore()     index lookups
            ├── ApplyWrite()      one-shot “do the whole write pipeline”
            └── … audit, jobs, blobs, node registry, etc.

When to use it

  • Running a cloud or edge server that many devices sync with
  • Need tenant isolation (multi-customer SaaS, regional tenants)
  • Server must be authoritative for accepted resource versions and event ordering
  • Background jobs, audit, analytics, or materialized views on the server

Use pkg/sqlite instead when the database lives on one device and syncs up later.

Usage

Connect and migrate
import "github.com/degoke/haistack/pkg/postgres"

db, err := postgres.Open(ctx, "postgres://user:pass@localhost:5432/haistack?sslmode=disable")
if err != nil { /* handle */ }
defer db.Close()

if err := db.Migrate(ctx); err != nil { /* creates tables */ }
Pick a tenant and read a resource
tdb := db.Tenant("tenant-acme")

patient, err := tdb.ResourceStore().Read(ctx, "Patient", "pat-123")
Accept a write (most common path)

ApplyWrite is the main entry point for creating, updating, or deleting a resource on the server:

result, err := tdb.ApplyWrite(ctx, postgres.Write{
    Resource: envelope,                   // *types.ResourceEnvelope with JSON
    Action:   store.VersionActionCreate, // create | update | delete
    SearchEntries: []store.SearchIndexEntry{{
        ResourceType: "Patient",
        ID:           "pat-123",
        Fields:       map[string]string{"string.family": "Smith"},
    }},
    Audit: store.AuditRecord{Actor: "api", Action: "create"},
})
// result.Resource.VersionID — server-assigned version
// result.Event.Sequence     — global event number

On success, Postgres updates the resource, history, event log, search index, ID registry, and audit log in one transaction.

Record a rejection or conflict (without changing data)
_, err := tdb.ApplyWrite(ctx, postgres.Write{
    Resource:        envelope,
    Action:          store.VersionActionUpdate,
    Outcome:         postgres.WriteOutcomeConflicted,
    RejectionReason: "version mismatch",
    ConflictLocalVersionID:  "v-local",
    ConflictRemoteVersionID: "v-remote",
    Audit: store.AuditRecord{Actor: "sync", Action: "update"},
})

The stored resource does not change; you get audit and conflict records instead.

Other stores

All hang off the same TenantDB:

Accessor Purpose
EventStore() Replay changes (ReadSince) for sync workers
CursorStore() Named checkpoints (“how far did this worker get?”)
ConflictStore() List and resolve sync conflicts
IDRegistry() Authoritative resource ID registration
JobStore() Background job enqueue / claim / update
AuditStore() Compliance and security audit trail
NodeRegistry() Register edge devices and cloud nodes
BlobStore() / BinaryStore() Inline or referenced binary payloads
ModuleStore() Runtime module registration metadata
MaterializedViewStore() Named read-optimized projections
ReportingTableStore() Analytics reporting table snapshots for view refreshes
AnalyticsStore() Append-only analytics events

For manual multi-step writes in one transaction, use BeginWrite / Session and commit when done.

Where it fits

Layer Role
types ResourceEnvelope — JSON container passed into stores
store Interface contracts this package implements
sqlite Local device copy; syncs accepted writes toward postgres
postgres Tenant-scoped server persistence and authoritative writes
core Orchestrates validation, version policy, and write pipelines upstream

Search index field keys

Search entries use typed table routing (same convention as sqlite):

  • token.<name> → token index
  • string.<name> → string index (default when no prefix)
  • date.<name>, number.<name>, reference.<name> / ref.<name> → typed tables
  • uri.<name> → string index (canonical/URI search parameters)

FHIR search parsing lives outside this package; callers pass prepared SearchIndexEntry values on writes.

Testing

Integration tests use testcontainers (postgres:16-alpine) or an external instance via:

TEST_POSTGRES_DSN='postgres://user:pass@localhost:5432/haistack?sslmode=disable' go test ./pkg/postgres/...

Without Docker or TEST_POSTGRES_DSN, integration tests skip.

MVP limits

  • Single Postgres database per DB (no built-in sharding or read-replica routing)
  • Blob Location stores an opaque string; no object-storage SDK integration
  • Partitioning, archival, and warehouse export cursors are future work
  • FHIR validation, HTTP, and business rules live in upstream packages

See doc.go for design principles, schema tables, file layout, and the full write coordinator behavior.

Documentation

Overview

Package postgres implements haistack-postgres, the authoritative edge/cloud storage backend for haistack.

haistack-postgres is the Postgres-backed implementation of pkg/store contracts for tenant-scoped server deployments. Unlike haistack-sqlite (pkg/sqlite), it persists accepted writes as the system of record, assigns version IDs and global event sequence numbers inside the adapter, enforces tenant boundaries, and records rejected or conflicted writes without mutating current resource state. This is not bytefhir-postgres; it is the haistack runtime's server persistence adapter at github.com/degoke/haistack/pkg/postgres.

Design principles

Tenant-scoped access:

  • DB holds a shared pgxpool.Pool; TenantDB scopes every query with a tenant_id.
  • Callers obtain stores through db.Tenant(tenantID); cross-tenant reads and writes are not exposed on the public API.
  • EnsureTenant (on DB or implicitly via BeginSession/ApplyWrite) registers the tenant row in the tenant table before writes proceed.

Authoritative accepted writes:

  • ApplyWrite and Session coordinate one Postgres transaction for each write attempt.
  • Accepted writes assign a new VersionID (UUID) and append to event_log with a globally monotonic BIGSERIAL sequence assigned inside the same transaction.
  • Accepted writes update resource, resource_history, event_log, typed search_* tables, resource_id_registry, and audit_log atomically.
  • Rejected or conflicted writes append audit_log only; conflicted writes also append sync_conflict. They do not change resource, resource_history, event_log, or search rows.

Canonical JSON:

  • types.ResourceEnvelope.JSON is the source of truth for resource content.
  • Stores persist JSONB plus metadata columns (version_id, last_updated, hash).
  • Search extraction and FHIR parsing remain outside this package; callers supply prepared store.SearchIndexEntry values on accepted writes.

pgx driver:

  • Uses github.com/jackc/pgx/v5 and pgxpool directly (not database/sql).
  • Open accepts functional options such as WithMaxConns, WithMinConns, and WithSchema.
  • WithSchema selects the Postgres schema for haistack tables (default: public).

Opening a database

db, err := postgres.Open(ctx, "postgres://user:pass@localhost:5432/haistack?sslmode=disable")
if err != nil { … }
defer db.Close()

if err := db.Migrate(ctx); err != nil { … }

Custom schema:

db, err := postgres.Open(ctx, dsn, postgres.WithSchema("haistack"))

Obtain a tenant-scoped accessor:

tdb := db.Tenant("tenant-a")
envelope, err := tdb.ResourceStore().Read(ctx, "Patient", "pat-1")

Implemented contracts

All types below satisfy pkg/store interfaces unless noted. Every store is tenant-scoped through TenantDB:

  • ResourceStore → store.ResourceStore — current-state CRUD (resource table)
  • HistoryStore → store.HistoryStore — immutable history and tombstones
  • SearchStore → store.SearchStore — typed search_* index tables
  • EventStore → store.EventStore — append-only event_log with global sequence
  • CursorStore → store.CursorStore — named sync_cursor checkpoints
  • InboxStore → store.InboxStore — sync_inbox_applied push/pull dedupe
  • ConflictStore → store.ConflictStore — sync_conflict append/list/resolve
  • IDRegistry → store.IDRegistryStore — resource_id_registry reserve/check/register
  • BinaryStore → store.BinaryStore — inline binary_object payloads
  • BlobStore → store.BlobStore — binary_object with optional Location (PutStream/Open materialize BYTEA; Open follows in-store Location pointers and errors on a URI Location with no payload. Use an object-store adapter for multi-GB payloads)
  • AuditStore → store.AuditStore — append-only audit_log
  • ModuleStore → store.ModuleStore — module_registry metadata
  • MaterializedViewStore → store.MaterializedViewStore — materialized_view projections
  • ReportingTableStore → store.ReportingTableStore — analytics reporting snapshots
  • AnalyticsStore → store.AnalyticsStore — analytics_event append/query
  • JobStore → store.JobStore — background_job enqueue/claim/update
  • NodeRegistry → store.NodeRegistryStore — node_registry for edge/cloud nodes
  • Session → store.WriteSession — transaction-scoped core stores
  • TenantDB → store.WriteSessionProvider — via BeginWrite / BeginSession

Session also exposes IDRegistry, ConflictStore, and AuditStore for manual multi-step server writes inside one transaction; those methods are not part of store.WriteSession.

Atomic write path

High-level helper for accepted, rejected, or conflicted writes:

result, err := tdb.ApplyWrite(ctx, postgres.Write{
    Resource:      envelope,
    Action:        store.VersionActionCreate,
    SearchEntries: []store.SearchIndexEntry{…},
    RequestedID:   "pat-1", // optional; overrides Resource.ID on create
    Audit:         store.AuditRecord{Actor: "api", Action: "create"},
    Outcome:       postgres.WriteOutcomeAccepted, // default when empty
})

Rejected write (audit only; no resource mutation):

_, err := tdb.ApplyWrite(ctx, postgres.Write{
    Resource:        envelope,
    Action:          store.VersionActionUpdate,
    Outcome:         postgres.WriteOutcomeRejected,
    RejectionReason: "validation failed",
    Audit:           store.AuditRecord{…},
})

Conflicted write (audit + sync_conflict; no resource mutation):

_, err := tdb.ApplyWrite(ctx, postgres.Write{
    Resource:                envelope,
    Action:                  store.VersionActionUpdate,
    Outcome:                 postgres.WriteOutcomeConflicted,
    RejectionReason:         "version mismatch",
    ConflictLocalVersionID:  localVersion,
    ConflictRemoteVersionID: remoteVersion,
    Audit:                   store.AuditRecord{…},
})

Manual session (same transaction boundary for accepted writes composed by hand):

session, err := tdb.BeginWrite(ctx)
session.ResourceStore().Create(ctx, envelope)
session.HistoryStore().AppendVersion(ctx, version)
session.EventStore().Append(ctx, event)
session.SearchStore().Index(ctx, entry)
session.Commit(ctx)

ApplyWrite on accepted outcomes assigns VersionID and event sequence; manual sessions require the caller to supply version metadata and events unless using lower-level stores directly without the write coordinator.

WriteResult returns the persisted envelope (with assigned VersionID on acceptance), ResourceVersion, ResourceEvent (with Sequence), IDRegistryResult, and WriteOutcome.

Search index field keys

SearchStore routes fields to typed tables using key prefixes (same convention as sqlite):

  • token.<name> → hai_search_token
  • string.<name> → hai_search_string
  • date.<name> → hai_search_date
  • number.<name> → hai_search_number
  • reference.<name> or ref.<name> → hai_search_reference
  • uri.<name> → hai_search_string

Keys without a prefix default to hai_search_string. QueryPrepared supports the "by-field" plan (args: key, value). AnalyticsStore QueryPrepared supports "by-name-since" (args: name, since as RFC3339).

ID registry

On accepted creates, ApplyWrite calls IDRegistry.Reserve to claim (tenant_id, resource_type, id) exclusively; duplicate creates fail the transaction. Updates and deletes verify or lazily register IDs. Conflict and rejection paths skip registry changes.

Schema and migrations

Migrations are embedded numbered SQL files under migrations/ (for example 0001_init.sql). Migrate runs them idempotently and records applied versions in hai_schema_migrations. Non-public schemas are created automatically before the first migration.

Main tables (all tenant-aware where applicable):

  • hai_tenant — authoritative tenant registry
  • hai_resource — current accepted state keyed by (tenant_id, resource_type, id)
  • hai_resource_history — immutable accepted version log with delete tombstones
  • hai_event_log — globally ordered accepted-write events (BIGSERIAL sequence)
  • hai_resource_id_registry — authoritative resource ID registration per type
  • hai_node_registry — edge/cloud node metadata for sync coordination
  • hai_sync_conflict — rejected/conflicted write records and resolution timestamps
  • hai_search_* — typed index tables (token, string, date, number, reference, text, composite)
  • hai_sync_cursor — named consumer checkpoints
  • hai_binary_object — inline binary or blob metadata (optional location column)
  • hai_audit_log — append-only audit entries
  • hai_module_registry — tenant module registration metadata
  • hai_materialized_view — named projection entries
  • hai_analytics_reporting_meta / hai_analytics_reporting_row — analytics reporting table snapshots
  • hai_analytics_event — append-only analytics records
  • hai_background_job — durable job queue with claim semantics (FOR UPDATE SKIP LOCKED)

Integration with other packages

pkg/store — interface contracts; postgres implements the full server-side surface. pkg/types — ResourceEnvelope is the only FHIR container crossing store boundaries. pkg/sqlite — embedded local adapter; callers sync local outbox events to server event_log. pkg/core — orchestrates write pipelines, validation, and conflict policy upstream. pkg/search — produces SearchIndexEntry values; does not implement SearchStore.

File layout

  • doc.go — package documentation (this file)
  • db.go — DB, Open, Migrate, Tenant, EnsureTenant, Pool
  • tenant.go — TenantDB and per-store accessors, BeginWrite, ApplyWrite
  • options.go — Open options (WithMaxConns, WithMinConns)
  • migrate.go — embedded migration runner
  • session.go — Session, Write, WriteResult, WriteOutcome, write coordinator
  • exec.go — internal querier/execer abstractions for pool vs tx
  • util.go — null helpers and pgx.ErrNoRows check
  • resource_store.go — ResourceStore
  • history_store.go — HistoryStore
  • search_store.go — SearchStore
  • event_store.go — EventStore (event_log)
  • cursor_store.go — CursorStore
  • conflict_store.go — ConflictStore
  • id_registry.go — IDRegistry
  • binary_store.go — BinaryStore
  • blob_store.go — BlobStore
  • audit_store.go — AuditStore
  • module_store.go — ModuleStore
  • node_registry.go — NodeRegistry
  • materialized_views.go — MaterializedViewStore
  • reporting_table_store.go — ReportingTableStore
  • analytics_store.go — AnalyticsStore
  • job_store.go — JobStore
  • migrations/*.sql — embedded schema migrations

Testing

postgres_test.go contains integration tests against a real Postgres instance via testcontainers (postgres:16-alpine) or TEST_POSTGRES_DSN when set. Tests cover migration idempotency, tenant isolation, per-store CRUD, ApplyWrite atomicity and rollback, accepted/rejected/conflicted write semantics, delete tombstones, ID registry races, conflict resolution, job claim/update, materialized views, analytics queries, node registry, and concurrent global event sequencing.

When Docker is unavailable and TEST_POSTGRES_DSN is unset, integration tests skip. initDockerHost resolves DOCKER_HOST from the active docker context for OrbStack and similar environments where the default socket path differs.

Out of scope (later work)

Partitioning by tenant or resource type, read replicas, hot/cold storage, archival history, object-storage integration for BlobStore.Location, warehouse export cursors, encrypted connections beyond DSN configuration, multi-database routing, and in-process caching layers.

Index

Constants

This section is empty.

Variables

View Source
var ErrVersionMismatch = errors.New("resource version mismatch")

ErrVersionMismatch reports that a conditional write no longer matches the version observed by the caller.

Functions

This section is empty.

Types

type AnalyticsStore

type AnalyticsStore struct {
	// contains filtered or unexported fields
}

AnalyticsStore persists analytics events in Postgres.

func (*AnalyticsStore) Append

func (s *AnalyticsStore) Append(ctx context.Context, event store.AnalyticsEvent) error

func (*AnalyticsStore) QueryPrepared

func (s *AnalyticsStore) QueryPrepared(ctx context.Context, query store.PreparedQuery, args map[string]string) ([]store.AnalyticsEvent, error)

type AuditStore

type AuditStore struct {
	// contains filtered or unexported fields
}

AuditStore persists append-only audit records in Postgres.

func (*AuditStore) Append

func (s *AuditStore) Append(ctx context.Context, record store.AuditRecord) error

func (*AuditStore) List

func (s *AuditStore) List(ctx context.Context, query store.AuditQuery) ([]store.AuditRecord, error)

type AuthStore

type AuthStore struct {
	// contains filtered or unexported fields
}

AuthStore persists auth data for one tenant context in Postgres.

func (*AuthStore) DeleteDevice

func (s *AuthStore) DeleteDevice(ctx context.Context, deviceID string) error

func (*AuthStore) DeletePolicy

func (s *AuthStore) DeletePolicy(ctx context.Context, name string) error

func (*AuthStore) DeletePrincipal

func (s *AuthStore) DeletePrincipal(ctx context.Context, id string) error

func (*AuthStore) DeleteRole

func (s *AuthStore) DeleteRole(ctx context.Context, name string) error

func (*AuthStore) DeleteTenantBinding

func (s *AuthStore) DeleteTenantBinding(ctx context.Context, principalID string) error

func (*AuthStore) GetActivePolicy

func (s *AuthStore) GetActivePolicy(ctx context.Context) (*store.AuthPolicyRecord, error)

func (*AuthStore) GetDevice

func (s *AuthStore) GetDevice(ctx context.Context, deviceID string) (*store.AuthDeviceRecord, error)

func (*AuthStore) GetPolicy

func (s *AuthStore) GetPolicy(ctx context.Context, name string) (*store.AuthPolicyRecord, error)

func (*AuthStore) GetPrincipal

func (s *AuthStore) GetPrincipal(ctx context.Context, id string) (*store.AuthPrincipalRecord, error)

func (*AuthStore) GetRole

func (s *AuthStore) GetRole(ctx context.Context, name string) (*store.AuthRoleRecord, error)

func (*AuthStore) GetTenantBinding

func (s *AuthStore) GetTenantBinding(ctx context.Context, principalID string) (*store.AuthTenantBindingRecord, error)

func (*AuthStore) ListDevices

func (s *AuthStore) ListDevices(ctx context.Context) ([]store.AuthDeviceRecord, error)

func (*AuthStore) ListPolicies

func (s *AuthStore) ListPolicies(ctx context.Context) ([]store.AuthPolicyRecord, error)

func (*AuthStore) ListPrincipals

func (s *AuthStore) ListPrincipals(ctx context.Context) ([]store.AuthPrincipalRecord, error)

func (*AuthStore) ListRoles

func (s *AuthStore) ListRoles(ctx context.Context) ([]store.AuthRoleRecord, error)

func (*AuthStore) ListTenantBindings

func (s *AuthStore) ListTenantBindings(ctx context.Context) ([]store.AuthTenantBindingRecord, error)

func (*AuthStore) Snapshot

func (s *AuthStore) Snapshot(ctx context.Context) (*store.AuthSnapshot, error)

func (*AuthStore) UpsertDevice

func (s *AuthStore) UpsertDevice(ctx context.Context, device store.AuthDeviceRecord) error

func (*AuthStore) UpsertPolicy

func (s *AuthStore) UpsertPolicy(ctx context.Context, policy store.AuthPolicyRecord) error

func (*AuthStore) UpsertPrincipal

func (s *AuthStore) UpsertPrincipal(ctx context.Context, principal store.AuthPrincipalRecord) error

func (*AuthStore) UpsertRole

func (s *AuthStore) UpsertRole(ctx context.Context, role store.AuthRoleRecord) error

func (*AuthStore) UpsertTenantBinding

func (s *AuthStore) UpsertTenantBinding(ctx context.Context, binding store.AuthTenantBindingRecord) error

type BinaryStore

type BinaryStore struct {
	// contains filtered or unexported fields
}

BinaryStore persists inline binary payloads in Postgres.

func (*BinaryStore) Delete

func (s *BinaryStore) Delete(ctx context.Context, key string) error

func (*BinaryStore) Get

func (s *BinaryStore) Get(ctx context.Context, key string) (*store.BinaryObject, error)

func (*BinaryStore) Put

type BlobChunkStore

type BlobChunkStore = PostgresBlobStore

BlobChunkStore is kept as a compatibility alias for earlier naming.

type BlobMetadataStore

type BlobMetadataStore struct {
	// contains filtered or unexported fields
}

BlobMetadataStore persists blob manifests, links, sync status, and transfer sessions.

func (*BlobMetadataStore) CreateDownloadSession

func (s *BlobMetadataStore) CreateDownloadSession(ctx context.Context, session binary.DownloadSession) error

func (*BlobMetadataStore) CreateUploadSession

func (s *BlobMetadataStore) CreateUploadSession(ctx context.Context, session binary.UploadSession) error
func (s *BlobMetadataStore) DeleteBinaryLink(ctx context.Context, resourceID string) error
func (s *BlobMetadataStore) DeleteDocumentLink(ctx context.Context, documentID string, contentIndex int) error

func (*BlobMetadataStore) DeleteDownloadSession

func (s *BlobMetadataStore) DeleteDownloadSession(ctx context.Context, id string) error

func (*BlobMetadataStore) DeleteManifest

func (s *BlobMetadataStore) DeleteManifest(ctx context.Context, blobID string) error

func (*BlobMetadataStore) DeleteSyncStatus

func (s *BlobMetadataStore) DeleteSyncStatus(ctx context.Context, blobID string) error

func (*BlobMetadataStore) DeleteUploadSession

func (s *BlobMetadataStore) DeleteUploadSession(ctx context.Context, id string) error
func (s *BlobMetadataStore) GetBinaryLink(ctx context.Context, resourceID string) (*binary.BinaryLink, error)
func (s *BlobMetadataStore) GetDocumentLink(ctx context.Context, documentID string, contentIndex int) (*binary.DocumentAttachmentLink, error)

func (*BlobMetadataStore) GetDownloadSession

func (s *BlobMetadataStore) GetDownloadSession(ctx context.Context, id string) (*binary.DownloadSession, error)

func (*BlobMetadataStore) GetManifest

func (s *BlobMetadataStore) GetManifest(ctx context.Context, blobID string) (*binary.BlobManifest, error)

func (*BlobMetadataStore) GetManifestByHash

func (s *BlobMetadataStore) GetManifestByHash(ctx context.Context, sha256 string) (*binary.BlobManifest, error)

func (*BlobMetadataStore) GetSyncStatus

func (s *BlobMetadataStore) GetSyncStatus(ctx context.Context, blobID string) (binary.BlobSyncStatus, error)

func (*BlobMetadataStore) GetUploadSession

func (s *BlobMetadataStore) GetUploadSession(ctx context.Context, id string) (*binary.UploadSession, error)
func (s *BlobMetadataStore) PutBinaryLink(ctx context.Context, link binary.BinaryLink) error
func (s *BlobMetadataStore) PutDocumentLink(ctx context.Context, link binary.DocumentAttachmentLink) error

func (*BlobMetadataStore) PutManifest

func (s *BlobMetadataStore) PutManifest(ctx context.Context, manifest binary.BlobManifest) error

func (*BlobMetadataStore) PutSyncStatus

func (s *BlobMetadataStore) PutSyncStatus(ctx context.Context, blobID string, status binary.BlobSyncStatus) error

func (*BlobMetadataStore) UpdateDownloadSession

func (s *BlobMetadataStore) UpdateDownloadSession(ctx context.Context, session binary.DownloadSession) error

func (*BlobMetadataStore) UpdateUploadSession

func (s *BlobMetadataStore) UpdateUploadSession(ctx context.Context, session binary.UploadSession) error

type BlobStore

type BlobStore struct {
	// contains filtered or unexported fields
}

BlobStore persists blob payloads or external location references in Postgres.

func (*BlobStore) Delete

func (s *BlobStore) Delete(ctx context.Context, key string) error

func (*BlobStore) Get

func (s *BlobStore) Get(ctx context.Context, key string) (*store.BlobObject, error)

func (*BlobStore) Head

func (s *BlobStore) Head(ctx context.Context, key string) (*store.BlobObject, error)

func (*BlobStore) Open

Open streams a blob. The BYTEA column is loaded in full, then wrapped in a reader; use an object-store adapter for multi-GB objects. In-store Location pointers are followed here. A URI Location without payload is an error, not an empty body.

func (*BlobStore) Put

func (s *BlobStore) Put(ctx context.Context, obj store.BlobObject) error

func (*BlobStore) PutStream

func (s *BlobStore) PutStream(ctx context.Context, key, contentType string, size int64, r io.Reader) error

PutStream uploads from r. The hai_binary_object.data column is BYTEA, so this implementation materializes the reader before INSERT. Use an object-store adapter (S3) or filesystem lakehouse partitions for multi-GB parquet objects.

type ConflictStore

type ConflictStore struct {
	// contains filtered or unexported fields
}

ConflictStore records rejected and conflicted writes in Postgres.

func (*ConflictStore) Append

func (s *ConflictStore) Append(ctx context.Context, record store.ConflictRecord) error

func (*ConflictStore) List

func (s *ConflictStore) List(ctx context.Context, resourceType, resourceID string) ([]store.ConflictRecord, error)

func (*ConflictStore) Resolve

func (s *ConflictStore) Resolve(ctx context.Context, id string, resolvedAt time.Time) error

type CursorStore

type CursorStore struct {
	// contains filtered or unexported fields
}

CursorStore persists named sync cursors in Postgres.

func (*CursorStore) DeleteCursor

func (s *CursorStore) DeleteCursor(ctx context.Context, name string) error

func (*CursorStore) GetCursor

func (s *CursorStore) GetCursor(ctx context.Context, name string) (*store.Cursor, error)

func (*CursorStore) UpsertCursor

func (s *CursorStore) UpsertCursor(ctx context.Context, cursor store.Cursor) error

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB owns the shared Postgres connection pool, migration runner, and tenant accessors.

func Open

func Open(ctx context.Context, dsn string, opts ...Option) (*DB, error)

Open opens a Postgres connection pool at dsn with default pool settings.

func ReadReplica

func ReadReplica(ctx context.Context, dsn string, opts ...Option) (*DB, error)

ReadReplica opens a read-only connection pool for analytics queries. Writes through this pool are not supported; use the primary DB for mutations.

func (*DB) Close

func (db *DB) Close()

Close closes the underlying connection pool.

func (*DB) DefinitionStore

func (db *DB) DefinitionStore() *DefinitionStore

DefinitionStore returns the global FHIR definition catalog store.

func (*DB) EnsureTenant

func (db *DB) EnsureTenant(ctx context.Context, tenantID string) error

EnsureTenant registers a tenant row if it does not already exist.

func (*DB) GlobalTerminologyStore

func (db *DB) GlobalTerminologyStore() *TerminologyStore

GlobalTerminologyStore returns the platform-wide terminology catalog store.

func (*DB) Migrate

func (db *DB) Migrate(ctx context.Context) error

Migrate runs embedded numbered SQL migrations.

func (*DB) PackageInstallStore

func (db *DB) PackageInstallStore() *PackageInstallStore

PackageInstallStore returns the global package install completion store.

func (*DB) Pool

func (db *DB) Pool() *pgxpool.Pool

Pool returns the underlying pgx pool for advanced use.

func (*DB) Schema

func (db *DB) Schema() string

Schema returns the configured Postgres schema for haistack tables.

func (*DB) Tenant

func (db *DB) Tenant(tenantID string) *TenantDB

Tenant returns a tenant-scoped database accessor.

func (*DB) TerminologyStore

func (db *DB) TerminologyStore(scopeID string) *TerminologyStore

TerminologyStore returns a terminology store scoped to the supplied tenant.

type DefinitionStore

type DefinitionStore struct {
	// contains filtered or unexported fields
}

DefinitionStore persists the global FHIR definition catalog in Postgres.

func (*DefinitionStore) Delete

func (s *DefinitionStore) Delete(ctx context.Context, canonicalURL, version string) error

func (*DefinitionStore) Get

func (s *DefinitionStore) Get(ctx context.Context, canonicalURL, version string) (*store.DefinitionResourceRecord, error)

func (*DefinitionStore) List

func (*DefinitionStore) Upsert

type EventStore

type EventStore struct {
	// contains filtered or unexported fields
}

EventStore persists append-only accepted-write events in Postgres.

func (*EventStore) Append

func (*EventStore) LatestForResource

func (s *EventStore) LatestForResource(ctx context.Context, resourceType, id string) (*store.ResourceEvent, error)

func (*EventStore) ReadSince

func (s *EventStore) ReadSince(ctx context.Context, afterSequence int64, limit int) ([]store.ResourceEvent, error)

type HistoryStore

type HistoryStore struct {
	// contains filtered or unexported fields
}

HistoryStore persists immutable resource version history in Postgres.

func (*HistoryStore) AppendVersion

func (s *HistoryStore) AppendVersion(ctx context.Context, version store.ResourceVersion) error

func (*HistoryStore) GetHistory

func (s *HistoryStore) GetHistory(ctx context.Context, resourceType, id string) ([]store.ResourceVersion, error)

func (*HistoryStore) GetVersion

func (s *HistoryStore) GetVersion(ctx context.Context, resourceType, id, versionID string) (store.ResourceVersion, error)

type IDRegistry

type IDRegistry struct {
	// contains filtered or unexported fields
}

IDRegistry manages authoritative resource ID registration per tenant.

func (*IDRegistry) Check

func (s *IDRegistry) Check(ctx context.Context, resourceType, id string) (bool, error)

func (*IDRegistry) Register

func (s *IDRegistry) Register(ctx context.Context, resourceType, id string) error

func (*IDRegistry) Reserve

func (s *IDRegistry) Reserve(ctx context.Context, resourceType, id string) error

type InboxStore

type InboxStore struct {
	// contains filtered or unexported fields
}

InboxStore tracks applied sync operations for idempotency.

func (*InboxStore) AppliedAt

func (s *InboxStore) AppliedAt(ctx context.Context, id string) (*time.Time, error)

AppliedAt returns when a remote operation was applied, if recorded.

func (*InboxStore) ClaimPush

func (s *InboxStore) ClaimPush(ctx context.Context, id string, claimedAt time.Time) (bool, error)

ClaimPush atomically claims a previously unseen push event ID for this transaction. PostgreSQL waits for a concurrent claimant to commit or roll back before resolving the conflict, so only one transaction performs the resource/conflict side effects for a first delivery.

func (*InboxStore) GetAckPayload

func (s *InboxStore) GetAckPayload(ctx context.Context, id string) ([]byte, bool, error)

GetAckPayload returns the stored push acknowledgement, if the inbox row exists. Pull inbox rows have no acknowledgement payload.

func (*InboxStore) IsApplied

func (s *InboxStore) IsApplied(ctx context.Context, id string) (bool, error)

IsApplied reports whether a remote operation has already been applied.

func (*InboxStore) MarkApplied

func (s *InboxStore) MarkApplied(ctx context.Context, id string, appliedAt time.Time) error

MarkApplied records that a remote operation has been applied.

func (*InboxStore) MarkAppliedWithPayload

func (s *InboxStore) MarkAppliedWithPayload(ctx context.Context, id string, payload []byte, appliedAt time.Time) error

MarkAppliedWithPayload records a hub acknowledgement together with the idempotency marker. Existing acknowledgement payloads are preserved on an idempotent retry.

type JobStore

type JobStore struct {
	// contains filtered or unexported fields
}

JobStore persists background jobs in Postgres.

func (*JobStore) ClaimNext

func (s *JobStore) ClaimNext(ctx context.Context, jobType string) (*store.JobRecord, error)

func (*JobStore) Delete

func (s *JobStore) Delete(ctx context.Context, id string) error

func (*JobStore) Enqueue

func (s *JobStore) Enqueue(ctx context.Context, job store.JobRecord) error

func (*JobStore) Get

func (s *JobStore) Get(ctx context.Context, id string) (*store.JobRecord, error)

func (*JobStore) Update

func (s *JobStore) Update(ctx context.Context, job store.JobRecord) error

func (*JobStore) UpdateIf

func (s *JobStore) UpdateIf(ctx context.Context, job store.JobRecord, expectedUpdatedAt time.Time) (bool, error)

type MaterializedViewStore

type MaterializedViewStore struct {
	// contains filtered or unexported fields
}

MaterializedViewStore persists named materialized projections in Postgres.

func (*MaterializedViewStore) Delete

func (s *MaterializedViewStore) Delete(ctx context.Context, viewName, key string) error

func (*MaterializedViewStore) Get

func (*MaterializedViewStore) ListKeys

func (s *MaterializedViewStore) ListKeys(ctx context.Context, viewName string) ([]string, error)

func (*MaterializedViewStore) Upsert

type ModuleStore

type ModuleStore struct {
	// contains filtered or unexported fields
}

ModuleStore persists module registration metadata in Postgres.

func (*ModuleStore) Get

func (s *ModuleStore) Get(ctx context.Context, name string) (*store.ModuleRecord, error)

func (*ModuleStore) List

func (s *ModuleStore) List(ctx context.Context) ([]store.ModuleRecord, error)

func (*ModuleStore) Register

func (s *ModuleStore) Register(ctx context.Context, module store.ModuleRecord) error

func (*ModuleStore) Unregister

func (s *ModuleStore) Unregister(ctx context.Context, name string) error

type NodeRegistry

type NodeRegistry struct {
	// contains filtered or unexported fields
}

NodeRegistry persists edge and cloud node metadata in Postgres.

func (*NodeRegistry) Get

func (s *NodeRegistry) Get(ctx context.Context, nodeID string) (*store.NodeRecord, error)

func (*NodeRegistry) List

func (s *NodeRegistry) List(ctx context.Context) ([]store.NodeRecord, error)

func (*NodeRegistry) Register

func (s *NodeRegistry) Register(ctx context.Context, node store.NodeRecord) error

func (*NodeRegistry) Unregister

func (s *NodeRegistry) Unregister(ctx context.Context, nodeID string) error

type Option

type Option func(*options)

Option configures an opened Postgres database pool.

func WithMaxConns

func WithMaxConns(n int32) Option

WithMaxConns sets the maximum number of connections in the pool.

func WithMinConns

func WithMinConns(n int32) Option

WithMinConns sets the minimum number of connections in the pool.

func WithSchema

func WithSchema(name string) Option

WithSchema sets the Postgres schema for haistack tables. Defaults to public.

type PackageInstallStore

type PackageInstallStore struct {
	// contains filtered or unexported fields
}

PackageInstallStore tracks completed FHIR package version installs in Postgres.

func (*PackageInstallStore) IsComplete

func (s *PackageInstallStore) IsComplete(ctx context.Context, packageName, packageVersion string) (bool, error)

func (*PackageInstallStore) MarkComplete

func (s *PackageInstallStore) MarkComplete(ctx context.Context, packageName, packageVersion string, completedAt time.Time) error

type PostgresBlobStore

type PostgresBlobStore struct {
	// contains filtered or unexported fields
}

PostgresBlobStore persists full blob bytes in Postgres via chunk tables. This is distinct from the legacy BlobStore backed by binary_object.

func (*PostgresBlobStore) AppendChunk

func (s *PostgresBlobStore) AppendChunk(ctx context.Context, key string, index int, data []byte) error

AppendChunk stores one chunk for a blob or staging key.

func (*PostgresBlobStore) Delete

func (s *PostgresBlobStore) Delete(ctx context.Context, blobID string) error

Delete removes blob chunks and manifest.

func (*PostgresBlobStore) DeleteChunks

func (s *PostgresBlobStore) DeleteChunks(ctx context.Context, key string) error

DeleteChunks removes all chunks for a key.

func (*PostgresBlobStore) Get

Get reads a finalized blob by assembling stored chunks.

func (*PostgresBlobStore) Head

Head returns blob metadata without reading payload bytes.

func (*PostgresBlobStore) ListChunkCount

func (s *PostgresBlobStore) ListChunkCount(ctx context.Context, key string) (int, error)

ListChunkCount returns contiguous chunk count starting at index 0.

func (*PostgresBlobStore) Metadata

func (s *PostgresBlobStore) Metadata() *BlobMetadataStore

Metadata returns the metadata store sharing this connection.

func (*PostgresBlobStore) Open

Open streams a finalized blob one chunk at a time.

func (*PostgresBlobStore) Put

func (s *PostgresBlobStore) Put(ctx context.Context, blobID string, data []byte, contentType string) (*binary.BlobDescriptor, error)

Put stores a finalized blob as chunked bytes in Postgres.

func (*PostgresBlobStore) PutStream

func (s *PostgresBlobStore) PutStream(ctx context.Context, blobID string, r io.Reader, size int64, contentType string) (*binary.BlobDescriptor, error)

PutStream stores a finalized blob by reading r in DefaultChunkSize slices.

func (*PostgresBlobStore) ReadChunk

func (s *PostgresBlobStore) ReadChunk(ctx context.Context, key string, index int) ([]byte, error)

ReadChunk reads one stored chunk.

type RegistryInstallStore

type RegistryInstallStore struct {
	// contains filtered or unexported fields
}

RegistryInstallStore persists tenant-scoped registry enablement and install references.

func (*RegistryInstallStore) Delete

func (*RegistryInstallStore) ListEnabled

func (*RegistryInstallStore) ListInstalled

func (*RegistryInstallStore) SetEnabled

func (*RegistryInstallStore) UpsertInstall

func (s *RegistryInstallStore) UpsertInstall(ctx context.Context, record store.RegistryInstallRecord) error

type ReportingTableStore

type ReportingTableStore struct {
	// contains filtered or unexported fields
}

ReportingTableStore persists tenant-scoped analytics reporting tables in Postgres.

func (*ReportingTableStore) GetMeta

func (s *ReportingTableStore) GetMeta(ctx context.Context, viewName, viewVersion string) (*store.ReportingTableMeta, error)

func (*ReportingTableStore) QueryRows

func (s *ReportingTableStore) QueryRows(ctx context.Context, viewName, viewVersion string) ([]map[string]any, error)

func (*ReportingTableStore) Refresh

func (s *ReportingTableStore) Refresh(ctx context.Context, meta store.ReportingTableMeta, rows []map[string]any) error

type ResourceStore

type ResourceStore struct {
	// contains filtered or unexported fields
}

ResourceStore persists current resource state in Postgres.

func (*ResourceStore) Create

func (*ResourceStore) Delete

func (s *ResourceStore) Delete(ctx context.Context, resourceType, id string) error

func (*ResourceStore) DeleteIfVersion

func (s *ResourceStore) DeleteIfVersion(ctx context.Context, resourceType, id, expectedVersion string) (bool, error)

DeleteIfVersion atomically deletes a resource only when its current version matches expectedVersion. The wildcard version "*" matches any existing version.

func (*ResourceStore) Exists

func (s *ResourceStore) Exists(ctx context.Context, resourceType, id string) (bool, error)

func (*ResourceStore) ListIDs

func (s *ResourceStore) ListIDs(ctx context.Context, resourceType string, limit, offset int) ([]string, error)

ListIDs returns resource IDs for one type in stable id order.

func (*ResourceStore) Read

func (s *ResourceStore) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)

func (*ResourceStore) Update

func (*ResourceStore) UpdateIfVersion

func (s *ResourceStore) UpdateIfVersion(ctx context.Context, res *types.ResourceEnvelope, expectedVersion string) (bool, error)

UpdateIfVersion atomically replaces a resource only when its current version matches expectedVersion. The wildcard version "*" matches any existing version.

type SearchStore

type SearchStore struct {
	// contains filtered or unexported fields
}

SearchStore persists typed search index rows in Postgres.

func (*SearchStore) FieldValues

func (s *SearchStore) FieldValues(ctx context.Context, resourceType, fieldKey string, resourceIDs []string) (map[string]string, error)

FieldValues returns one indexed value per resource ID for a typed field key.

func (*SearchStore) Index

func (s *SearchStore) Index(ctx context.Context, entry store.SearchIndexEntry) error

func (*SearchStore) ListIndexedResourceIDs

func (s *SearchStore) ListIndexedResourceIDs(ctx context.Context, resourceType string) ([]string, error)

ListIndexedResourceIDs returns distinct resource IDs with any search index row.

func (*SearchStore) Lookup

func (s *SearchStore) Lookup(ctx context.Context, key, value string) ([]string, error)

func (*SearchStore) LookupFullText

func (s *SearchStore) LookupFullText(ctx context.Context, resourceType, queryText string) (store.FullTextMatch, error)

LookupFullText returns resource IDs ranked by Postgres full-text relevance.

func (*SearchStore) LookupMatch

func (s *SearchStore) LookupMatch(ctx context.Context, match store.SearchMatch) ([]string, error)

LookupMatch returns resource IDs matching one typed predicate within a resource type.

func (*SearchStore) LookupReferences

func (s *SearchStore) LookupReferences(ctx context.Context, resourceType, fieldKey string, sourceIDs []string) (map[string][]store.ReferenceLink, error)

LookupReferences returns indexed reference links for source resources.

func (*SearchStore) LookupReferencing

func (s *SearchStore) LookupReferencing(ctx context.Context, sourceType, fieldKey, targetType, targetID string) ([]string, error)

LookupReferencing returns source resource IDs referencing a target resource.

func (*SearchStore) QueryPrepared

func (s *SearchStore) QueryPrepared(ctx context.Context, query store.PreparedQuery, args map[string]string) ([]string, error)

func (*SearchStore) RemoveIndex

func (s *SearchStore) RemoveIndex(ctx context.Context, resourceType, id string) error

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session coordinates transaction-scoped store access for atomic writes.

func (*Session) ApplyWrite

func (s *Session) ApplyWrite(ctx context.Context, input Write) (*WriteResult, error)

ApplyWrite applies one write inside this session transaction.

func (*Session) AuditStore

func (s *Session) AuditStore() store.AuditStore

AuditStore returns the transaction-scoped audit store.

func (*Session) BinaryMetadataStore

func (s *Session) BinaryMetadataStore() binary.MetadataStore

BinaryMetadataStore returns the transaction-scoped blob metadata store.

func (*Session) Commit

func (s *Session) Commit(ctx context.Context) error

Commit commits the session transaction.

func (*Session) ConflictStore

func (s *Session) ConflictStore() store.ConflictStore

ConflictStore returns the transaction-scoped conflict store.

func (*Session) CursorStore

func (s *Session) CursorStore() store.CursorStore

CursorStore returns the transaction-scoped cursor store.

func (*Session) EventStore

func (s *Session) EventStore() store.EventStore

EventStore returns the transaction-scoped event store.

func (*Session) HistoryStore

func (s *Session) HistoryStore() store.HistoryStore

HistoryStore returns the transaction-scoped history store.

func (*Session) IDRegistry

func (s *Session) IDRegistry() store.IDRegistryStore

IDRegistry returns the transaction-scoped ID registry store.

func (*Session) InboxStore

func (s *Session) InboxStore() store.InboxStore

InboxStore returns the transaction-scoped sync inbox store.

func (*Session) JobStore

func (s *Session) JobStore() store.JobStore

JobStore returns the transaction-scoped background job store.

func (*Session) ResourceStore

func (s *Session) ResourceStore() store.ResourceStore

ResourceStore returns the transaction-scoped resource store.

func (*Session) Rollback

func (s *Session) Rollback(ctx context.Context) error

Rollback rolls back the session transaction.

func (*Session) SearchStore

func (s *Session) SearchStore() store.SearchStore

SearchStore returns the transaction-scoped search store.

func (*Session) TerminologyStore

func (s *Session) TerminologyStore() store.TerminologyStore

TerminologyStore returns the transaction-scoped terminology projection store.

type SubscriptionDeliveryStore

type SubscriptionDeliveryStore struct {
	// contains filtered or unexported fields
}

SubscriptionDeliveryStore persists delivery logs in Postgres.

func (*SubscriptionDeliveryStore) Append

Append implements store.SubscriptionDeliveryStore.

func (*SubscriptionDeliveryStore) Get

Get implements store.SubscriptionDeliveryStore.

func (*SubscriptionDeliveryStore) List

List implements store.SubscriptionDeliveryStore.

func (*SubscriptionDeliveryStore) Update

Update implements store.SubscriptionDeliveryStore.

type SubscriptionStore

type SubscriptionStore struct {
	// contains filtered or unexported fields
}

SubscriptionStore persists subscription definitions in Postgres.

func (*SubscriptionStore) Create

Create implements store.SubscriptionStore.

func (*SubscriptionStore) Delete

func (s *SubscriptionStore) Delete(ctx context.Context, id string) error

Delete implements store.SubscriptionStore.

func (*SubscriptionStore) Get

Get implements store.SubscriptionStore.

func (*SubscriptionStore) List

List implements store.SubscriptionStore.

func (*SubscriptionStore) Update

Update implements store.SubscriptionStore.

type TenantDB

type TenantDB struct {
	// contains filtered or unexported fields
}

TenantDB scopes all store operations to one tenant.

func (*TenantDB) AnalyticsStore

func (tdb *TenantDB) AnalyticsStore() *AnalyticsStore

AnalyticsStore returns a tenant-scoped analytics store.

func (*TenantDB) ApplyWrite

func (tdb *TenantDB) ApplyWrite(ctx context.Context, input Write) (*WriteResult, error)

ApplyWrite commits an accepted, rejected, or conflicted write atomically.

func (*TenantDB) AuditStore

func (tdb *TenantDB) AuditStore() *AuditStore

AuditStore returns a tenant-scoped audit store.

func (*TenantDB) AuthStore

func (tdb *TenantDB) AuthStore() *AuthStore

AuthStore returns a tenant-scoped auth persistence adapter.

func (*TenantDB) BeginSession

func (tdb *TenantDB) BeginSession(ctx context.Context) (*Session, error)

BeginSession starts a tenant-scoped transaction session.

func (*TenantDB) BeginWrite

func (tdb *TenantDB) BeginWrite(ctx context.Context) (store.WriteSession, error)

BeginWrite starts a tenant-scoped atomic write session.

func (*TenantDB) BinaryStore

func (tdb *TenantDB) BinaryStore() *BinaryStore

BinaryStore returns a tenant-scoped binary store.

func (*TenantDB) BlobMetadataStore

func (tdb *TenantDB) BlobMetadataStore() *BlobMetadataStore

BlobMetadataStore returns a tenant-scoped blob metadata store.

func (*TenantDB) BlobStore

func (tdb *TenantDB) BlobStore() *BlobStore

BlobStore returns a tenant-scoped blob store.

func (*TenantDB) ChunkBlobStore

func (tdb *TenantDB) ChunkBlobStore() *BlobChunkStore

ChunkBlobStore returns a tenant-scoped chunked blob store.

func (*TenantDB) ConflictStore

func (tdb *TenantDB) ConflictStore() *ConflictStore

ConflictStore returns a tenant-scoped conflict store.

func (*TenantDB) CursorStore

func (tdb *TenantDB) CursorStore() *CursorStore

CursorStore returns a tenant-scoped cursor store.

func (*TenantDB) EventStore

func (tdb *TenantDB) EventStore() *EventStore

EventStore returns a tenant-scoped event store.

func (*TenantDB) HistoryStore

func (tdb *TenantDB) HistoryStore() *HistoryStore

HistoryStore returns a tenant-scoped history store.

func (*TenantDB) IDRegistry

func (tdb *TenantDB) IDRegistry() *IDRegistry

IDRegistry returns a tenant-scoped ID registry store.

func (*TenantDB) InboxStore

func (tdb *TenantDB) InboxStore() *InboxStore

InboxStore returns a tenant-scoped inbox idempotency store.

func (*TenantDB) JobStore

func (tdb *TenantDB) JobStore() *JobStore

JobStore returns a tenant-scoped job store.

func (*TenantDB) MaterializedViewStore

func (tdb *TenantDB) MaterializedViewStore() *MaterializedViewStore

MaterializedViewStore returns a tenant-scoped materialized view store.

func (*TenantDB) ModuleStore

func (tdb *TenantDB) ModuleStore() *ModuleStore

ModuleStore returns a tenant-scoped module store.

func (*TenantDB) NodeRegistry

func (tdb *TenantDB) NodeRegistry() *NodeRegistry

NodeRegistry returns a tenant-scoped node registry store.

func (*TenantDB) PingReadReplica

func (tdb *TenantDB) PingReadReplica(ctx context.Context) error

PingReadReplica verifies connectivity to the read pool when configured.

func (*TenantDB) PostgresBlobStore

func (tdb *TenantDB) PostgresBlobStore() *PostgresBlobStore

PostgresBlobStore returns a tenant-scoped chunked blob store.

func (*TenantDB) ReadOnlyResourceStore

func (tdb *TenantDB) ReadOnlyResourceStore() *ResourceStore

ReadOnlyResourceStore returns a tenant-scoped resource store backed by the read replica pool when configured, otherwise the primary pool.

func (*TenantDB) RegistryInstallStore

func (tdb *TenantDB) RegistryInstallStore() *RegistryInstallStore

RegistryInstallStore returns a tenant-scoped registry install overlay store.

func (*TenantDB) ReportingTableStore

func (tdb *TenantDB) ReportingTableStore() *ReportingTableStore

ReportingTableStore returns a tenant-scoped analytics reporting table store.

func (*TenantDB) ResourceStore

func (tdb *TenantDB) ResourceStore() *ResourceStore

ResourceStore returns a tenant-scoped resource store.

func (*TenantDB) SearchStore

func (tdb *TenantDB) SearchStore() *SearchStore

SearchStore returns a tenant-scoped search store.

func (*TenantDB) SubscriptionDeliveryStore

func (tdb *TenantDB) SubscriptionDeliveryStore() *SubscriptionDeliveryStore

SubscriptionDeliveryStore returns a tenant-scoped delivery log store.

func (*TenantDB) SubscriptionStore

func (tdb *TenantDB) SubscriptionStore() *SubscriptionStore

SubscriptionStore returns a tenant-scoped subscription registry store.

func (*TenantDB) TenantID

func (tdb *TenantDB) TenantID() string

TenantID returns the tenant identifier for this accessor.

func (*TenantDB) TerminologyInstallStore

func (tdb *TenantDB) TerminologyInstallStore() *TerminologyInstallStore

TerminologyInstallStore returns a tenant-scoped terminology pack opt-in store.

func (*TenantDB) TerminologyStore

func (tdb *TenantDB) TerminologyStore() *TerminologyStore

TerminologyStore returns a tenant-scoped terminology projection store.

func (*TenantDB) WithReadPool

func (tdb *TenantDB) WithReadPool(readPool *pgxpool.Pool) *TenantDB

WithReadPool attaches a read-only pool for read-scoped store accessors.

type TerminologyInstallStore

type TerminologyInstallStore struct {
	// contains filtered or unexported fields
}

TerminologyInstallStore persists tenant-scoped terminology pack enablement.

func (*TerminologyInstallStore) Delete

func (*TerminologyInstallStore) ListEnabled

func (*TerminologyInstallStore) ListInstalled

func (*TerminologyInstallStore) SetEnabled

func (*TerminologyInstallStore) UpsertInstall

type TerminologyInstallStoreFactory

type TerminologyInstallStoreFactory struct {
	// contains filtered or unexported fields
}

TerminologyInstallStoreFactory resolves Postgres terminology opt-in stores per tenant.

func NewTerminologyInstallStoreFactory

func NewTerminologyInstallStoreFactory(db *DB) *TerminologyInstallStoreFactory

NewTerminologyInstallStoreFactory returns a factory backed by db.

func (*TerminologyInstallStoreFactory) ForTenant

ForTenant returns the terminology install store for tenantID.

type TerminologyStore

type TerminologyStore struct {
	// contains filtered or unexported fields
}

func (*TerminologyStore) DeleteProjections

func (s *TerminologyStore) DeleteProjections(ctx context.Context, scope, typ, url, ver string) error

func (*TerminologyStore) DeleteResource

func (s *TerminologyStore) DeleteResource(ctx context.Context, scope, typ, url, ver string) error

func (*TerminologyStore) FindResource

func (s *TerminologyStore) FindResource(ctx context.Context, scope, typ, url, ver string) (*store.TerminologyResourceRecord, error)

func (*TerminologyStore) GetValueSet

func (s *TerminologyStore) GetValueSet(ctx context.Context, scope, url, ver string) (*store.TerminologyValueSetRecord, error)

func (*TerminologyStore) ListResources

func (s *TerminologyStore) ListResources(ctx context.Context, scope, typ string) ([]store.TerminologyResourceRecord, error)

func (*TerminologyStore) ListValueSetMembers

func (s *TerminologyStore) ListValueSetMembers(ctx context.Context, scope, url, ver string) ([]store.TerminologyExpansionMemberRecord, error)

func (*TerminologyStore) LookupConcept

func (s *TerminologyStore) LookupConcept(ctx context.Context, scope, url, ver, code string) (*store.TerminologyConceptRecord, error)

func (*TerminologyStore) PutResource

func (*TerminologyStore) ReplaceCodeSystem

func (s *TerminologyStore) ReplaceCodeSystem(ctx context.Context, scope, url, ver string, cs []store.TerminologyConceptRecord) error

type Write

type Write struct {
	Resource        *types.ResourceEnvelope
	Action          store.VersionAction
	SearchEntries   []store.SearchIndexEntry
	RequestedID     string
	ExpectedVersion string
	EventID         string
	OriginNodeID    string
	LocalVersionID  string
	Audit           store.AuditRecord

	Outcome                 WriteOutcome
	RejectionReason         string
	ConflictLocalVersionID  string
	ConflictRemoteVersionID string
}

Write bundles inputs for one atomic write pipeline.

type WriteOutcome

type WriteOutcome string

WriteOutcome describes whether a write was accepted, rejected, or conflicted.

const (
	WriteOutcomeAccepted   WriteOutcome = "accepted"
	WriteOutcomeRejected   WriteOutcome = "rejected"
	WriteOutcomeConflicted WriteOutcome = "conflicted"
)

type WriteResult

type WriteResult struct {
	Resource   *types.ResourceEnvelope
	Version    store.ResourceVersion
	Event      store.ResourceEvent
	IDRegistry store.IDRegistryResult
	ConflictID string
	Outcome    WriteOutcome
}

WriteResult returns persisted write outputs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL