cql

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

README

haistack-cql (pkg/cql)

Clinical Quality Language 1.5 evaluation for SDC questionnaires, in-memory clinical reasoning, and CQF Measure reports.

This package runs CQL libraries and inline expressions against a Patient (and, optionally, retrieved clinical resources). It also evaluates FHIR Measure resources into MeasureReport (individual, summary, subject-list). FHIR Library resources may include text/cql (or application/cql) source or application/elm+json. ELM JSON is compiled into the same evaluator used for CQL. Empty ELM payloads and application/elm+xml return ErrUnsupported.

CQL vs FHIRPath

FHIRPath (pkg/fhirpath) CQL (pkg/cql)
Typical SDC language text/fhirpath text/cql, text/cql.identifier, application/cql, application/x-cql
Unit of reuse One path on the current resource Named define / define function in a Library
Context Current resource (%resource, %subject) context Patient plus parameters
Clinical helpers Custom functions you register Built-ins such as AgeInYears()
Retrieve No (use FHIR Query / search) [Observation] when a Retriever is wired
Quality reporting No EvaluateMeasure → MeasureReport

Use FHIRPath for field access and enablement on the resource in focus. Use CQL when the questionnaire references a cqf-library (or contained Library) and expressions should share named clinical logic, or when evaluating a Measure.

CQL 1.5 coverage

  • library / using FHIR / include / context Patient or Unfiltered
  • define named expressions and define function / define fluent function
  • parameter declarations with optional defaults (Measurement Period for measures)
  • literals, identifiers, arithmetic, comparison, and / or / xor / not / implies
  • if then else, case when else, is null / is not null
  • FHIR property navigation (Patient.name.given); uses Config.FHIRPath when set, otherwise JSON navigation
  • retrieve [ResourceType] and related-context aliases ([Observation] O)
  • queries: from / where / return / sort by / with / without / let
  • Bracket-query shorthand (top-level define bodies and Engine.Eval / ParseExpression only): [Observation] O where O.status = 'final' is equivalent to from [Observation] O where O.status = 'final'. Inside a let operand, [Observation] is only a retrieve (not a query); use from [Observation] O … or let L: [Observation] when you need an aliased source in a query clause.
  • define function optional returns type (e.g. returns List<Integer>) for list-valued results in in / tuple fields
  • as promotions: Integer↔Decimal, Date↔DateTime, whole Decimal→Integer/Long, DateTime↔Time, dimensionless Quantity→Integer/Decimal
  • Interval values and operators (in, contains, during, includes, overlaps, …)
  • Quantity literals (5 'mg', 1 year) and duration in years between; quantity +/- convert compatible units via Config.UCUM
  • List in / contains / distinct / intersect / except / union dedupe / IndexOf / Mode use equivalence (~) for membership, not strict =
  • codesystem / valueset / code declarations
  • retrieve and in filters against FHIR Coding / CodeableConcept (value-set MemberOf when Config.Terminology is set)
  • First, Last, Count, Exists, AgeInYears, ToString, ToInterval, Min / Max / Sum and related helpers

Unsupported (clear error): empty ELM payloads, application/elm+xml, or an unimplemented operator. application/elm+json Libraries compile into this package's AST. Prefer attaching text/cql with AttachLibraryCQL when the original source is available.

Tests as examples

These tests double as executable examples for common patterns:

Topic Go test (in this package)
Bracket-query shorthand in a define TestDefineBracketQueryShorthand (engine_test.go)
Measure → MeasureReport TestEvaluateMeasureIndividualAndSummary, TestEvaluateMeasureListMembershipAndStratifierAndSDE (measure_test.go)
define function … returns List<T> TestFunctionReturnsListType (engine_test.go)
ELM FunctionDef + resultTypeSpecifier TestELMFunctionReturnType (elm_test.go)
List parameters / defines / in TestListParameterIdentSemantics, TestDefineListIdentSemantics

Usage

eng, err := cql.NewEngine(cql.Config{})
patient := envelope // *types.ResourceEnvelope for Patient

values, err := eng.Eval(ctx, "First(Patient.name.given)", cql.EvalContext{
    Patient: patient,
})

lib, err := eng.ParseLibrary(cqlSource)
values, err = eng.EvalDefine(ctx, lib, "Patient Given Name", cql.EvalContext{
    Patient: patient,
})

Evaluate a Measure:

report, err := eng.EvaluateMeasure(ctx, cql.MeasureRequest{
    Measure:     measureEnvelope,
    PeriodStart: start,
    PeriodEnd:   end,
    ReportType:  "individual",
    Patient:     patient,
    Libraries:   []*cql.Library{lib},
})

Load a FHIR Library resource:

lib, err := eng.CompileLibrary(libraryEnvelope) // text/cql or application/elm+json
src, url, name, version, err := cql.EnvelopeLibrary(libraryEnvelope) // CQL source only
env, err = cql.AttachLibraryCQL(libraryEnvelope, cqlSource)

SDC adapter

cql.Provider implements sdc.CQLProvider. Wire it with sdc.ComposeExpressions so $populate, $validate, and Render can evaluate CQL expressions:

