sqlite

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: 17 Imported by: 0

README

haistack-sqlite (pkg/sqlite)

Embedded offline database for haistack local deployments.

What it does

haistack-sqlite is the local database for haistack. It saves FHIR resources and related data to a SQLite file on disk — on a device, tablet, workstation, or small edge node — so the app works offline.

Think of it as: save Patient/Observation JSON locally, keep history, index for lookup, and queue changes for sync — all in one place.

When you save a resource, SQLite keeps several things in sync:

Piece What it is
Current resource Latest version of each Patient, Observation, etc.
History Every past version (including deletes)
Search index Fast lookup by field (e.g. family name → patient IDs)
Outbox A log of local changes, for sync later
Cursors “Where did the sync worker leave off?” checkpoints

It also has tables for conflicts, small binaries, module metadata, inbox idempotency, background jobs, and audit logs. The main job is local FHIR persistence + sync prep.

It implements the pkg/store interfaces on top of SQLite. Other code depends on store.ResourceStore, not on SQLite directly. Background workers use DB.JobStore() with pkg/jobs; audit emitters use DB.AuditStore() with pkg/audit.

It does not:

  • Parse FHIR or assign version numbers (pkg/types, pkg/core, etc.)
  • Run FHIR search queries (only stores pre-built index entries)
  • Talk to the cloud (sync layers read the outbox)
  • Replace Postgres for multi-tenant/cloud (pkg/postgres)

When to use it

  • Embedded local storage on a device or edge node
  • Offline-first apps that need durable FHIR resource state
  • Atomic local writes where resource, history, outbox, and search must stay consistent
  • Tests that need a real persistence layer without Postgres

Usage

Open the database and run migrations:

import (
    "context"

    "github.com/degoke/haistack/pkg/sqlite"
)

db, err := sqlite.Open("/path/to/haistack.db")
if err != nil {
    // handle error
}
defer db.Close()

if err := db.Migrate(context.Background()); err != nil {
    // handle error
}

Use sqlite.Open(":memory:") for an in-memory database in tests.

Simple reads and writes (one store at a time):

resources := db.ResourceStore()

err := resources.Create(ctx, envelope)
env, err := resources.Read(ctx, "Patient", "pat-1")
err = resources.Delete(ctx, "Patient", "pat-1")

Same pattern for history, search, outbox, and cursors via db.HistoryStore(), db.SearchStore(), db.OutboxStore(), db.CursorStore(), and so on.

Full local write (recommended for creates, updates, deletes):

When you change a resource, update current state, history, outbox event, and search index together. If any step fails, nothing is half-saved.

import "github.com/degoke/haistack/pkg/store"

result, err := db.ApplyLocalWrite(ctx, sqlite.LocalWrite{
    Resource:      envelope, // from pkg/types
    Action:        store.VersionActionCreate,
    Version:       version,  // caller supplies version ID
    Event:         event,    // change notification for sync
    SearchEntries: []store.SearchIndexEntry{
        {
            ResourceType: "Patient",
            ID:           "pat-1",
            Fields:       map[string]string{"string.family": "Doe"},
        },
    },
})
// result.Event.Sequence is the outbox sequence number

Manual transaction (same guarantee, more control):

session, err := db.BeginWrite(ctx)
if err != nil {
    // handle error
}

session.ResourceStore().Create(ctx, envelope)
session.HistoryStore().AppendVersion(ctx, version)
session.EventStore().Append(ctx, event)
session.SearchStore().Index(ctx, entry)

err = session.Commit(ctx)

Search index field keys

SearchStore routes fields to typed tables using key prefixes:

Prefix Table
token.<name> search_token
string.<name> search_string
date.<name> search_date
number.<name> search_number
reference.<name> or ref.<name> search_reference
uri.<name> search_string

Keys without a prefix (for example family) default to search_string. FHIR search parsing stays in pkg/search; this package only stores prepared entries.

Mental model

pkg/types   → wrap/normalize FHIR JSON (ResourceEnvelope)
pkg/core    → business rules, version IDs, write pipeline
pkg/store   → interfaces (what “storage” means)
pkg/sqlite  → actual SQLite file + tables + atomic writes

One line: pkg/sqlite is the offline filing cabinet — it keeps resources, their history, search indexes, and a change log ready for sync, with the guarantee that a local write either fully succeeds or fully rolls back.

Where it fits

