eval

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package eval provides T-SQL expression evaluation for xolu FSM guard conditions and set clauses.

It is a surgical extraction of the ExpressionEvaluator from github.com/ha1tch/aulsql/pkg/tsqlruntime. The Interpreter, ExecutionContext, TempTableManager, CursorManager, and all database machinery have been removed. Only the expression evaluator, the Value type system, ToValue, and the built-in function registry are retained.

Entry points

EvalGuard evaluates a boolean guard expression against machine variables and a walk payload:

ok, err := eval.EvalGuard(e, "payload.result = 'pass' AND @retries < 3",
    map[string]interface{}{"retries": 2},
    map[string]interface{}{"result": "pass", "technician": "alice"})

EvalSet evaluates an arithmetic set-clause expression and returns the new variable value:

val, err := eval.EvalSet(e, "@retries + 1", map[string]interface{}{"retries": 2})

Payload binding convention

Payload fields are bound into the variable map with the prefix "payload." so that the expression `payload.result` resolves to the payload field named "result". This prefix is flattened — nested payload objects are not supported in guard expressions; only top-level string/number/bool fields are accessible.

Machine variables are bound without prefix. A variable declared as `@retries INTEGER` is bound as key "retries" (the @ is stripped by SetVariable). Guard expressions reference it as `@retries`.

Generator functions

The four stateless generators are registered on every Evaluator so they are available in FSM set clauses:

SET @id = UUID_V4()
SET @ref = CUID()

Package tsqlruntime provides a runtime interpreter for T-SQL, enabling execution of dynamic SQL at runtime in Go applications.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearErrorContext

func ClearErrorContext()

ClearErrorContext clears the error context

func ContainsNextValueFor

func ContainsNextValueFor(expr string) (bool, error)

ContainsNextValueFor reports whether a set-clause expression string references NEXT VALUE FOR. The walk runtime uses this to decide whether a set clause must run inside the sequence-aware path.

func EvalGuard

func EvalGuard(e *Evaluator, expr string, vars map[string]interface{}, payload map[string]interface{}) (bool, error)

EvalGuard parses and evaluates a boolean guard expression. Returns true if the guard passes, false if it fails, and an error if the expression cannot be parsed or evaluated.

vars and payload are bound before evaluation; they do not persist between calls. Create a new Evaluator per walk step.

func EvalGuardWithQuery

func EvalGuardWithQuery(e *Evaluator, expr string, vars, payload, query map[string]interface{}) (bool, error)

EvalGuardWithQuery evaluates a guard with vars, payload, and transition pre-query result columns (bound under the "query." prefix) all in scope.

func EvalSet

func EvalSet(e *Evaluator, expr string, vars map[string]interface{}) (interface{}, error)

EvalSet parses and evaluates a set-clause expression and returns the result as a Go value suitable for storing back into machine variables.

vars is bound before evaluation. The expression should be an arithmetic or string expression (e.g. "@retries + 1", "UPPER(@status)").

func EvalSetWithSeq

func EvalSetWithSeq(e *Evaluator, expr string, vars map[string]interface{}) (interface{}, error)

EvalSetWithSeq evaluates a set-clause expression, resolving any NEXT VALUE FOR references via the installed incrementor before evaluation. If the expression contains no NEXT VALUE FOR it behaves exactly like EvalSet. If it contains NEXT VALUE FOR and no incrementor is installed, it returns an error.

func ForceTop1

func ForceTop1(query string) (string, error)

ForceTop1 parses a SELECT query, forces TOP 1 onto it (replacing any existing TOP), and returns the rewritten query text. It returns an error if the query does not parse or is not a single SELECT statement. ORDER BY, WHERE, and all other clauses are preserved; only the row-count bound is imposed.

func FromValue

func FromValue(v Value) interface{}

FromValue converts a runtime Value to a Go value

func ParseGuard

func ParseGuard(expr string) (ast.Expression, error)