eng, _ := cql.NewEngine(cql.Config{FHIRPath: fhirPathEngine})
cqlProvider := cql.NewProvider(eng, &cql.StoreLibraryResolver{
    Resources: resourceStore,
    Engine:    eng,
})
provider := sdc.ComposeExpressions(
    sdc.FHIRPathExpressions{Engine: fhirPathEngine},
    fhirQuery, // optional
    cqlProvider,
)

The default pkg/runtime wiring does this automatically: CQL libraries are resolved from stored Library resources, questionnaire contained Libraries, and cqf-library canonicals. Missing Patient context or a missing library returns a diagnostic rather than a silent empty answer.

Questionnaire expressions:

  • text/cql / application/cql / application/x-cql — inline CQL
  • text/cql.identifier — name of a define in a loaded library

Measure/$evaluate-measure

Runtime wires http.CoreMeasureService so GET/POST /fhir/Measure/{id}/$evaluate-measure (and type-level /fhir/Measure/$evaluate-measure?measure=) return a MeasureReport.

Query or Parameters inputs: periodStart, periodEnd (required), reportType (individual / subject-list / summary), subject (Patient/{id}).

Errors

  • ErrMissingContext — Patient context required but not supplied
  • ErrLibraryNotFound — canonical Library could not be loaded
  • ErrExpressionNotFound — named define is missing
  • ErrUnsupported — empty/non-JSON ELM, ELM XML, or an unimplemented operator
  • ErrMeasure — Measure evaluation input or criteria failed
  • ErrEmptyExpression / ErrEngineUnavailable

See doc.go for package boundaries and the tests in this directory for executable examples.

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

View Source
const DefaultMaxExpressionLen = 65536

Variables

View Source
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 is returned when evaluation is attempted without an engine.
	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

func IsLanguage(lang string) bool

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 Code

type Code struct {
	Name    string
	Code    string
	System  string
	Display string
}

Code is a CQL code declaration.

type CodeSystem

type CodeSystem struct {
	Name string
	URL  string
}

CodeSystem is a CQL codesystem declaration.

type Concept

type Concept struct {
	Name    string
	Codes   []string
	Display string
}

Concept is a CQL concept 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 Define

type Define struct {
	Name       string
	Access     string
	Expression Node
	Source     string
}

Define is a named CQL expression.

type Engine

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

Engine compiles and evaluates CQL 1.5 libraries and Measure reports.

func NewEngine

func NewEngine(cfg Config) (*Engine, error)

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

func (e *Engine) Eval(ctx context.Context, expr string, env EvalContext) ([]any, error)

Eval evaluates a CQL expression or named identifier against env.

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

func (e *Engine) ParseELM(src []byte) (*Library, error)

ParseELM compiles an application/elm+json library into the CQL evaluator AST.

func (*Engine) ParseExpression

func (e *Engine) ParseExpression(src string) (Node, error)

ParseExpression compiles a CQL expression (not a full library).

func (*Engine) ParseLibrary

func (e *Engine) ParseLibrary(src string) (*Library, error)

ParseLibrary compiles CQL library source.

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

type FunctionParam struct {
	Name string
	Type string
}

FunctionParam is a CQL function operand.

type Include

type Include struct {
	Name    string
	Version string
	Called  string
}

Include records an included CQL library. FHIRHelpers is provided as a builtin.

type Interval

type Interval struct {
	Low, High             any
	LowClosed, HighClosed bool
}

Interval is a CQL Interval value.

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

type LibraryResolver interface {
	Resolve(ctx context.Context, canonical string) (*Library, error)
}

LibraryResolver loads a CQL library by canonical URL (url or url|version).

type MapLibraryResolver

type MapLibraryResolver map[string]string

MapLibraryResolver resolves from an in-memory CQL source table.

func (MapLibraryResolver) Resolve

func (m MapLibraryResolver) Resolve(_ context.Context, canonical string) (*Library, error)

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 Parameter

type Parameter struct {
	Name    string
	Type    string
	Default Node
}

Parameter is a CQL parameter declaration with an optional default.

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.

func (Provider) EvaluateCQL

func (p Provider) EvaluateCQL(ctx context.Context, expr string, input any) ([]any, error)

EvaluateCQL evaluates a CQL expression or named library define.

type Quantity

type Quantity struct {
	Value float64
	Unit  string
}

Quantity is a CQL Quantity value (5 'mg', 1 year).

type Ratio

type Ratio struct {
	Numerator   Quantity
	Denominator Quantity
}

Ratio is a CQL Ratio value (numerator / denominator quantities).

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

type StaticLibraries map[string]*Library

StaticLibraries resolves libraries from an in-memory canonical table.

func (StaticLibraries) Resolve

func (s StaticLibraries) Resolve(_ context.Context, canonical string) (*Library, error)

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.

func (*StoreLibraryResolver) Resolve

func (r *StoreLibraryResolver) Resolve(ctx context.Context, canonical string) (*Library, error)

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.

type ValueSet

type ValueSet struct {
	Name string
	URL  string
}

ValueSet is a CQL valueset declaration.

Jump to

Keyboard shortcuts

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