Layer Role
types Canonical JSON and ResourceEnvelope
store Persistence contracts
sqlite Embedded local SQLite implementation
postgres Tenant-scoped edge/cloud implementation
core Orchestrates write pipelines on top of store interfaces

MVP limits

  • Pure Go driver (modernc.org/sqlite); no CGO
  • Canonical JSON in ResourceEnvelope.JSON; no proto-only storage
  • Version assignment and search extraction stay outside this package
  • Inbox, conflict, binary, and module stores persist data but omit full upstream workflows (sync apply, reconciliation, blob offload, module activation)
  • Encrypted SQLite, backup/restore, and multi-profile DBs are out of scope

See doc.go for the full API, schema tables, and file layout.

Documentation

Overview

Package sqlite implements haistack-sqlite, the embedded offline database layer for haistack local deployments.

haistack-sqlite is the SQLite-backed implementation of pkg/store contracts for device, tablet, workstation, and lightweight edge nodes. It owns schema, migrations, and the atomic local write path. This is not bytefhir-sqlite; it is the haistack runtime's embedded persistence adapter at github.com/degoke/haistack/pkg/sqlite.

Design principles

Single-transaction local writes:

  • A local write must update current resource state, immutable history, sync outbox, and typed search index rows in one SQLite transaction so persistence and sync state cannot drift.
  • ApplyLocalWrite and Session implement this guarantee for callers.
  • Version assignment and search extraction stay outside this package; SQLite persists caller-supplied version IDs and prepared SearchIndexEntry values.

Canonical JSON:

  • types.ResourceEnvelope.JSON is the source of truth for resource content.
  • Stores persist JSON blobs plus metadata columns (version_id, last_updated, hash).
  • Optional proto blob columns are deferred to a future migration.

Pure Go driver:

  • database/sql with modernc.org/sqlite for cross-platform embedded use without CGO.
  • Default pragmas: foreign_keys=ON, journal_mode=WAL, configurable busy_timeout.

Opening a database

db, err := sqlite.OpenAndMigrate(ctx, "/path/to/haistack.db")
if err != nil { … }
defer db.Close()

Or open and migrate separately:

db, err := sqlite.Open("/path/to/haistack.db")
if err != nil { … }
defer db.Close()
if err := db.Migrate(ctx); err != nil { … }

Reopening an existing file uses the same pattern: a fresh Open (or OpenAndMigrate) call, then reconstruct in-memory services and snapshots. Migrate is idempotent. Close leaves the database file on disk; remove the parent directory with os.RemoveAll when cleaning up temporary test databases.

Open accepts functional options such as WithBusyTimeout. Use path ":memory:" for ephemeral in-memory databases (common in tests).

Implemented contracts (MVP-complete)

These types satisfy pkg/store interfaces and are fully wired for local MVP use:

  • ResourceStore → store.ResourceStore — current-state CRUD
  • HistoryStore → store.HistoryStore — immutable version history and tombstones
  • SearchStore → store.SearchStore — typed search_token/string/date/number/reference tables
  • OutboxStore → store.EventStore — append-only sync_outbox with monotonic sequence
  • CursorStore → store.CursorStore — named sync_cursor checkpoints
  • Session → store.WriteSession — transaction-scoped stores for atomic writes
  • DB → store.WriteSessionProvider via BeginWrite

Scaffold contracts (schema + store; upstream workflow deferred)

These adapters persist data correctly but intentionally omit higher-level orchestration:

  • InboxStore → store.InboxStore — sync_inbox_applied idempotency for pull/apply.
  • ConflictStore → store.ConflictStore — sync_conflict append/list/resolve. Conflict detection and reconciliation policy live in pkg/core and sync layers.
  • BinaryStore → store.BinaryStore — small inline binary_object payloads. Large blob offload and deduplication are out of scope for embedded SQLite.
  • ModuleStore → store.ModuleStore — module_registry metadata. Code loading and activation policy live elsewhere.
  • JobStore → store.JobStore — background_job enqueue/claim/update. Scheduling and worker loops live in pkg/jobs.
  • AuditStore → store.AuditStore — append-only audit_log. Event shaping and emit helpers live in pkg/audit.

Out of scope (not in haistack-sqlite MVP)

Use pkg/postgres or future adapters for:

  • optional proto column on resource
  • encrypted SQLite (SQLCipher / platform keystore)
  • hot backup and restore
  • vacuum, compaction, and maintenance jobs
  • multiple database profiles per device
  • store.BlobStore with external blob references
  • store.IDRegistryStore
  • analytics store
  • materialized projection store