ParseGuard parses a guard expression string and returns the AST node. Use this at FSM definition creation time to validate guard syntax without evaluating. Returns a non-nil error if the expression is syntactically invalid.

func SetErrorContext

func SetErrorContext(errNum int, msg string, line int, proc string, state int, severity int)

SetErrorContext updates the error context for error functions

Types

type DataType

type DataType int

DataType represents T-SQL data types

const (
	TypeUnknown DataType = iota
	// Integer types
	TypeBit
	TypeTinyInt
	TypeSmallInt
	TypeInt
	TypeBigInt
	// Exact numeric
	TypeDecimal
	TypeNumeric
	TypeMoney
	TypeSmallMoney
	// Approximate numeric
	TypeFloat
	TypeReal
	// Date/time
	TypeDate
	TypeTime
	TypeDateTime
	TypeDateTime2
	TypeSmallDateTime
	TypeDateTimeOffset
	// String
	TypeChar
	TypeVarChar
	TypeNChar
	TypeNVarChar
	TypeText
	TypeNText
	// Binary
	TypeBinary
	TypeVarBinary
	// Other
	TypeUniqueIdentifier
	TypeXML
	TypeTable
)

func ParseDataType

func ParseDataType(typeName string) (DataType, int, int, int)

ParseDataType parses a T-SQL type name into DataType with precision/scale/maxlen

func (DataType) IsDateTime

func (dt DataType) IsDateTime() bool

IsDateTime returns true if the type is a date/time type

func (DataType) IsInteger

func (dt DataType) IsInteger() bool

IsInteger returns true if the type is an integer type

func (DataType) IsNumeric

func (dt DataType) IsNumeric() bool

IsNumeric returns true if the type is numeric

func (DataType) IsString

func (dt DataType) IsString() bool

IsString returns true if the type is a string type

func (DataType) String

func (dt DataType) String() string

type Evaluator

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

Evaluator wraps ExpressionEvaluator with the xolu-specific API. Create one per FSM definition validation or per walk execution. Evaluators are not safe for concurrent use.

func New

func New() *Evaluator

New creates a new Evaluator with the built-in function registry seeded with the four stateless generators.

func (*Evaluator) BindPayload

func (e *Evaluator) BindPayload(payload map[string]interface{})

BindPayload binds walk payload fields into the evaluator under the "payload." prefix. A payload field "result" is accessible in expressions as `payload.result`. Only top-level string, number, and bool fields are bound; nested objects are skipped.

func (*Evaluator) BindQuery

func (e *Evaluator) BindQuery(cols map[string]interface{})

BindQuery binds transition pre-query result columns under the "query." prefix, so a guard or set clause can read query.<column>. Like BindPayload, only top-level scalar columns are bound.

func (*Evaluator) BindVars

func (e *Evaluator) BindVars(vars map[string]interface{})

BindVars binds machine variable values into the evaluator. The @ prefix is stripped from keys; `@retries` and `retries` both bind as "retries". Values are converted via ToValue.

func (*Evaluator) RegisterFunc

func (e *Evaluator) RegisterFunc(name string, fn func(args []Value) (Value, error))

RegisterFunc registers a custom function on this Evaluator. name is normalised to uppercase. Use this to register @SEQ, @GEN, or domain-specific functions needed in a specific FSM definition.

func (*Evaluator) SetSeqIncrementor

func (e *Evaluator) SetSeqIncrementor(fn SeqIncrementor)

SetSeqIncrementor installs the sequence incrementor used by EvalSetWithSeq. When nil (the default), a NEXT VALUE FOR in a set clause produces an error rather than silently evaluating to nil.

type ExclusivityResult

type ExclusivityResult struct {
	Exclusive bool
	Reason    string
	OverlapA  string
	OverlapB  string
}

ExclusivityResult is the recognizer's verdict.

func CheckExclusivity

func CheckExclusivity(guards []GuardExpr) ExclusivityResult

