celvalues

package
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 21 Imported by: 0

README

Typed CEL dates and currency

celvalues supplies civil dates and CEL integration for commons/decimal.Money and commons/bigdecimal.Money. Gomplate enables its CEL library automatically. Applications using cel-go directly add celvalues.Library(); custom function callbacks adapt their results with celvalues.NewAdapter(env.CELTypeAdapter()).NativeToValue(value).

Declare direct cel-go record variables as cel.DynType or cel.MapType(cel.StringType, cel.DynType) so CEL's static checker permits comparisons between their fields and primitive literals.

dueDate, err := celvalues.NewDate("2026-11-10")
if err != nil {
    return err
}
premium, err := decimal.NewMoney(decimal.MoneyOptions{
    Amount: "125.005",
    Currency: "USD",
    DecimalPlaces: 2,
})
if err != nil {
    return err
}
result, err := gomplate.RunExpression(map[string]any{
    "policy": map[string]any{"DueDate": dueDate, "PremiumDue": premium},
}, gomplate.Template{
    Expression: `policy.DueDate <= "2026-11-10" && policy.PremiumDue > 100`,
    Strict: true,
})

NewDate accepts an exact YYYY-MM-DD calendar date. Dates compare to other dates, ISO date strings, or the UTC calendar day of a CEL timestamp. string(policy.DueDate) returns 2026-11-10. Actual timestamp values retain CEL's timestamp behavior.

Import decimal from github.com/flanksource/commons/decimal. Amount is a finite decimal string rounded half-even to the backend precision: decimal supports 19 digits; bigdecimal provides decimal128 precision. Currency is a three-letter uppercase code. DecimalPlaces is the minimum display scale, between 0 and 31; extra stored fractional precision is retained. string(policy.PremiumDue) above returns USD 125.005. A value of 125 with scale 2 returns USD 125.00.

Money compares to numbers or money of the same precision type and currency. All comparison operators work in either operand position. Comparing different currencies or precision types is an error. Implicit currency conversion is not provided.

bigdecimal.Money supports exact arithmetic, and the result is always a Money in the operand's currency:

Expression Result
money + money, money - money Same currency only; keeps whichever operand shows more decimal places
money + n, n + money, money - n, n - money n (int, uint or double) is an amount in the Money's currency
money * n, n * money, money / n Scales the amount
-money Negates the amount

Doubles are read through their shortest decimal form, so money - 0.1 - 0.2 == money - 0.3 holds exactly. Multiplying or dividing two Money values, dividing a number by Money, mixing currencies, dividing by zero, and any arithmetic on decimal.Money are errors. Numeric arithmetic that involves no Money keeps CEL's own behaviour. Dates and money remain native values through CEL-created maps/lists and custom functions; converting a value to JSON explicitly renders its string representation.

Go values in the environment

NewAdapter reads host Go values lazily. Gomplate adapts each environment value without copying it, so an expression pays only for the fields it reads. Values registered with gomplate.RegisterType keep cel-go's native type handling instead.

Go value CEL value
Struct, or pointer to one Map keyed the way encoding/json names fields: json tag names, json:"-" and unexported fields absent, omitempty zero values absent, embedded struct fields promoted
Map, slice, array Map or list whose entries are converted as they are read
uuid.UUID String
AsMap(...string) map[string]any The returned map
Unsigned integer Int, when it fits in int64
Nil pointer null
time.Time, *time.Time, time.Duration, []byte, Money Timestamp, duration, bytes or Money, at any depth

Go templates resolve struct fields with the same keys through celvalues.Field, except that omitempty zero fields stay present; see Reading the environment.

A function or result that receives one of these maps or lists gets plain Go values: map[string]any, []any, int64 and strings, with dates, durations, bytes and Money kept. celvalues.Plain(value) performs the same conversion.

String collection .sum() uses commons/decimal parsing and summation, rounding inputs and the final result to its precision without intermediate rounding of additions. Results have no insignificant trailing zeros. Invalid inputs and overflow return errors; sufficiently small inputs round to zero.

Run the scalar and Gomplate integration specs from the module root:

go test ./celvalues

Documentation

Overview

Package celvalues provides civil dates and Commons Money integration for CEL.

NewDate accepts YYYY-MM-DD. Date comparisons accept another Date, an ISO date string, or the UTC calendar day of a CEL timestamp. Construct currency amounts with commons/decimal.NewMoney or commons/bigdecimal.NewMoney. Money may be compared with a number or money in the same currency; different currencies produce an error. Both types support string() and preserve their native Go values through Gomplate evaluations, including nested maps and lists.

Gomplate includes Library automatically. Plain cel-go callers add Library() to their environment options. Custom callbacks adapt Money through NewAdapter.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Field

func Field(value reflect.Value, key string) (reflect.Value, bool)

Field reads one field of a struct by the key encoding/json names it with, following the same rules as the CEL view of the struct except omitempty: a zero field is still present.

func Library

func Library() cel.EnvOption

Library enables Date and Money comparisons and string conversions.

func NewAdapter

func NewAdapter(base types.Adapter) types.Adapter

NewAdapter extends an existing CEL adapter with Commons Money support. Use this adapter for custom function results as well as host input.

func Plain

func Plain(value any) any

Plain converts a host value to the Go form CEL reads it as: structs become maps keyed like encoding/json, maps become map[string]any, lists []any, integers int64 and UUIDs strings. Dates, durations, Money, bytes and CEL values are kept.

Types

type AsMapper

type AsMapper interface {
	AsMap(fields ...string) map[string]any
}

AsMapper is implemented by host values that present themselves to CEL as a map.

type Date

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

Date is a civil calendar day. Construct it with NewDate.

func NewDate

func NewDate(value string) (Date, error)

NewDate accepts an exact YYYY-MM-DD date without a time or timezone.

func (Date) Compare

func (d Date) Compare(other ref.Val) ref.Val

func (Date) ConvertToNative

func (d Date) ConvertToNative(target reflect.Type) (any, error)

func (Date) ConvertToType

func (d Date) ConvertToType(target ref.Type) ref.Val

func (Date) Equal

func (d Date) Equal(other ref.Val) ref.Val

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

func (Date) String

func (d Date) String() string

func (Date) Type

func (d Date) Type() ref.Type

func (Date) Value

func (d Date) Value() any

Jump to

Keyboard shortcuts

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