Atomic local write path

High-level helper:

result, err := db.ApplyLocalWrite(ctx, sqlite.LocalWrite{
    Resource:      envelope,
    Action:        store.VersionActionCreate,
    SearchEntries: []store.SearchIndexEntry{…},
    Event:         event,
    Version:       version,
})

Manual session (same transaction boundary):

session, err := db.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)

ApplyLocalWrite and Session cover create, update, and delete. Delete removes current resource state, appends a history tombstone, emits an outbox event, and clears search index rows for the resource. ApplyLocalWrite does not run validation or build search entries; callers supply prepared SearchIndexEntry values. Use BeginWrite/BeginSession directly when higher-level steps must roll back together with persistence.

Search index field keys

SearchStore routes fields to typed tables using key prefixes:

  • 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 (for example "family") default to hai_search_string. FHIR search parsing and token extraction remain in pkg/search; this package stores prepared entries.

Search limitations on SQLite:

  • SearchStore implements store.SearchQueryExecutor (LookupMatch, FieldValues) only.
  • It does not implement store.SearchAdvancedExecutor: no LookupReferences, LookupReferencing, or LookupFullText. Queries using _include, _revinclude, or full-text search return store.ErrUnsupportedFeature.
  • Index skips composite.* and text.* field keys; composite and full-text parameters cannot be queried through the SQLite adapter.

QueryPrepared supports the "by-field" plan (args: key, value) matching pkg/store test doubles.

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.

Main tables:

  • hai_resource — current canonical state keyed by (resource_type, id)
  • hai_resource_history — immutable version log with delete tombstones
  • hai_search_* — five typed index tables (no generic fallback)
  • hai_sync_outbox — append-only local change events (AUTOINCREMENT sequence)
  • hai_sync_inbox_applied — remote operation idempotency (scaffold)
  • hai_sync_cursor — named consumer checkpoints
  • hai_sync_conflict — conflict records (scaffold)
  • hai_binary_object — inline binary metadata and payload (scaffold)
  • hai_module_registry — local module registration metadata (scaffold)

Integration with other packages

pkg/store — interface contracts; sqlite implements the embedded-local subset. pkg/types — ResourceEnvelope is the only FHIR container crossing store boundaries. pkg/postgres — tenant-scoped edge/cloud adapter with broader contract surface. pkg/core — orchestrates write pipelines and version policy on top of store interfaces. pkg/search — produces SearchIndexEntry values; does not implement SearchStore.

