Documentation
¶
Overview ¶
Package cel2sql converts CEL (Common Expression Language) expressions to PostgreSQL SQL conditions.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Convert ¶
func Convert(ast *cel.Ast, opts ...ConvertOption) (string, error)
Convert converts a CEL AST to a PostgreSQL SQL WHERE clause condition. Options can be provided to configure the conversion behavior.
Example without options:
sql, err := cel2sql.Convert(ast)
Example with schema information for JSON/JSONB support:
sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas))
Types ¶
type ComprehensionInfo ¶
type ComprehensionInfo struct {
Type ComprehensionType
IterVar string
IndexVar string // for two-variable comprehensions
AccuVar string
HasFilter bool
IsTwoVar bool
Transform *exprpb.Expr // transform expression for map/transformList
Predicate *exprpb.Expr // predicate expression for filtering
Filter *exprpb.Expr // filter expression for map with filter
}
ComprehensionInfo holds metadata about a comprehension operation
type ComprehensionType ¶
type ComprehensionType int
ComprehensionType represents the type of comprehension operation
const ( ComprehensionAll ComprehensionType = iota // All elements satisfy condition ComprehensionExists // At least one element satisfies condition ComprehensionExistsOne // Exactly one element satisfies condition ComprehensionMap // Transform elements using expression ComprehensionFilter // Filter elements by predicate ComprehensionTransformList // Transform list elements ComprehensionTransformMap // Transform map entries ComprehensionTransformMapEntry // Transform map key-value pairs ComprehensionUnknown // Unrecognized comprehension pattern )
CEL comprehension types supported by cel2sql
func (ComprehensionType) String ¶
func (ct ComprehensionType) String() string
String returns a string representation of the comprehension type
type ConversionError ¶ added in v2.12.0
type ConversionError struct {
// UserMessage is the sanitized error message safe to display to end users
UserMessage string
// InternalDetails contains detailed information for logging and debugging
// This should NEVER be exposed to end users
InternalDetails string
// WrappedErr is the underlying error, if any
WrappedErr error
}
ConversionError represents an error that occurred during CEL to SQL conversion. It provides a sanitized user-facing message while preserving detailed information for logging and debugging. This prevents information disclosure through error messages (CWE-209: Information Exposure Through Error Message).
func (*ConversionError) Error ¶ added in v2.12.0
func (e *ConversionError) Error() string
Error returns the user-facing error message. This is what gets displayed when the error is returned to callers.
func (*ConversionError) Internal ¶ added in v2.12.0
func (e *ConversionError) Internal() string
Internal returns the full internal details for logging purposes. This should only be used with structured logging, never displayed to users.
func (*ConversionError) Unwrap ¶ added in v2.12.0
func (e *ConversionError) Unwrap() error
Unwrap returns the wrapped error for use with errors.Is and errors.As
type ConvertOption ¶ added in v2.11.0
type ConvertOption func(*convertOptions)
ConvertOption is a functional option for configuring the Convert function.
func WithContext ¶ added in v2.11.0
func WithContext(ctx context.Context) ConvertOption
WithContext provides a context for cancellation and timeout support. If not provided, operations will run without cancellation checks. This allows long-running conversions to be cancelled and enables timeout protection.
Example with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() sql, err := cel2sql.Convert(ast, cel2sql.WithContext(ctx))
Example with cancellation:
ctx, cancel := context.WithCancel(context.Background()) defer cancel() sql, err := cel2sql.Convert(ast, cel2sql.WithContext(ctx), cel2sql.WithSchemas(schemas))
func WithLogger ¶ added in v2.11.0
func WithLogger(logger *slog.Logger) ConvertOption
WithLogger provides a logger for observability and debugging. If not provided, logging is disabled with zero overhead using slog.DiscardHandler.
The logger enables visibility into:
- JSON path detection decisions (table, field, operator selection)
- Comprehension type identification (all, exists, filter, map)
- Schema lookups (hits/misses, field types)
- Performance metrics (conversion duration)
- Regex pattern transformations (RE2 to POSIX)
- Operator mapping decisions
- Error contexts with full details
Example with JSON output:
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
sql, err := cel2sql.Convert(ast, cel2sql.WithLogger(logger))
Example with text output:
logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas), cel2sql.WithLogger(logger))
func WithMaxDepth ¶ added in v2.12.0
func WithMaxDepth(maxDepth int) ConvertOption
WithMaxDepth sets the maximum recursion depth for expression traversal. If not provided, defaultMaxRecursionDepth (100) is used. This protects against stack overflow from deeply nested expressions (CWE-674).
Example with custom depth:
sql, err := cel2sql.Convert(ast, cel2sql.WithMaxDepth(150))
Example with multiple options:
sql, err := cel2sql.Convert(ast,
cel2sql.WithMaxDepth(50),
cel2sql.WithContext(ctx),
cel2sql.WithSchemas(schemas))
func WithMaxOutputLength ¶ added in v2.12.0
func WithMaxOutputLength(maxLength int) ConvertOption
WithMaxOutputLength sets the maximum length of generated SQL output. If not provided, defaultMaxSQLOutputLength (50000) is used. This protects against resource exhaustion from extremely large SQL queries (CWE-400).
Example with custom output length limit:
sql, err := cel2sql.Convert(ast, cel2sql.WithMaxOutputLength(100000))
Example with multiple options:
sql, err := cel2sql.Convert(ast,
cel2sql.WithMaxOutputLength(25000),
cel2sql.WithMaxDepth(50),
cel2sql.WithContext(ctx))
func WithSchemas ¶ added in v2.11.0
func WithSchemas(schemas map[string]pg.Schema) ConvertOption
WithSchemas provides schema information for proper JSON/JSONB field handling. This option is required for correct SQL generation when using JSON/JSONB fields.
Example:
schemas := provider.GetSchemas() sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas))
type Result ¶ added in v2.12.0
type Result struct {
SQL string // The generated SQL WHERE clause with placeholders
Parameters []interface{} // Parameter values in order ($1, $2, etc.)
}
Result represents the output of a CEL to SQL conversion with parameterized queries. It contains the SQL string with placeholders ($1, $2, etc.) and the corresponding parameter values.
func ConvertParameterized ¶ added in v2.12.0
func ConvertParameterized(ast *cel.Ast, opts ...ConvertOption) (*Result, error)
ConvertParameterized converts a CEL AST to a parameterized PostgreSQL SQL WHERE clause. Returns both the SQL string with placeholders ($1, $2, etc.) and the parameter values. This enables query plan caching and provides additional SQL injection protection.
Constants that are parameterized:
- String literals: 'John' → $1
- Numeric literals: 42, 3.14 → $1, $2
- Byte literals: b"data" → $1
Constants kept inline (for query plan optimization):
- TRUE, FALSE (boolean constants)
- NULL
Example:
result, err := cel2sql.ConvertParameterized(ast,
cel2sql.WithSchemas(schemas),
cel2sql.WithContext(ctx))
// result.SQL: "user.age = $1 AND user.name = $2"
// result.Parameters: []interface{}{18, "John"}
// Execute with database/sql
rows, err := db.Query("SELECT * FROM users WHERE "+result.SQL, result.Parameters...)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Package main demonstrates basic usage of cel2sql with a predefined schema.
|
Package main demonstrates basic usage of cel2sql with a predefined schema. |
|
comprehensions
command
Package main demonstrates CEL comprehensions support in cel2sql with PostgreSQL integration.
|
Package main demonstrates CEL comprehensions support in cel2sql with PostgreSQL integration. |
|
context
command
Package main demonstrates context usage with cel2sql for cancellation and timeout support.
|
Package main demonstrates context usage with cel2sql for cancellation and timeout support. |
|
load_table_schema
command
Package main demonstrates loading table schema dynamically from PostgreSQL.
|
Package main demonstrates loading table schema dynamically from PostgreSQL. |
|
logging
command
Package main demonstrates cel2sql structured logging with log/slog.
|
Package main demonstrates cel2sql structured logging with log/slog. |
|
parameterized
command
Package main demonstrates parameterized query support in cel2sql.
|
Package main demonstrates parameterized query support in cel2sql. |
|
Package pg provides PostgreSQL type provider for CEL type system integration.
|
Package pg provides PostgreSQL type provider for CEL type system integration. |
|
Package sqltypes provides custom SQL type definitions for CEL (Date, Time, DateTime).
|
Package sqltypes provides custom SQL type definitions for CEL (Date, Time, DateTime). |
|
Package test provides PostgreSQL schema definitions for testing.
|
Package test provides PostgreSQL schema definitions for testing. |