Documentation
¶
Overview ¶
Package view implements haistack-view, a standalone Go library for executing FHIR ViewDefinition resources into structured JSON rows.
Scope ¶
The package executes SQL-on-FHIR ViewDefinition projections in-process:
- Single root resource type per view.
- Scan-based execution via store.ResourceStore.ListIDs and Read.
- Flat and nested selects with forEach, forEachOrNull, unionAll, and reference joins resolved through the resource store.
- JSON row output with row-level pagination for expanded results.
- Optional pluggable authorization, audit hooks, and materialized view persistence.
ViewDefinition support ¶
The canonical input is a FHIR ViewDefinition resource serialized as JSON. Supported constructs include:
- One source resource type per view (the top-level "resource" field).
- Root and nested select trees with column, select, forEach, forEachOrNull, and unionAll blocks.
- Optional root filters expressed as FHIRPath predicates in "where" clauses.
- Materialization metadata: metadata.materialize and metadata.materializeKey.
- Declared permissions as a top-level "permissions" array; auth.ViewAuthorizer is the stack adapter.
Public API ¶
The package centers on three public types:
- ParseDefinition / DefinitionParser: load a ViewDefinition JSON payload and produce a normalized ViewSpec. A FHIRPath engine is required so that filter and column expressions are validated at parse time.
- Registry: in-memory store for named/versioned ViewSpec values. Registering a view compiles its expressions immediately.
- Executor: runs a registered view against a store.ResourceStore and returns structured rows.
Typical usage:
engine, err := fhirpath.NewEngine(fhirpath.Config{})
if err != nil { /* handle */ }
reg := view.NewRegistry()
if _, err := reg.Register(view.PatientSummaryView(), engine); err != nil {
// handle
}
exec, err := view.NewExecutor(view.Config{
Resources: resources,
Engine: engine,
Registry: reg,
})
if err != nil { // handle
}
res, err := exec.Execute(ctx, view.ExecuteRequest{ViewName: "patient_summary_view"})
Execution model ¶
Execute resolves the view, applies the optional authorizer, scans the source resource type, evaluates filter FHIRPath for each resource, expands the select tree into zero or more rows per resource, and returns rows.
Result.Total is the number of output rows across the entire scan, not just the returned page. NextOffset is set when additional rows are available.
Authorization and audit ¶
If the Executor is configured with an Authorizer and the view declares permissions, AuthorizeView is called before any resources are read. If the Executor is configured with an AuditLogger, LogViewAccess is called on success, denial, and view resolution errors. Both seams are optional; the package is fully usable without them.
Integration points ¶
- haistack-modules: views are declared by name in module metadata today; installers register packaged ViewDefinition resources into a view registry.
- haistack-ai: consumes Result.Rows directly as structured context.
- haistack-auth: auth.ViewAuthorizer implements Authorizer.
- haistack-analytics: reuses the same Executor for reporting-table refresh.
- store.MaterializedViewStore: optional persistence when metadata.materialize is set and Executor.Config.MaterializedViews is wired.
Index ¶
- Constants
- Variables
- func AppointmentView() []byte
- func IsOperationOutputFormat(raw string) bool
- func IsParquetFile(data []byte) bool
- func LatestTimestamp(a, b time.Time) time.Time
- func ObservationView() []byte
- func ParquetFileRowCount(data []byte) (int64, error)
- func ParseLimitOffset(limitRaw, offsetRaw string) (int, int, error)
- func PatientSummaryView() []byte
- func WatermarkAdvanceTime(maxUpdated, fallback time.Time) time.Time
- func WriteParquetOutput(ctx context.Context, w io.Writer, result *Result, execReq ExecuteRequest, ...) (int, error)
- func WriteParquetResult(w io.Writer, result *Result) error
- type AuditLogger
- type AuditLoggerFunc
- type AuditRecord
- type AuditStoreAdapter
- type AuthRequest
- type Authorizer
- type AuthorizerFunc
- type ColumnInfo
- type ColumnSpec
- type Config
- type DefinitionParser
- type ExecuteRequest
- type Executor
- func (e *Executor) CollectMatchingResources(ctx context.Context, req ExecuteRequest) ([]map[string]any, string, error)deprecated
- func (e *Executor) Execute(ctx context.Context, req ExecuteRequest) (*Result, error)
- func (e *Executor) ExecuteInline(ctx context.Context, req ExecuteRequest, def []byte) (*Result, error)
- func (e *Executor) ResolveView(name, version string) (*ViewSpec, error)
- type ExportFile
- type ExportFileStore
- type ExportFileStoreWithStream
- type ExportService
- func (s *ExportService) Cancel(ctx context.Context, jobID string) error
- func (s *ExportService) FileURL(jobID, filename string) string
- func (s *ExportService) GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)
- func (s *ExportService) GetJob(ctx context.Context, jobID string) (*ViewExportJob, error)
- func (s *ExportService) JobHandler() jobs.Handler
- func (s *ExportService) Kickoff(ctx context.Context, req ViewExportRequest) (*ViewExportJob, error)
- func (s *ExportService) OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
- func (s *ExportService) RunJob(ctx context.Context, jobID string) error
- func (s *ExportService) StatusURL(jobID string) string
- type ExportServiceConfig
- type ExportStatus
- type ExportWriter
- type FileExportWriter
- type FilterSpec
- type LocalExportFileStore
- func (s *LocalExportFileStore) DeleteJob(_ context.Context, jobID string) error
- func (s *LocalExportFileStore) Get(ctx context.Context, jobID, filename string) ([]byte, string, error)
- func (s *LocalExportFileStore) Open(_ context.Context, jobID, filename string) (io.ReadCloser, string, error)
- func (s *LocalExportFileStore) Put(ctx context.Context, jobID, filename string, data []byte, contentType string) error
- func (s *LocalExportFileStore) PutStream(_ context.Context, jobID, filename string, r io.Reader, size int64, ...) error
- type LocalMaterializeJobStore
- type LocalViewExportJobStore
- type MatchingResourceStats
- type MaterializeJob
- type MaterializeJobPayload
- type MaterializeJobStore
- type MaterializeRequest
- type MaterializeResult
- type MaterializeService
- func (s *MaterializeService) Cancel(ctx context.Context, jobID string) error
- func (s *MaterializeService) GetJob(ctx context.Context, jobID string) (*MaterializeJob, error)
- func (s *MaterializeService) JobHandler() jobs.Handler
- func (s *MaterializeService) Kickoff(ctx context.Context, req MaterializeRequest) (*MaterializeJob, error)
- func (s *MaterializeService) Result(job *MaterializeJob) *MaterializeResult
- func (s *MaterializeService) RunJob(ctx context.Context, jobID string) error
- func (s *MaterializeService) StatusURL(jobID string) string
- type MaterializeServiceConfig
- type MaterializeStatus
- type MemoryExportWriter
- type OutputFormat
- type ParquetExportResult
- type ParquetLayout
- type ParquetRowWriter
- type Registry
- func (r *Registry) Get(name, version string) (*ViewSpec, error)
- func (r *Registry) List() []*ViewSpec
- func (r *Registry) Register(def []byte, engine fhirpath.Engine) (*ViewSpec, error)
- func (r *Registry) Resolve(name, version string) (*ViewSpec, error)
- func (r *Registry) Unregister(name, version string) error
- type ReportingTableRef
- type Result
- type ResultMetadata
- type RowEncoder
- type RunService
- type SQLQueryEngine
- type SQLQueryRequest
- type SQLQueryResult
- type SQLQueryService
- type SearchMode
- type SelectSpec
- type TimestampEncoding
- type ViewExportJob
- type ViewExportJobPayload
- type ViewExportJobStore
- type ViewExportRequest
- type ViewExportTarget
- type ViewRunRequest
- type ViewSpec
- type WatermarkAdvancer
Constants ¶
const ( // TimestampEncodingInt64 writes TIMESTAMP(MILLIS) on INT64 (default). TimestampEncodingInt64 = parquetfhir.TimestampEncodingInt64 // TimestampEncodingInt96 writes spec INT96 + TIMESTAMP(MILLIS). TimestampEncodingInt96 = parquetfhir.TimestampEncodingInt96 )
const DefaultParquetPageSize = 1000
DefaultParquetPageSize is the default executor page size for streaming parquet export.
const DefaultParquetRowGroupSize = 1000
DefaultParquetRowGroupSize controls how many rows are buffered per parquet row group.
const ParquetContentType = "application/vnd.apache.parquet"
ParquetContentType is the SQL-on-FHIR native media type for parquet output.
const TypeViewMaterialize = jobs.TypeViewMaterialize
TypeViewMaterialize is the job type for ViewDefinition materialization.
Variables ¶
var ( // ErrInvalidViewDefinition is returned when a ViewDefinition JSON payload is // malformed or fails structural validation. ErrInvalidViewDefinition = errors.New("view: invalid ViewDefinition") // ErrUnsupportedFeature is returned when a ViewDefinition uses a feature // outside the executable subset (for example multiple source resource types). ErrUnsupportedFeature = errors.New("view: unsupported ViewDefinition feature") // ErrViewNotFound is returned when a named/versioned view is not registered. ErrViewNotFound = errors.New("view: view not found") // ErrViewAlreadyRegistered is returned when registering a view whose name and // version already exist in the registry. ErrViewAlreadyRegistered = errors.New("view: view already registered") // execution request. ErrUnauthorized = errors.New("view: unauthorized") // ErrRowEncoding is returned when a column result cannot be normalized into a // JSON-safe value. ErrRowEncoding = errors.New("view: row encoding failed") // ErrMissingEngine is returned when an Executor is configured without a // FHIRPath engine. ErrMissingEngine = errors.New("view: missing FHIRPath engine") // ErrMissingResourceStore is returned when an Executor is configured without // a resource store. ErrMissingResourceStore = errors.New("view: missing resource store") // ErrMissingMaterializedViewStore is returned when materialization is requested // without a configured MaterializedViewStore. ErrMissingMaterializedViewStore = errors.New("view: missing materialized view store") // ErrMissingReportingTables is returned when SQL query execution is requested // without a configured ReportingTableStore. ErrMissingReportingTables = errors.New("view: missing reporting table store") )
Functions ¶
func AppointmentView ¶
func AppointmentView() []byte
AppointmentView returns an example FHIR ViewDefinition for booked appointments with a status/date filter.
func IsOperationOutputFormat ¶
IsOperationOutputFormat reports whether raw selects a SQL-on-FHIR operation artifact encoding (csv, ndjson, parquet) rather than a FHIR response envelope.
ParseOutputFormat("json") returns FormatJSON because json is a valid FHIR envelope for Parameters/Binary responses, but IsOperationOutputFormat("json") is false so Accept-header negotiation still applies to json/xml envelopes.
func IsParquetFile ¶
IsParquetFile reports whether data begins with the parquet magic bytes.
func LatestTimestamp ¶
LatestTimestamp returns the later of two timestamps.
func ObservationView ¶
func ObservationView() []byte
ObservationView returns an example FHIR ViewDefinition for final observations with scalar quantity extraction.
func ParquetFileRowCount ¶
ParquetFileRowCount returns the number of rows in a parquet file payload.
func ParseLimitOffset ¶
ParseLimitOffset parses _limit and _offset query parameters.
func PatientSummaryView ¶
func PatientSummaryView() []byte
PatientSummaryView returns an example FHIR ViewDefinition for a flat patient summary. All selected columns resolve to JSON scalars in v1.
func WatermarkAdvanceTime ¶
WatermarkAdvanceTime returns the timestamp to persist for incremental export or refresh. When exported resources carry LastUpdated, that data clock is preferred over the process clock to avoid skew-related gaps or duplicates.
func WriteParquetOutput ¶
func WriteParquetOutput(ctx context.Context, w io.Writer, result *Result, execReq ExecuteRequest, layout ParquetLayout, exec *Executor) (int, error)
WriteParquetOutput writes flat view rows or Parquet-on-FHIR resources to w.
Types ¶
type AuditLogger ¶
type AuditLogger interface {
LogViewAccess(ctx context.Context, rec AuditRecord) error
}
AuditLogger is the pluggable audit seam. It is invoked on both successful and denied executions. The package remains usable without an audit logger.
type AuditLoggerFunc ¶
type AuditLoggerFunc func(ctx context.Context, rec AuditRecord) error
AuditLoggerFunc adapts a function to the AuditLogger interface.
func (AuditLoggerFunc) LogViewAccess ¶
func (f AuditLoggerFunc) LogViewAccess(ctx context.Context, rec AuditRecord) error
LogViewAccess implements AuditLogger.
type AuditRecord ¶
type AuditRecord struct {
ViewName string `json:"viewName"`
Version string `json:"version,omitempty"`
Actor string `json:"actor"`
Subject string `json:"subject,omitempty"`
Outcome string `json:"outcome"`
Details map[string]string `json:"details,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
AuditRecord captures one view access event for the audit seam. It is intentionally smaller than store.AuditRecord and scoped to view execution.
type AuditStoreAdapter ¶
type AuditStoreAdapter struct {
Store store.AuditStore
Now func() time.Time
NewID func() string
}
AuditStoreAdapter writes view audit records through pkg/audit into a store.AuditStore. Action naming is owned by pkg/audit (execute-view). Set NewID for deterministic event IDs (research provenance bundles); the default is a UUID.
func (*AuditStoreAdapter) LogViewAccess ¶
func (a *AuditStoreAdapter) LogViewAccess(ctx context.Context, rec AuditRecord) error
LogViewAccess converts a view.AuditRecord to a canonical audit event and appends it.
type AuthRequest ¶
type AuthRequest struct {
ViewName string `json:"viewName"`
Version string `json:"version,omitempty"`
ResourceType string `json:"resourceType"`
Actor string `json:"actor"`
Subject string `json:"subject,omitempty"`
Permissions []string `json:"permissions,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
}
AuthRequest carries the authorization context for one view execution.
type Authorizer ¶
type Authorizer interface {
AuthorizeView(ctx context.Context, req AuthRequest) error
}
Authorizer is the pluggable authorization seam. If an Executor is configured without an Authorizer, executions proceed without permission checks. If an Authorizer is configured and the view declares permissions, the Authorizer is invoked before any resources are read.
type AuthorizerFunc ¶
type AuthorizerFunc func(ctx context.Context, req AuthRequest) error
AuthorizerFunc adapts a function to the Authorizer interface.
func (AuthorizerFunc) AuthorizeView ¶
func (f AuthorizerFunc) AuthorizeView(ctx context.Context, req AuthRequest) error
AuthorizeView implements Authorizer.
type ColumnInfo ¶
ColumnInfo describes one output column for result metadata.
type ColumnSpec ¶
type ColumnSpec struct {
Name string
Path string
Type string
Description string
Collection bool
// contains filtered or unexported fields
}
ColumnSpec describes one output column.
type Config ¶
type Config struct {
Resources store.ResourceStore
Engine fhirpath.Engine
Authorizer Authorizer
Audit AuditLogger
Registry *Registry
MaterializedViews store.MaterializedViewStore
Search search.Executor
SearchRegistry search.Registry
SearchPlanner search.Planner
BaseURL string
ResolveLogicalID func(ctx context.Context, logicalID string) (resourceType, id string, ok bool)
ProfileCatalog validate.ProfileCatalog
Now func() time.Time
}
Config configures an Executor. The resource store and FHIRPath engine are required; authorizer, audit logger, and registry are optional but required for their respective features. If Now is nil, time.Now is used.
type DefinitionParser ¶
type DefinitionParser struct {
// contains filtered or unexported fields
}
DefinitionParser loads and validates a FHIR ViewDefinition resource from JSON bytes. A FHIRPath engine is required so that all filter and column expressions are validated at parse time. Use NewDefinitionParser to create one.
func NewDefinitionParser ¶
func NewDefinitionParser(engine fhirpath.Engine) (*DefinitionParser, error)
NewDefinitionParser returns a parser that validates FHIRPath expressions with the supplied engine when parsing. Engine must be non-nil.
type ExecuteRequest ¶
type ExecuteRequest struct {
ViewName string
Version string
Actor string
Subject string
Limit int
Offset int
Parameters map[string]any
Since time.Time
Materialize bool
TimestampEncoding TimestampEncoding
}
ExecuteRequest carries runtime parameters for one view execution.
func ExecRequestForExport ¶
func ExecRequestForExport(result *Result, actor string) ExecuteRequest
ExecRequestForExport returns the execute request used for Parquet-on-FHIR export.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor runs a parsed ViewDefinition against a store.ResourceStore.
func NewExecutor ¶
NewExecutor validates the configuration and returns an Executor.
func (*Executor) CollectMatchingResources
deprecated
func (e *Executor) CollectMatchingResources(ctx context.Context, req ExecuteRequest) ([]map[string]any, string, error)
CollectMatchingResources returns full FHIR resources matching a view's filters.
Deprecated: prefer WriteParquetFHIRExport for large exports. This helper materializes every matching resource in memory and is not suitable for lakehouse-scale datasets.
func (*Executor) Execute ¶
Execute resolves the registered view, applies optional authorization, scans the source resource type, filters resources, extracts columns, and returns rows. Audit records are written for both success and denial when an Audit logger is configured.
func (*Executor) ExecuteInline ¶
func (e *Executor) ExecuteInline(ctx context.Context, req ExecuteRequest, def []byte) (*Result, error)
ExecuteInline runs an inline ViewDefinition payload with the same authorization, audit, and scan behavior as Execute.
type ExportFile ¶
type ExportFile struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
OutputName string `json:"outputName"`
Filename string `json:"filename"`
RowCount int `json:"rowCount"`
Format string `json:"format"`
ParquetLayout ParquetLayout `json:"parquetLayout,omitempty"`
TimestampEncoding TimestampEncoding `json:"timestampEncoding,omitempty"`
}
ExportFile describes one exported artifact.
type ExportFileStore ¶
type ExportFileStore interface {
Put(ctx context.Context, jobID, filename string, data []byte, contentType string) error
Get(ctx context.Context, jobID, filename string) ([]byte, string, error)
DeleteJob(ctx context.Context, jobID string) error
}
ExportFileStore persists view export artifacts keyed by job id and filename.
type ExportFileStoreWithStream ¶
type ExportFileStoreWithStream interface {
ExportFileStore
PutStream(ctx context.Context, jobID, filename string, r io.Reader, size int64, contentType string) error
Open(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
}
ExportFileStoreWithStream optionally writes artifacts from an io.Reader and opens them without requiring the caller to materialize the full payload as []byte.
func NewInMemoryExportFileStore ¶
func NewInMemoryExportFileStore() ExportFileStoreWithStream
NewInMemoryExportFileStore returns an in-memory ExportFileStoreWithStream.
type ExportService ¶
type ExportService struct {
// contains filtered or unexported fields
}
ExportService orchestrates ViewDefinition/$viewdefinition-export operations.
func NewExportService ¶
func NewExportService(cfg ExportServiceConfig) (*ExportService, error)
NewExportService validates configuration and returns an ExportService.
func (*ExportService) Cancel ¶
func (s *ExportService) Cancel(ctx context.Context, jobID string) error
Cancel requests cancellation of an in-progress export job.
func (*ExportService) FileURL ¶
func (s *ExportService) FileURL(jobID, filename string) string
FileURL returns the download URL for one exported artifact.
func (*ExportService) GetFile ¶
func (s *ExportService) GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)
GetFile returns one exported artifact.
func (*ExportService) GetJob ¶
func (s *ExportService) GetJob(ctx context.Context, jobID string) (*ViewExportJob, error)
GetJob returns the current export job state.
func (*ExportService) JobHandler ¶
func (s *ExportService) JobHandler() jobs.Handler
JobHandler returns a jobs.Handler for async execution.
func (*ExportService) Kickoff ¶
func (s *ExportService) Kickoff(ctx context.Context, req ViewExportRequest) (*ViewExportJob, error)
Kickoff creates an async export job.
func (*ExportService) OpenFile ¶
func (s *ExportService) OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
OpenFile streams one exported artifact without assembling a full []byte.
func (*ExportService) RunJob ¶
func (s *ExportService) RunJob(ctx context.Context, jobID string) error
RunJob executes one export job synchronously.
func (*ExportService) StatusURL ¶
func (s *ExportService) StatusURL(jobID string) string
StatusURL returns the polling URL for a job.
type ExportServiceConfig ¶
type ExportServiceConfig struct {
Jobs ViewExportJobStore
Files ExportFileStore
Executor *Executor
Watermark WatermarkAdvancer
JobQueue store.JobStore
BasePath string
Now func() time.Time
NewID func() string
}
ExportServiceConfig configures ExportService.
type ExportStatus ¶
type ExportStatus string
ExportStatus tracks view export job lifecycle.
const ( ExportInProgress ExportStatus = "in-progress" ExportComplete ExportStatus = "complete" ExportError ExportStatus = "error" ExportCancelled ExportStatus = "cancelled" )
type ExportWriter ¶
type ExportWriter interface {
WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error
}
ExportWriter receives one exported view artifact.
func NewFileExportWriter ¶
func NewFileExportWriter(store ExportFileStore, jobID string) ExportWriter
NewFileExportWriter returns a writer that persists artifacts for one export job.
type FileExportWriter ¶
type FileExportWriter struct {
// contains filtered or unexported fields
}
FileExportWriter stores export artifacts in an ExportFileStore scoped to one job.
func (*FileExportWriter) WriteExport ¶
func (w *FileExportWriter) WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error
type FilterSpec ¶
FilterSpec describes one root filter predicate.
type LocalExportFileStore ¶
type LocalExportFileStore struct {
// contains filtered or unexported fields
}
LocalExportFileStore persists view export artifacts on the local filesystem.
func NewLocalExportFileStore ¶
func NewLocalExportFileStore(root string) (*LocalExportFileStore, error)
NewLocalExportFileStore creates a filesystem-backed ExportFileStore.
func (*LocalExportFileStore) DeleteJob ¶
func (s *LocalExportFileStore) DeleteJob(_ context.Context, jobID string) error
func (*LocalExportFileStore) Open ¶
func (s *LocalExportFileStore) Open(_ context.Context, jobID, filename string) (io.ReadCloser, string, error)
type LocalMaterializeJobStore ¶
type LocalMaterializeJobStore struct {
// contains filtered or unexported fields
}
LocalMaterializeJobStore persists MaterializeJob records as JSON files.
func NewLocalMaterializeJobStore ¶
func NewLocalMaterializeJobStore(dir string) (*LocalMaterializeJobStore, error)
NewLocalMaterializeJobStore creates a filesystem-backed MaterializeJobStore.
func (*LocalMaterializeJobStore) Create ¶
func (s *LocalMaterializeJobStore) Create(_ context.Context, job MaterializeJob) error
func (*LocalMaterializeJobStore) Get ¶
func (s *LocalMaterializeJobStore) Get(_ context.Context, id string) (*MaterializeJob, error)
func (*LocalMaterializeJobStore) Update ¶
func (s *LocalMaterializeJobStore) Update(_ context.Context, job MaterializeJob) error
type LocalViewExportJobStore ¶
type LocalViewExportJobStore struct {
// contains filtered or unexported fields
}
LocalViewExportJobStore persists ViewExportJob records as JSON files.
func NewLocalViewExportJobStore ¶
func NewLocalViewExportJobStore(dir string) (*LocalViewExportJobStore, error)
NewLocalViewExportJobStore creates a filesystem-backed ViewExportJobStore.
func (*LocalViewExportJobStore) Create ¶
func (s *LocalViewExportJobStore) Create(_ context.Context, job ViewExportJob) error
func (*LocalViewExportJobStore) Get ¶
func (s *LocalViewExportJobStore) Get(_ context.Context, id string) (*ViewExportJob, error)
func (*LocalViewExportJobStore) Update ¶
func (s *LocalViewExportJobStore) Update(_ context.Context, job ViewExportJob) error
type MatchingResourceStats ¶
type MatchingResourceStats struct {
Scanned int
Filtered int
Written int
SourceResourceType string
MaxLastUpdated time.Time
}
MatchingResourceStats summarizes FHIR resource matching for Parquet-on-FHIR export.
func WriteParquetFHIRExport ¶
func WriteParquetFHIRExport(ctx context.Context, w io.Writer, exec *Executor, req ExecuteRequest) (int, MatchingResourceStats, error)
WriteParquetFHIRExport writes Parquet-on-FHIR nested resources for one view.
type MaterializeJob ¶
type MaterializeJob struct {
ID string `json:"id"`
Status MaterializeStatus `json:"status"`
Request MaterializeRequest `json:"request"`
RowCount int `json:"rowCount,omitempty"`
Progress string `json:"progress,omitempty"`
LastError string `json:"lastError,omitempty"`
CreatedAt time.Time `json:"createdAt"`
CompletedAt time.Time `json:"completedAt,omitempty"`
Cancelled bool `json:"cancelled,omitempty"`
}
MaterializeJob is a durable materialize job record.
type MaterializeJobPayload ¶
type MaterializeJobPayload struct {
JobID string `json:"jobId"`
}
MaterializeJobPayload is the background job payload for materialize execution.
type MaterializeJobStore ¶
type MaterializeJobStore interface {
Create(ctx context.Context, job MaterializeJob) error
Get(ctx context.Context, id string) (*MaterializeJob, error)
Update(ctx context.Context, job MaterializeJob) error
}
MaterializeJobStore persists materialize jobs.
func NewInMemoryMaterializeJobStore ¶
func NewInMemoryMaterializeJobStore() MaterializeJobStore
NewInMemoryMaterializeJobStore returns an ephemeral job store for tests and edge mode.
type MaterializeRequest ¶
type MaterializeRequest struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
TargetName string `json:"targetName,omitempty"`
Since time.Time `json:"since,omitempty"`
Actor string `json:"actor,omitempty"`
}
MaterializeRequest captures parameters for one materialize operation.
type MaterializeResult ¶
type MaterializeResult struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
TargetName string `json:"targetName"`
RowCount int `json:"rowCount"`
Metadata ResultMetadata `json:"metadata"`
UpdatedAt time.Time `json:"updatedAt"`
}
MaterializeResult is returned when a materialize job completes.
type MaterializeService ¶
type MaterializeService struct {
// contains filtered or unexported fields
}
MaterializeService orchestrates ViewDefinition $materialize operations.
func NewMaterializeService ¶
func NewMaterializeService(cfg MaterializeServiceConfig) (*MaterializeService, error)
NewMaterializeService validates configuration and returns a MaterializeService.
func (*MaterializeService) Cancel ¶
func (s *MaterializeService) Cancel(ctx context.Context, jobID string) error
Cancel requests cancellation of an in-progress job.
func (*MaterializeService) GetJob ¶
func (s *MaterializeService) GetJob(ctx context.Context, jobID string) (*MaterializeJob, error)
GetJob returns the current job state.
func (*MaterializeService) JobHandler ¶
func (s *MaterializeService) JobHandler() jobs.Handler
JobHandler returns a jobs.Handler for async execution.
func (*MaterializeService) Kickoff ¶
func (s *MaterializeService) Kickoff(ctx context.Context, req MaterializeRequest) (*MaterializeJob, error)
Kickoff creates an async materialize job.
func (*MaterializeService) Result ¶
func (s *MaterializeService) Result(job *MaterializeJob) *MaterializeResult
Result builds the completed operation result payload.
func (*MaterializeService) RunJob ¶
func (s *MaterializeService) RunJob(ctx context.Context, jobID string) error
RunJob executes one materialize job synchronously.
func (*MaterializeService) StatusURL ¶
func (s *MaterializeService) StatusURL(jobID string) string
StatusURL returns the polling URL for a job.
type MaterializeServiceConfig ¶
type MaterializeServiceConfig struct {
Jobs MaterializeJobStore
Executor *Executor
JobQueue store.JobStore
BasePath string
Now func() time.Time
NewID func() string
}
MaterializeServiceConfig configures MaterializeService.
type MaterializeStatus ¶
type MaterializeStatus string
MaterializeStatus tracks materialize job lifecycle.
const ( MaterializeInProgress MaterializeStatus = "in-progress" MaterializeComplete MaterializeStatus = "complete" MaterializeError MaterializeStatus = "error" MaterializeCancelled MaterializeStatus = "cancelled" )
type MemoryExportWriter ¶
type MemoryExportWriter struct {
// contains filtered or unexported fields
}
MemoryExportWriter stores exported artifacts in memory for tests and edge mode.
func NewMemoryExportWriter ¶
func NewMemoryExportWriter() *MemoryExportWriter
NewMemoryExportWriter returns an in-memory ExportWriter.
func (*MemoryExportWriter) Get ¶
func (w *MemoryExportWriter) Get(filename string) ([]byte, bool)
Get returns one exported artifact by filename.
func (*MemoryExportWriter) WriteExport ¶
func (w *MemoryExportWriter) WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error
WriteExport encodes one view result using the requested export format.
type OutputFormat ¶
type OutputFormat string
OutputFormat selects SQL-on-FHIR operation output encoding.
const ( FormatJSON OutputFormat = "json" FormatNDJSON OutputFormat = "ndjson" FormatCSV OutputFormat = "csv" FormatParquet OutputFormat = "parquet" )
func ParseOutputFormat ¶
func ParseOutputFormat(raw string) OutputFormat
ParseOutputFormat maps SQL-on-FHIR _format values to OutputFormat.
type ParquetExportResult ¶
ParquetExportResult summarizes a streamed flat view parquet export.
func WriteParquetExport ¶
func WriteParquetExport(ctx context.Context, w io.Writer, exec *Executor, req ExecuteRequest, pageSize int) (ParquetExportResult, error)
WriteParquetExport streams a view export through paginated executor calls.
type ParquetLayout ¶
type ParquetLayout string
ParquetLayout selects how Parquet output is encoded.
const ( // ParquetLayoutFlat exports ViewDefinition flat columns (default). ParquetLayoutFlat ParquetLayout = "flat" // ParquetLayoutFHIR exports full nested FHIR resources using Parquet-on-FHIR. ParquetLayoutFHIR ParquetLayout = "fhir" )
func ParseParquetLayout ¶
func ParseParquetLayout(raw string) ParquetLayout
ParseParquetLayout maps _parquetLayout query values.
type ParquetRowWriter ¶
type ParquetRowWriter struct {
// contains filtered or unexported fields
}
ParquetRowWriter streams view rows into an Apache Parquet file.
func NewParquetRowWriter ¶
func NewParquetRowWriter(w io.Writer, result *Result) (*ParquetRowWriter, error)
NewParquetRowWriter opens a parquet writer using the schema from result metadata.
func (*ParquetRowWriter) Close ¶
func (pw *ParquetRowWriter) Close() error
Close flushes the parquet footer.
func (*ParquetRowWriter) RowCount ¶
func (pw *ParquetRowWriter) RowCount() int
RowCount returns the number of rows written so far.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry stores named/versioned views in memory for runtime lookup. It is safe for concurrent use. Registering a view compiles its FHIRPath expressions immediately with the supplied engine so that invalid expressions are caught at registration time.
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry returns an empty in-memory view registry.
func (*Registry) Get ¶
Get returns a registered view by name and version. Returns ErrViewNotFound when no matching view exists.
func (*Registry) List ¶
List returns all registered views. The returned slice is a copy; the underlying ViewSpec values are shared.
func (*Registry) Register ¶
Register parses, validates, and stores a ViewDefinition. The name and version are taken from the ViewDefinition itself. All FHIRPath expressions are compiled with engine to fail fast on invalid expressions. If a view with the same name and version is already registered, ErrViewAlreadyRegistered is returned.
func (*Registry) Resolve ¶
Resolve returns a registered view by name and version. If version is empty, the only registered version with that name is returned. If multiple versions are registered for the name and version is empty, ErrViewNotFound is returned.
func (*Registry) Unregister ¶
Unregister removes a view from the registry. Returns ErrViewNotFound if the view was not registered.
type ReportingTableRef ¶
ReportingTableRef identifies one reporting table to load into the SQL engine.
type Result ¶
type Result struct {
ViewName string
Version string
Columns []ColumnInfo
Rows []map[string]any
Total int
Metadata ResultMetadata
NextOffset *int
ExecRequest *ExecuteRequest
}
Result is the structured output of a view execution.
type ResultMetadata ¶
type ResultMetadata struct {
ExecutedAt time.Time `json:"executedAt"`
Duration time.Duration `json:"duration"`
SourceResourceType string `json:"sourceResourceType"`
Scanned int `json:"scanned"`
Filtered int `json:"filtered"`
// MaxLastUpdated is the latest resource LastUpdated among rows/resources included
// in the result. Flat Execute counts expanded view rows; FHIR export counts
// matching source resources written to parquet.
MaxLastUpdated time.Time `json:"maxLastUpdated,omitempty"`
}
ResultMetadata captures execution-side metadata.
type RowEncoder ¶
type RowEncoder struct{}
RowEncoder normalizes fhirpath.Value collections into JSON-safe values. Empty results become null; singletons become scalars; multi-item results become arrays. Complex objects are converted only when they are already representable from pkg/fhirpath.Value (currently system.Quantity); otherwise ErrRowEncoding is returned.
func (*RowEncoder) Encode ¶
func (e *RowEncoder) Encode(values []fhirpath.Value) (any, error)
Encode converts a fhirpath collection to a JSON-safe value.
func (*RowEncoder) EncodeColumn ¶
EncodeColumn converts a FHIRPath collection to a JSON-safe value. When collection is true, singleton results are wrapped in a one-element array. When collection is false, multi-item results return ErrRowEncoding.
type RunService ¶
type RunService struct {
// contains filtered or unexported fields
}
RunService executes synchronous ViewDefinition runs.
func NewRunService ¶
func NewRunService(executor *Executor) *RunService
NewRunService returns a RunService.
func (*RunService) Execute ¶
func (s *RunService) Execute(ctx context.Context, req ViewRunRequest) ([]byte, string, error)
Execute runs a registered or inline ViewDefinition and encodes the result.
type SQLQueryEngine ¶
type SQLQueryEngine struct {
// contains filtered or unexported fields
}
SQLQueryEngine executes read-only SQL against reporting table snapshots.
func NewSQLQueryEngine ¶
func NewSQLQueryEngine(tables store.ReportingTableStore) *SQLQueryEngine
NewSQLQueryEngine returns an engine backed by ReportingTableStore.
func (*SQLQueryEngine) Query ¶
func (e *SQLQueryEngine) Query(ctx context.Context, sqlText string, tables []ReportingTableRef) (*SQLQueryResult, error)
Query executes one read-only SQL statement against loaded reporting tables. Table names correspond to sanitized view names from reporting metadata.
type SQLQueryRequest ¶
type SQLQueryRequest struct {
SQL string
Tables []ReportingTableRef
Format OutputFormat
}
SQLQueryRequest carries one SQL-on-FHIR sqlquery-run request.
type SQLQueryResult ¶
type SQLQueryResult struct {
Columns []ColumnInfo `json:"columns"`
Rows []map[string]any `json:"rows"`
}
SQLQueryResult is the tabular output of one SQL query.
type SQLQueryService ¶
type SQLQueryService struct {
// contains filtered or unexported fields
}
SQLQueryService executes SQL queries against reporting tables.
func NewSQLQueryService ¶
func NewSQLQueryService(engine *SQLQueryEngine) *SQLQueryService
NewSQLQueryService returns a SQLQueryService.
func (*SQLQueryService) Execute ¶
func (s *SQLQueryService) Execute(ctx context.Context, req SQLQueryRequest) ([]byte, string, error)
Execute runs one SQL query and encodes the result.
type SearchMode ¶
type SearchMode string
SearchMode controls whether view execution uses the search index.
const ( // SearchModeAuto uses search when configured and search params are available. SearchModeAuto SearchMode = "auto" // SearchModeIndex requires search-backed candidate resolution. SearchModeIndex SearchMode = "index" // SearchModeScan forces ListIDs scanning. SearchModeScan SearchMode = "scan" )
type SelectSpec ¶
type SelectSpec struct {
Columns []ColumnSpec
Children []SelectSpec
ForEach string
ForEachOrNull string
UnionAll []SelectSpec
// contains filtered or unexported fields
}
SelectSpec is one node in a ViewDefinition select tree. Columns are evaluated in the current iteration context; nested Children are cross-joined with parent rows; ForEach / ForEachOrNull iterate over a FHIRPath collection; UnionAll concatenates sibling branches.
func (*SelectSpec) FlattenColumns ¶
func (s *SelectSpec) FlattenColumns() []ColumnSpec
FlattenColumns returns output columns in tree order for metadata.
type TimestampEncoding ¶
type TimestampEncoding = parquetfhir.TimestampEncoding
TimestampEncoding selects Parquet-on-FHIR date annotation physical types.
func NormalizeTimestampEncoding ¶
func NormalizeTimestampEncoding(enc TimestampEncoding) TimestampEncoding
NormalizeTimestampEncoding returns int64 unless enc is explicitly int96.
func ParseTimestampEncoding ¶
func ParseTimestampEncoding(raw string) (TimestampEncoding, error)
ParseTimestampEncoding maps _parquetTimestampEncoding query or Parameters body values.
type ViewExportJob ¶
type ViewExportJob struct {
ID string `json:"id"`
Status ExportStatus `json:"status"`
Request ViewExportRequest `json:"request"`
Files []ExportFile `json:"files,omitempty"`
Progress string `json:"progress,omitempty"`
LastError string `json:"lastError,omitempty"`
CreatedAt time.Time `json:"createdAt"`
CompletedAt time.Time `json:"completedAt,omitempty"`
Cancelled bool `json:"cancelled,omitempty"`
}
ViewExportJob tracks async export progress.
type ViewExportJobPayload ¶
type ViewExportJobPayload struct {
JobID string `json:"jobId"`
}
ViewExportJobPayload is the background job payload for export execution.
type ViewExportJobStore ¶
type ViewExportJobStore interface {
Create(ctx context.Context, job ViewExportJob) error
Get(ctx context.Context, id string) (*ViewExportJob, error)
Update(ctx context.Context, job ViewExportJob) error
}
ViewExportJobStore persists export jobs.
func NewInMemoryViewExportJobStore ¶
func NewInMemoryViewExportJobStore() ViewExportJobStore
NewInMemoryViewExportJobStore returns an ephemeral export job store.
type ViewExportRequest ¶
type ViewExportRequest struct {
Views []ViewExportTarget `json:"views"`
Since time.Time `json:"since"`
Format OutputFormat `json:"format"`
ParquetLayout ParquetLayout `json:"parquetLayout,omitempty"`
TimestampEncoding TimestampEncoding `json:"timestampEncoding,omitempty"`
Actor string `json:"actor,omitempty"`
Subject string `json:"subject,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
}
ViewExportRequest captures one ViewDefinition export operation.
type ViewExportTarget ¶
type ViewExportTarget struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
OutputName string `json:"outputName,omitempty"`
}
ViewExportTarget identifies one view to export.
type ViewRunRequest ¶
type ViewRunRequest struct {
ViewName string
Version string
InlineDef []byte
Since time.Time
Limit int
Offset int
Actor string
Subject string
Parameters map[string]any
Format OutputFormat
ParquetLayout ParquetLayout
TimestampEncoding TimestampEncoding
Header bool
}
ViewRunRequest captures parameters for ViewDefinition/$viewdefinition-run.
type ViewSpec ¶
type ViewSpec struct {
Name string
Version string
URL string
ResourceType string
Description string
Status string
RootSelect SelectSpec
Columns []ColumnSpec
Filters []FilterSpec
Permissions []string
Metadata map[string]string
// Materialize enables writing rows to MaterializedViewStore when configured
// on the Executor. MaterializeKey names the output column used as the row key.
Materialize bool
MaterializeKey string
SearchParams url.Values
SearchMode SearchMode
Raw []byte
// contains filtered or unexported fields
}
ViewSpec is a normalized internal representation of one parsed FHIR ViewDefinition, including source resource type, compiled filter expressions, compiled column expressions, declared permissions, and optional metadata tags.
func ParseDefinition ¶
ParseDefinition loads and validates a ViewDefinition payload into a normalized ViewSpec. All filter and column FHIRPath expressions are compiled with engine to fail fast on invalid expressions. Engine must be non-nil.
func RegisterViewDefinition ¶
RegisterViewDefinition parses raw JSON and registers it when resourceType is ViewDefinition.
func (*ViewSpec) ColumnInfos ¶
func (s *ViewSpec) ColumnInfos() []ColumnInfo
ColumnInfos returns column metadata for the view.
func (*ViewSpec) ColumnNames ¶
ColumnNames returns the declared output column names in order.
Source Files
¶
- audit.go
- auth.go
- builtins.go
- definition.go
- doc.go
- encode.go
- errors.go
- executor.go
- executor_search.go
- executor_select.go
- export_encode.go
- export_files.go
- export_service.go
- export_writer.go
- format.go
- loader.go
- local_job_stores.go
- materialize_service.go
- parquet_encode.go
- parquet_fhir_export.go
- parquet_layout.go
- parquet_output.go
- parquet_schema.go
- parquet_timestamp.go
- paths.go
- proto_choice.go
- proto_temporal.go
- reference.go
- registry.go
- run_service.go
- select.go
- sql_engine.go
- watermark_time.go