File layout

  • doc.go — package documentation (this file)
  • db.go — DB, Open, Migrate, ApplyLocalWrite, store constructors
  • options.go — Open options (WithBusyTimeout)
  • migrate.go — embedded migration runner
  • session.go — Session, BeginSession, atomic write pipeline
  • resource_store.go — ResourceStore
  • history_store.go — HistoryStore
  • search_store.go — SearchStore
  • outbox_store.go — OutboxStore (EventStore)
  • inbox_store.go — InboxStore (scaffold)
  • cursor_store.go — CursorStore
  • conflict_store.go — ConflictStore (scaffold)
  • binary_store.go — BinaryStore (scaffold)
  • module_store.go — ModuleStore (scaffold)
  • job_store.go — JobStore
  • audit_store.go — AuditStore
  • timeutil.go — RFC3339Nano timestamp helpers
  • migrations/*.sql — embedded schema migrations

Testing

sqlite_test.go contains integration tests against temporary and :memory: databases: migration idempotency, per-store CRUD, ApplyLocalWrite atomicity and rollback, delete tombstones, concurrent smoke tests, and compose-style lifecycle tests mirroring pkg/store/store_test.go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuditStore

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

AuditStore persists append-only audit records in SQLite.

func (*AuditStore) Append

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

Append implements store.AuditStore.

func (*AuditStore) List

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

List implements store.AuditStore.

type AuthStore

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

AuthStore persists auth data for one logical tenant in SQLite.

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 small inline binary payloads in SQLite.

Inline keyed storage only; large blob offload and deduplication are out of scope here.

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 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 ChunkBlobStore

type ChunkBlobStore = SQLiteBlobStore

ChunkBlobStore is kept as a compatibility alias for earlier naming.

type ConflictStore

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

ConflictStore persists sync and write conflicts in SQLite.

Append, List, and Resolve are supported. Conflict detection and reconciliation policy live outside this package.

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

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 SQLite connection, migration runner, and store constructors.

func Open

func Open(path string, opts ...Option) (*DB, error)

Open opens a SQLite database at path with default pragmas and wiring.

func OpenAndMigrate

func OpenAndMigrate(ctx context.Context, path string, opts ...Option) (*DB, error)

OpenAndMigrate opens a SQLite database and runs embedded migrations.

func (*DB) ApplyLocalWrite

func (db *DB) ApplyLocalWrite(ctx context.Context, input LocalWrite) (*LocalWriteResult, error)

ApplyLocalWrite commits resource, history, outbox, and search changes atomically.

func (*DB) AuditStore

func (db *DB) AuditStore() *AuditStore

AuditStore returns a connection-scoped audit store.

func (*DB) AuthStore

func (db *DB) AuthStore(tenantID string) *AuthStore

AuthStore returns a tenant-scoped auth persistence adapter.

func (*DB) BeginSession

func (db *DB) BeginSession(ctx context.Context) (*Session, error)

BeginSession starts a new SQLite transaction session.

func (*DB) BeginWrite

func (db *DB) BeginWrite(ctx context.Context) (store.WriteSession, error)

BeginWrite starts a new atomic write session.

func (*DB) BinaryStore

func (db *DB) BinaryStore() *BinaryStore

BinaryStore returns a connection-scoped inline binary store.

func (*DB) BlobMetadataStore

func (db *DB) BlobMetadataStore() *BlobMetadataStore

BlobMetadataStore returns a connection-scoped blob metadata store.

func (*DB) ChunkBlobStore

func (db *DB) ChunkBlobStore() *ChunkBlobStore

ChunkBlobStore returns a connection-scoped chunked blob store.

func (*DB) Close

func (db *DB) Close() error

Close closes the underlying database connection.

func (*DB) ConflictStore

func (db *DB) ConflictStore() *ConflictStore

ConflictStore returns a connection-scoped conflict store.

func (*DB) CursorStore

func (db *DB) CursorStore() *CursorStore

CursorStore returns a connection-scoped cursor store.

func (*DB) DefinitionStore

func (db *DB) DefinitionStore() *DefinitionStore

DefinitionStore returns a connection-scoped FHIR definition catalog store.

func (*DB) GlobalTerminologyStore

func (db *DB) GlobalTerminologyStore() *TerminologyStore

GlobalTerminologyStore returns the platform-wide terminology catalog store.

func (*DB) HistoryStore

func (db *DB) HistoryStore() *HistoryStore

HistoryStore returns a connection-scoped history store.

func (*DB) InboxStore

func (db *DB) InboxStore() *InboxStore

InboxStore returns a connection-scoped inbox applied store.

func (*DB) JobStore

func (db *DB) JobStore() *JobStore

JobStore returns a connection-scoped background job store.

func (*DB) Migrate

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

Migrate runs embedded numbered SQL migrations.

func (*DB) ModuleStore

func (db *DB) ModuleStore() *ModuleStore

ModuleStore returns a connection-scoped module registry store.

func (*DB) OutboxStore

func (db *DB) OutboxStore() *OutboxStore

OutboxStore returns a connection-scoped outbox event store.

func (*DB) PackageInstallStore

func (db *DB) PackageInstallStore() *PackageInstallStore

PackageInstallStore returns a connection-scoped package install completion store.

func (*DB) RegistryInstallStore

func (db *DB) RegistryInstallStore() *RegistryInstallStore

RegistryInstallStore returns a connection-scoped registry install overlay store.

func (*DB) ResourceStore

func (db *DB) ResourceStore() *ResourceStore

ResourceStore returns a connection-scoped resource store.

func (*DB) SQL

func (db *DB) SQL() *sql.DB

SQL returns the underlying database handle for advanced use.

func (*DB) SQLiteBlobStore

func (db *DB) SQLiteBlobStore() *SQLiteBlobStore

SQLiteBlobStore returns a connection-scoped chunked blob store.

func (*DB) SearchStore

func (db *DB) SearchStore() *SearchStore

SearchStore returns a connection-scoped search store.

func (*DB) SubscriptionDeliveryStore

func (db *DB) SubscriptionDeliveryStore() *SubscriptionDeliveryStore

SubscriptionDeliveryStore returns a connection-scoped delivery log store.

func (*DB) SubscriptionStore

func (db *DB) SubscriptionStore() *SubscriptionStore

SubscriptionStore returns a connection-scoped subscription registry store.

func (*DB) TerminologyInstallStore

func (db *DB) TerminologyInstallStore(tenantID string) *TerminologyInstallStore

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

func (*DB) TerminologyStore

func (db *DB) TerminologyStore() *TerminologyStore

type DefinitionStore

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

DefinitionStore persists FHIR definition resources in SQLite.

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 HistoryStore

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

HistoryStore persists immutable resource version history in SQLite.

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 InboxStore

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

InboxStore tracks applied remote sync operations for idempotency.

MarkApplied, IsApplied, and AppliedAt implement store.InboxStore.

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) 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 locally.

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

func (*JobStore) ClaimNext

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

ClaimNext implements store.JobStore with Postgres-compatible claim semantics.

func (*JobStore) Delete

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

Delete implements store.JobDeleter.

func (*JobStore) Enqueue

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

Enqueue implements store.JobStore.

func (*JobStore) Get

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

Get implements store.JobStore.

func (*JobStore) Update

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

Update implements store.JobStore.

func (*JobStore) UpdateIf

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

UpdateIf implements store.JobCASStore.

type LocalWrite

type LocalWrite struct {
	Resource      *types.ResourceEnvelope
	Action        store.VersionAction
	SearchEntries []store.SearchIndexEntry
	Event         store.ResourceEvent
	Version       store.ResourceVersion
}

LocalWrite bundles the inputs for one atomic local write pipeline.

type LocalWriteResult

type LocalWriteResult struct {
	Version store.ResourceVersion
	Event   store.ResourceEvent
}

LocalWriteResult returns persisted write outputs.

type ModuleStore

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

ModuleStore persists local module registration metadata in SQLite.

Name, version, and metadata only; module code loading and activation policy live elsewhere.

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 Option

type Option func(*options)

Option configures an opened SQLite database.

func WithBusyTimeout

func WithBusyTimeout(d time.Duration) Option

WithBusyTimeout sets the SQLite busy timeout for lock contention.

type OutboxStore

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

OutboxStore persists append-only sync outbox events in SQLite.

func (*OutboxStore) Append

func (*OutboxStore) LatestForResource

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

func (*OutboxStore) ReadSince

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

type PackageInstallStore

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

PackageInstallStore tracks completed FHIR package version installs in SQLite.

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 RegistryInstallStore

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

RegistryInstallStore persists local registry enablement and install references in SQLite.

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 ResourceStore

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

ResourceStore persists current resource state in SQLite.

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 SQLiteBlobStore

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

SQLiteBlobStore persists full blob bytes in SQLite via chunk and manifest tables.

func (*SQLiteBlobStore) AppendChunk

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

AppendChunk stores one chunk for a blob or staging key.

func (*SQLiteBlobStore) Delete

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

Delete removes blob chunks and manifest.

func (*SQLiteBlobStore) DeleteChunks

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

DeleteChunks removes all chunks for a key.

func (*SQLiteBlobStore) Get

func (s *SQLiteBlobStore) Get(ctx context.Context, blobID string) ([]byte, *binary.BlobDescriptor, error)

Get reads a finalized blob by assembling stored chunks.

func (*SQLiteBlobStore) Head

func (s *SQLiteBlobStore) Head(ctx context.Context, blobID string) (*binary.BlobDescriptor, error)

Head returns blob metadata without reading payload bytes.

func (*SQLiteBlobStore) ListChunkCount

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

ListChunkCount returns contiguous chunk count starting at index 0.

func (*SQLiteBlobStore) Metadata

func (s *SQLiteBlobStore) Metadata() *BlobMetadataStore

Metadata returns the metadata store sharing this connection.

func (*SQLiteBlobStore) Open

Open streams a finalized blob one chunk at a time.

func (*SQLiteBlobStore) Put

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

Put stores a finalized blob as chunked bytes in SQLite.

func (*SQLiteBlobStore) PutStream

func (s *SQLiteBlobStore) 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 (*SQLiteBlobStore) ReadChunk

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

ReadChunk reads one stored chunk.

type SearchStore

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

SearchStore persists typed search index rows in SQLite.

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) Lookup

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

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) 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 local writes.

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) 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) InboxStore

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

InboxStore returns the transaction-scoped sync inbox store.

func (*Session) OutboxStore

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

OutboxStore returns the transaction-scoped outbox event 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 SQLite.

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

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 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 SQLite 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

Jump to

Keyboard shortcuts

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