Documentation
¶
Overview ¶
Package cql implements a Clinical Quality Language (CQL) 1.5 engine for HAIStack SDC questionnaires and CQF Measure evaluation.
The engine compiles text/cql libraries and application/elm+json Libraries into the same evaluator AST, then runs them against Patient or Unfiltered context. Empty or non-JSON ELM payloads remain unsupported.
Role in the stack ¶
FHIRPath (pkg/fhirpath) reads fields inside a single resource with path expressions. CQL names reusable clinical logic in libraries, supports Patient context, retrieve, Interval/Quantity, queries, and functions. CQF Measure resources reference those libraries; EvaluateMeasure produces a MeasureReport (individual, summary, or subject-list). SDC questionnaires may use either language; wire both through sdc.ComposeExpressions.
Typical consumers are pkg/sdc (populate, validate, render expression providers), pkg/http (Measure/$evaluate-measure), and pkg/runtime (default CQLProvider and measure service when libraries can be loaded from the resource store or contained Questionnaire resources).
CQL 1.5 coverage ¶
- library / using FHIR / include / context Patient | Unfiltered
- define statements and define function / define fluent function
- parameter declarations with optional defaults (including Measurement Period)
- literals, identifiers, arithmetic, comparison, and/or/xor/not/implies
- if-then-else, case-when-else, is null / is not null, as Type
- FHIR property navigation (Patient.name.given); FHIRPath when Config.FHIRPath is set
- retrieve [ResourceType] (optional terminology) and related-context aliases
- queries: from / where / return / sort / with / without / let
- Interval values and operators (in, contains, during, includes, overlaps, starts, ends, before, after)
- Quantity literals (5 'mg', 1 year), UCUM-aware quantity +/-, and duration in years/months/days
- List membership helpers (in, contains, distinct, intersect, except, IndexOf, Mode) use equivalence (~)
- codesystem / valueset / code declarations
- retrieve and `in` filters against Coding/CodeableConcept (MemberOf when Config.Terminology is set)
- First, Last, Count, Exists, AgeInYears, ToString, ToInterval, Min/Max/Sum and related helpers
ELM JSON is compiled into this package's AST (not a separate ELM engine). Empty ELM payloads and application/elm+xml still return ErrUnsupported.
Integration ¶
pkg/cql must not be imported by pkg/sdc. The SDC adapter in this package implements sdc.CQLProvider. Applications and pkg/runtime inject it with sdc.ComposeExpressions. Measure/$evaluate-measure is exposed by pkg/http when a MeasureEvaluateService (default: http.CoreMeasureService) is wired.
Index ¶
- Constants
- Variables
- func AttachLibraryCQL(env *types.ResourceEnvelope, source string) (*types.ResourceEnvelope, error)
- func EnvelopeLibrary(env *types.ResourceEnvelope) (source string, url, name, version string, err error)
- func IsLanguage(lang string) bool
- func ListStorePatients(ctx context.Context, resources interface{ ... }) ([]any, error)
- func MeasureLibraryCanonicals(env *types.ResourceEnvelope) []string
- type Code
- type CodeSystem
- type Concept
- type Config
- type Define
- type Engine
- func (e *Engine) CompileLibrary(env *types.ResourceEnvelope) (*Library, error)
- func (e *Engine) Eval(ctx context.Context, expr string, env EvalContext) ([]any, error)
- func (e *Engine) EvalDefine(ctx context.Context, lib *Library, name string, env EvalContext) ([]any, error)
- func (e *Engine) EvaluateMeasure(ctx context.Context, req MeasureRequest) (*types.ResourceEnvelope, error)
- func (e *Engine) ParseELM(src []byte) (*Library, error)
- func (e *Engine) ParseExpression(src string) (Node, error)
- func (e *Engine) ParseLibrary(src string) (*Library, error)
- type EvalContext
- type Function
- type FunctionParam
- type Include
- type Interval
- type Library
- type LibraryResolver
- type MapLibraryResolver
- type MeasureRequest
- type Node
- type Parameter
- type Provider
- type Quantity
- type Ratio
- type ReferenceLookup
- type Request
- type RetrieveRequest
- type Retriever
- type StaticLibraries
- type StaticRetriever
- type StoreLibraryResolver
- type StoreRetriever
- type UCUMConverter
- type ValueSet
Constants ¶
const DefaultMaxExpressionLen = 65536
Variables ¶
var ( // ErrMissingContext is returned when a Patient-context expression is // evaluated without a subject Patient. ErrMissingContext = errors.New("CQL Patient context is missing") // ErrLibraryNotFound is returned when a referenced CQL library cannot be loaded. ErrLibraryNotFound = errors.New("CQL library was not found") // ErrExpressionNotFound is returned when a named define is missing from loaded libraries. ErrExpressionNotFound = errors.New("CQL expression was not found in the loaded libraries") ErrEngineUnavailable = errors.New("CQL engine is unavailable") // ErrUnsupported is returned for CQL features that are not implemented, // including empty or non-JSON ELM payloads. ErrUnsupported = errors.New("CQL feature is not supported") // ErrEmptyExpression is returned when the expression text is empty. ErrEmptyExpression = errors.New("CQL expression is empty") // ErrMeasure is returned when a FHIR Measure cannot be evaluated. ErrMeasure = errors.New("CQL measure evaluation failed") )
Functions ¶
func AttachLibraryCQL ¶
func AttachLibraryCQL(env *types.ResourceEnvelope, source string) (*types.ResourceEnvelope, error)
AttachLibraryCQL returns a copy of env with text/cql content set to source. Existing CQL attachments are replaced; ELM and other content attachments are kept.
func EnvelopeLibrary ¶
func EnvelopeLibrary(env *types.ResourceEnvelope) (source string, url, name, version string, err error)
EnvelopeLibrary parses a FHIR Library resource envelope into CQL source. When the Library only has ELM, CQL is recovered from an embedded library string or annotation when present; otherwise ErrUnsupported is returned. Use Engine.CompileLibrary to evaluate ELM-only Libraries.
func IsLanguage ¶
IsLanguage reports whether lang is a CQL expression language.
func ListStorePatients ¶
func ListStorePatients(ctx context.Context, resources interface { ListIDs(ctx context.Context, resourceType string, limit, offset int) ([]string, error) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error) }) ([]any, error)
ListStorePatients loads Patient resources from a ResourceStore for summary evaluation.
func MeasureLibraryCanonicals ¶
func MeasureLibraryCanonicals(env *types.ResourceEnvelope) []string
MeasureLibraryCanonicals returns Measure.library canonicals.
Types ¶
type CodeSystem ¶
CodeSystem is a CQL codesystem declaration.
type Config ¶
type Config struct {
// FHIRPath is optional. When set, resource-root member access is evaluated
// with FHIRPath first; JSON navigation remains the fallback. NewEngine does
// not construct a FHIRPath engine when this is nil.
FHIRPath fhirpath.Engine
// Retriever loads clinical resources for CQL retrieve expressions.
Retriever Retriever
// Terminology is optional. When set, retrieve and `in` valueset filters use
// MemberOf; when it also implements fhirpath.SubsumptionValidator, CQL
// subsumes uses code-system hierarchy instead of string heuristics.
Terminology fhirpath.TerminologyValidator
// UCUM converts quantity units (defaults to a UCUM-essence-backed converter).
UCUM UCUMConverter
// Libraries resolves included CQL libraries (except builtin FHIRHelpers).
Libraries LibraryResolver
// Now overrides the evaluation clock (defaults to time.Now UTC).
Now func() time.Time
// MaxExpressionLen caps CQL source length (default 65536).
MaxExpressionLen int
}
Config configures a CQL engine.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine compiles and evaluates CQL 1.5 libraries and Measure reports.
func NewEngine ¶
NewEngine constructs a CQL engine. Config.FHIRPath is stored as-is and is never defaulted; JSON navigation is used when it is nil.
func (*Engine) CompileLibrary ¶
func (e *Engine) CompileLibrary(env *types.ResourceEnvelope) (*Library, error)
CompileLibrary compiles a FHIR Library resource from text/cql or application/elm+json.
func (*Engine) EvalDefine ¶
func (e *Engine) EvalDefine(ctx context.Context, lib *Library, name string, env EvalContext) ([]any, error)
EvalDefine evaluates a named expression in a compiled library.
func (*Engine) EvaluateMeasure ¶
func (e *Engine) EvaluateMeasure(ctx context.Context, req MeasureRequest) (*types.ResourceEnvelope, error)
EvaluateMeasure runs a FHIR Measure against Patient context(s) and returns a MeasureReport.
func (*Engine) ParseELM ¶
ParseELM compiles an application/elm+json library into the CQL evaluator AST.
func (*Engine) ParseExpression ¶
ParseExpression compiles a CQL expression (not a full library).
type EvalContext ¶
type EvalContext struct {
Patient any
Parameters map[string]any
Libraries []*Library
LibraryRefs []string
Contained []map[string]any
Language string
Now time.Time
Retriever Retriever
}
EvalContext is the evaluation environment for a CQL expression.
type Function ¶
type Function struct {
Name string
Access string
Fluent bool
Params []FunctionParam
ReturnType string
Body Node
Source string
}
Function is a named CQL function (define function / define fluent function).
type FunctionParam ¶
FunctionParam is a CQL function operand.
type Library ¶
type Library struct {
Name string
Version string
Using string
Context string
Includes []Include
Defines []Define
Functions []Function
Parameters []Parameter
CodeSystems []CodeSystem
ValueSets []ValueSet
Codes []Code
Concepts []Concept
Source string
URL string
}
Library is a compiled CQL library.
type LibraryResolver ¶
LibraryResolver loads a CQL library by canonical URL (url or url|version).
type MapLibraryResolver ¶
MapLibraryResolver resolves from an in-memory CQL source table.
type MeasureRequest ¶
type MeasureRequest struct {
// Measure is a FHIR Measure resource.
Measure *types.ResourceEnvelope
// PeriodStart and PeriodEnd bound the Measurement Period parameter.
PeriodStart time.Time
PeriodEnd time.Time
// ReportType is individual, subject-list, or summary (population).
ReportType string
// Subject is Patient/{id} when evaluating an individual report.
Subject string
// Patient is the already-loaded subject for individual reports.
Patient any
// Patients is the population for summary and subject-list reports.
Patients []any
// Libraries are compiled CQL libraries referenced by the Measure.
Libraries []*Library
// Parameters overlay CQL parameter values (Measurement Period is filled from the period).
Parameters map[string]any
// Retriever is used for clinical retrieve during evaluation.
Retriever Retriever
}
MeasureRequest is the input to CQF Measure evaluation.
type Node ¶
type Node interface {
Source() string
// contains filtered or unexported methods
}
Node is a CQL expression AST node.
type Provider ¶
type Provider struct {
Engine *Engine
Libraries LibraryResolver
Retriever Retriever
}
Provider implements sdc.CQLProvider.
func NewProvider ¶
func NewProvider(engine *Engine, libs LibraryResolver) Provider
NewProvider constructs an SDC CQL adapter.
type ReferenceLookup ¶
type ReferenceLookup interface {
LookupReferencing(ctx context.Context, sourceType, fieldKey, targetType, targetID string) ([]string, error)
}
ReferenceLookup finds resources that reference a given target (optional search index).
type Request ¶
type Request struct {
Language string
Name string
Patient any
Parameters map[string]any
Libraries []*Library
LibraryRefs []string
Contained []map[string]any
Input any
}
Request is passed through sdc.CQLProvider.EvaluateCQL as the input value when the SDC adapter has questionnaire or language metadata.
type RetrieveRequest ¶
type RetrieveRequest struct {
ResourceType string
// Terminology is the retrieve filter as written (valueset name, code name, or literal).
Terminology string
// Comparator is in, =, or ~ when the retrieve used `code in` / `code =` / `code ~`.
Comparator string
// CodePath is the retrieve property when present (`category in`, `code =`, …).
CodePath string
// ValueSetURL is set when Terminology names a declared valueset.
ValueSetURL string
// System and Code are set when Terminology names a declared code or system|code literal.
System string
Code string
}
RetrieveRequest names a FHIR resource type and optional terminology filter.
type Retriever ¶
type Retriever interface {
Retrieve(ctx context.Context, req RetrieveRequest, patient any) ([]any, error)
}
Retriever executes CQL retrieve ([Observation], …) against a data source.
type StaticLibraries ¶
StaticLibraries resolves libraries from an in-memory canonical table.
type StaticRetriever ¶
type StaticRetriever []any
StaticRetriever returns a fixed collection, optionally filtered by resource type.
func (StaticRetriever) Retrieve ¶
func (r StaticRetriever) Retrieve(_ context.Context, req RetrieveRequest, _ any) ([]any, error)
type StoreLibraryResolver ¶
type StoreLibraryResolver struct {
Resources store.ResourceStore
Registry store.DefinitionStore
Engine *Engine
// contains filtered or unexported fields
}
StoreLibraryResolver loads FHIR Library resources from a ResourceStore and optionally a DefinitionStore, then compiles their CQL or ELM content.
Resolve peeks url/name/version on listed Library resources so in-place URL retargets are visible, compiles only matching candidates, and caches compiled libraries by resource ID and envelope Hash.
type StoreRetriever ¶
type StoreRetriever struct {
Resources store.ResourceStore
References ReferenceLookup
}
StoreRetriever retrieves FHIR resources from a ResourceStore, filtered by the Patient subject when present. When References is set, retrieve uses subject/patient reference lookups instead of listing every resource of the type.
func (StoreRetriever) Retrieve ¶
func (r StoreRetriever) Retrieve(ctx context.Context, req RetrieveRequest, patient any) ([]any, error)
type UCUMConverter ¶
type UCUMConverter interface {
Canonicalize(unit string) (string, bool)
Convert(value float64, fromUnit, toUnit string) (float64, bool)
Dimension(unit string) (string, bool)
}
UCUMConverter parses UCUM units and converts quantities between compatible units.
func DefaultUCUMConverter ¶
func DefaultUCUMConverter() UCUMConverter
DefaultUCUMConverter uses github.com/iimos/ucum with CQL-friendly unit aliases.