CheckExclusivity reports whether guards are provably pairwise mutually exclusive. Empty or single-guard sets are trivially exclusive.

type ExpressionEvaluator

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

ExpressionEvaluator evaluates T-SQL expressions at runtime

func NewExpressionEvaluator

func NewExpressionEvaluator() *ExpressionEvaluator

NewExpressionEvaluator creates a new expression evaluator

func (*ExpressionEvaluator) Evaluate

func (e *ExpressionEvaluator) Evaluate(expr ast.Expression) (Value, error)

Evaluate evaluates an AST expression and returns its value

func (*ExpressionEvaluator) GetVariable

func (e *ExpressionEvaluator) GetVariable(name string) (Value, bool)

GetVariable gets a variable value

func (*ExpressionEvaluator) SetVariable

func (e *ExpressionEvaluator) SetVariable(name string, value Value)

SetVariable sets a variable value

func (*ExpressionEvaluator) SetVariables

func (e *ExpressionEvaluator) SetVariables(vars map[string]interface{})

SetVariables sets multiple variables from a map

type Function

type Function func(args []Value) (Value, error)

Function is a T-SQL function implementation

type FunctionRegistry

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

FunctionRegistry holds all registered functions

func NewFunctionRegistry

func NewFunctionRegistry() *FunctionRegistry

NewFunctionRegistry creates a new function registry with built-in functions

func (*FunctionRegistry) Call

func (r *FunctionRegistry) Call(name string, args []Value) (Value, error)

Call invokes a function by name

func (*FunctionRegistry) Has

func (r *FunctionRegistry) Has(name string) bool

Has returns true if the function exists

func (*FunctionRegistry) Register

func (r *FunctionRegistry) Register(name string, fn Function)

Register adds a function to the registry

type GuardExpr

type GuardExpr struct {
	Source string
	AST    ast.Expression
}

GuardExpr pairs a guard's source text with its parsed AST.

type SeqIncrementor

type SeqIncrementor func(name string) (int64, error)

SeqIncrementor increments the named sequence and returns the new value. It is expected to run on the caller's transaction so the increment is atomic with the surrounding walk. A non-nil error aborts the set clause.

type Value

type Value struct {
	Type      DataType
	IsNull    bool
	Precision int // For decimal/numeric
	Scale     int // For decimal/numeric
	MaxLen    int // For string/binary types
	// contains filtered or unexported fields
}

Value represents a runtime T-SQL value with type information

func Cast

func Cast(v Value, targetType DataType, precision, scale, maxLen int) (Value, error)

Cast converts a value to the target type

func Convert

func Convert(v Value, targetType DataType, precision, scale, maxLen int, style int) (Value, error)

Convert converts a value to the target type with optional style

func NewBigInt

func NewBigInt(v int64) Value

NewBigInt creates a bigint value

func NewBinary

func NewBinary(v []byte) Value

NewBinary creates a binary value

func NewBit

func NewBit(v bool) Value

NewBit creates a bit value

func NewChar

func NewChar(v string, length int) Value

NewChar creates a char value (padded to length)

func NewDate

func NewDate(v time.Time) Value

NewDate creates a date value

func NewDateTime

func NewDateTime(v time.Time) Value

NewDateTime creates a datetime value

func NewDecimal

func NewDecimal(v decimal.Decimal, precision, scale int) Value

NewDecimal creates a decimal value

func NewDecimalFromString

func NewDecimalFromString(s string, precision, scale int) (Value, error)

NewDecimalFromString creates a decimal from a string

func NewFloat

func NewFloat(v float64) Value

NewFloat creates a float value

func NewInt

func NewInt(v int64) Value

NewInt creates an integer value

func NewMoney

func NewMoney(v decimal.Decimal) Value

NewMoney creates a money value

func NewNVarChar

func NewNVarChar(v string, maxLen int) Value

NewNVarChar creates an nvarchar value

func NewReal

func NewReal(v float32) Value

NewReal creates a real value

