cql

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 11 Imported by: 0

README

go-cql

CI Go Reference codecov Go Report Card

A native Clinical Quality Language (CQL) engine for Go, designed for evaluating CQL expressions against FHIR R4 resources.

Installation

go get github.com/gofhir/cql

Quick Start

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/gofhir/cql"
)

func main() {
	engine := cql.NewEngine(
		cql.WithTimeout(30 * time.Second),
	)

	cqlSource := `
		library Example version '1.0'
		using FHIR version '4.0.1'
		context Patient
		define IsAdult: AgeInYears() >= 18
	`

	patient := json.RawMessage(`{"resourceType": "Patient", "birthDate": "1990-01-01"}`)

	results, err := engine.EvaluateLibrary(context.Background(), cqlSource, patient, nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("IsAdult:", results["IsAdult"])
}

Conformance

1731/1731 (100%) — passes all official cqframework/cql-tests conformance suites.

Suite Tests Status
Aggregate Functions 50/50
Aggregate Operator 9/9
Arithmetic Functions 212/212
Comparison Operators 223/223
Conditional Operators 9/9
DateTime Operators 317/317
Errors and Messaging 4/4
Interval Operators 412/412
List Operators 212/212
Logical Operators 39/39
Nullological Operators 22/22
Query Expressions 12/12
String Operators 81/81
Type Operators 35/35
Types 28/28
Value Literals & Selectors 66/66

Run conformance tests locally:

go test ./conformance/... -v

Features

  • Full CQL parsing via ANTLR4 grammar
  • 100% conformance with the official CQL test suite
  • Expression evaluation with FHIR R4 context
  • Pluggable data and terminology providers
  • Compiled expression caching
  • Configurable timeouts and resource limits
  • Trace listener support for debugging

API

Engine
// Create engine with options
engine := cql.NewEngine(
    cql.WithDataProvider(dp),
    cql.WithTerminologyProvider(tp),
    cql.WithTimeout(30 * time.Second),
    cql.WithMaxDepth(100),
)

// Evaluate all definitions in a CQL library
results, err := engine.EvaluateLibrary(ctx, cqlSource, resource, params)

// Evaluate a single named expression
value, err := engine.EvaluateExpression(ctx, cqlSource, "ExpressionName", resource, params)

// Validate CQL syntax without evaluation
err := engine.Compile(cqlSource)
Options
Option Description Default
WithDataProvider Data provider for retrieve expressions nil
WithTerminologyProvider Terminology provider for valueset checks nil
WithModelInfo FHIR model information R4
WithTimeout Per-evaluation timeout 30s
WithMaxExpressionLen Maximum CQL source length 100KB
WithMaxRetrieveSize Maximum resources per retrieve 10000
WithMaxDepth Maximum recursion depth 100
WithTraceListener Trace listener for debugging nil

Error Handling

The engine returns typed errors for different failure modes:

Error Type Description
ErrSyntaxError CQL parse error
ErrEvaluation Runtime evaluation error
ErrTimeout Evaluation exceeded timeout
ErrTooCostly Expression exceeds size limits

License

MIT - Copyright (c) 2025 Roberto Araneda

Documentation

Overview

Package cql provides a native CQL (Clinical Quality Language) engine for Go.

The engine parses CQL text into an AST, evaluates expressions, and supports FHIR data retrieval through pluggable data and terminology providers.

Basic usage:

engine := cql.NewEngine(
    cql.WithDataProvider(myDataProvider),
    cql.WithTimeout(30 * time.Second),
)
results, err := engine.EvaluateLibrary(ctx, cqlSource, patientJSON, params)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Engine

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

Engine is the public API for the CQL engine.

func NewEngine

func NewEngine(opts ...Option) *Engine

NewEngine creates a new CQL engine with the given options.

func (*Engine) Compile

func (e *Engine) Compile(cqlSource string) error

Compile parses a CQL source string without evaluating it. Useful for syntax validation and data requirements analysis.

func (*Engine) EvaluateExpression

func (e *Engine) EvaluateExpression(
	ctx context.Context,
	cqlSource string,
	expressionName string,
	contextResource json.RawMessage,
	params map[string]fptypes.Value,
	evalOpts ...EvalOption,
) (fptypes.Value, error)

EvaluateExpression parses CQL source and evaluates a single named expression. Optional EvalOption arguments allow per-call configuration (e.g., WithCallTraceListener).

func (*Engine) EvaluateLibrary

func (e *Engine) EvaluateLibrary(
	ctx context.Context,
	cqlSource string,
	contextResource json.RawMessage,
	params map[string]fptypes.Value,
	evalOpts ...EvalOption,
) (map[string]fptypes.Value, error)

EvaluateLibrary parses and evaluates a CQL library, returning named expression results. Optional EvalOption arguments allow per-call configuration (e.g., WithCallTraceListener).

type ErrEvaluation

type ErrEvaluation struct {
	Cause error
}

ErrEvaluation indicates a runtime evaluation error (HTTP 422).

func (*ErrEvaluation) Error

func (e *ErrEvaluation) Error() string

func (*ErrEvaluation) Unwrap

func (e *ErrEvaluation) Unwrap() error

type ErrSyntaxError

type ErrSyntaxError struct {
	Cause error
}

ErrSyntaxError indicates a CQL parse error (HTTP 400).

func (*ErrSyntaxError) Error

func (e *ErrSyntaxError) Error() string

func (*ErrSyntaxError) Unwrap

func (e *ErrSyntaxError) Unwrap() error

type ErrTimeout

type ErrTimeout struct {
	Duration time.Duration
}

ErrTimeout indicates the evaluation exceeded the configured timeout (HTTP 408).

func (*ErrTimeout) Error

func (e *ErrTimeout) Error() string

type ErrTooCostly

type ErrTooCostly struct {
	Msg string
}

ErrTooCostly indicates the evaluation is too expensive (HTTP 422).

func (*ErrTooCostly) Error

func (e *ErrTooCostly) Error() string

type EvalOption

type EvalOption func(*evalConfig)

EvalOption configures a single evaluation call.

func WithCallTraceListener

func WithCallTraceListener(tl eval.TraceListener) EvalOption

WithCallTraceListener sets a trace listener for a specific call, overriding the engine-level trace listener for that call only. This enables per-request tracing in concurrent environments.

type Option

type Option func(*Engine)

Option configures the Engine.

func WithDataProvider

func WithDataProvider(dp eval.DataProvider) Option

WithDataProvider sets the data provider for retrieve expressions.

func WithMaxDepth

func WithMaxDepth(n int) Option

WithMaxDepth sets the maximum recursion depth for nested expressions.

func WithMaxExpressionLen

func WithMaxExpressionLen(n int) Option

WithMaxExpressionLen sets the maximum CQL source length (DoS protection).

func WithMaxRetrieveSize

func WithMaxRetrieveSize(n int) Option

WithMaxRetrieveSize sets the maximum number of resources per retrieve.

func WithModelInfo

func WithModelInfo(mi model.ModelInfo) Option

WithModelInfo sets the FHIR model information.

func WithTerminologyProvider

func WithTerminologyProvider(tp eval.TerminologyProvider) Option

WithTerminologyProvider sets the terminology provider for valueset checks.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-evaluation timeout.

func WithTraceListener

func WithTraceListener(tl eval.TraceListener) Option

WithTraceListener sets a trace listener for expression-level debugging. When set, OnEnter/OnExit are called for every expression evaluation, allowing construction of trace trees for debugging and profiling.

Directories

Path Synopsis
Package ast defines the Abstract Syntax Tree (AST) node types for CQL.
Package ast defines the Abstract Syntax Tree (AST) node types for CQL.
Package compiler transforms CQL source text into an AST representation.
Package compiler transforms CQL source text into an AST representation.
Package elm implements the HL7 CQL Expression Logic Model (ELM) serialization.
Package elm implements the HL7 CQL Expression Logic Model (ELM) serialization.
Package eval implements the CQL expression evaluator.
Package eval implements the CQL expression evaluator.
Package model provides version-agnostic FHIR model information for the CQL engine.
Package model provides version-agnostic FHIR model information for the CQL engine.
parser
Package types defines CQL-specific types that extend the FHIRPath type system.
Package types defines CQL-specific types that extend the FHIRPath type system.

Jump to

Keyboard shortcuts

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