func NewSmallInt

func NewSmallInt(v int16) Value

NewSmallInt creates a smallint value

func NewTime

func NewTime(v time.Time) Value

NewTime creates a time value

func NewTinyInt

func NewTinyInt(v uint8) Value

NewTinyInt creates a tinyint value

func NewVarBinary

func NewVarBinary(v []byte, maxLen int) Value

NewVarBinary creates a new varbinary value

func NewVarChar

func NewVarChar(v string, maxLen int) Value

NewVarChar creates a varchar value

func Null

func Null(dt DataType) Value

Null returns a NULL value of the given type

func ToValue

func ToValue(v interface{}) Value

ToValue converts a Go value to a runtime Value

func (Value) Add

func (v Value) Add(other Value) Value

Add performs addition

func (Value) And

func (v Value) And(other Value) Value

And performs logical AND

func (Value) AsBool

func (v Value) AsBool() bool

AsBool returns the value as bool, with type coercion

func (Value) AsDecimal

func (v Value) AsDecimal() decimal.Decimal

AsDecimal returns the value as decimal.Decimal, with type coercion

func (Value) AsFloat

func (v Value) AsFloat() float64

AsFloat returns the value as float64, with type coercion

func (Value) AsInt

func (v Value) AsInt() int64

AsInt returns the value as int64, with type coercion

func (Value) AsString

func (v Value) AsString() string

AsString returns the value as string, with type coercion

func (Value) AsTime

func (v Value) AsTime() time.Time

AsTime returns the value as time.Time, with type coercion

func (Value) BitwiseAnd

func (v Value) BitwiseAnd(other Value) Value

BitwiseAnd performs bitwise AND

func (Value) BitwiseNot

func (v Value) BitwiseNot() Value

BitwiseNot performs bitwise NOT

func (Value) BitwiseOr

func (v Value) BitwiseOr(other Value) Value

BitwiseOr performs bitwise OR

func (Value) BitwiseXor

func (v Value) BitwiseXor(other Value) Value

BitwiseXor performs bitwise XOR

func (Value) Clone

func (v Value) Clone() Value

Clone creates a copy of the value

func (Value) Compare

func (v Value) Compare(other Value) int

Compare compares two values, returning -1, 0, or 1

func (Value) Div

func (v Value) Div(other Value) Value

Div performs division

func (Value) Equals

func (v Value) Equals(other Value) Value

Equals checks if two values are equal (handles NULL)

func (Value) GreaterThan

func (v Value) GreaterThan(other Value) Value

GreaterThan compares values

func (Value) GreaterThanOrEqual

func (v Value) GreaterThanOrEqual(other Value) Value

GreaterThanOrEqual compares values

func (Value) IsTruthy

func (v Value) IsTruthy() bool

IsTruthy returns true if the value is considered "true" in a boolean context

func (Value) LessThan

func (v Value) LessThan(other Value) Value

LessThan compares values

func (Value) LessThanOrEqual

func (v Value) LessThanOrEqual(other Value) Value

LessThanOrEqual compares values

func (Value) Mod

func (v Value) Mod(other Value) Value

Mod performs modulo

func (Value) Mul

func (v Value) Mul(other Value) Value

Mul performs multiplication

func (Value) Neg

func (v Value) Neg() Value

Neg negates the value

func (Value) Not

func (v Value) Not() Value

Not performs logical NOT

func (Value) NotEquals

func (v Value) NotEquals(other Value) Value

NotEquals checks if two values are not equal

func (Value) Or

func (v Value) Or(other Value) Value

Or performs logical OR

func (Value) Power

func (v Value) Power(exp Value) Value

Power raises v to the power of exp

func (Value) Sub

func (v Value) Sub(other Value) Value

Sub performs subtraction

func (Value) ToInterface

func (v Value) ToInterface() interface{}

ToInterface converts the Value to a Go interface{} for use with JSON/XML

Jump to

Keyboard shortcuts

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