-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
48 lines (41 loc) · 1.32 KB
/
Copy pathmain.go
File metadata and controls
48 lines (41 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Package main demonstrates basic usage of cel2sql with a predefined schema.
package main
import (
"fmt"
"log"
"github.com/google/cel-go/cel"
"github.com/spandigital/cel2sql/v3"
"github.com/spandigital/cel2sql/v3/pg"
)
func main() {
// Define a PostgreSQL table schema
employeeSchema := pg.NewSchema([]pg.FieldSchema{
{Name: "name", Type: "text", Repeated: false},
{Name: "age", Type: "integer", Repeated: false},
{Name: "department", Type: "text", Repeated: false},
{Name: "hired_at", Type: "timestamp with time zone", Repeated: false},
{Name: "active", Type: "boolean", Repeated: false},
})
// Create CEL environment with PostgreSQL type provider
env, err := cel.NewEnv(
cel.CustomTypeProvider(pg.NewTypeProvider(map[string]pg.Schema{
"Employee": employeeSchema,
})),
cel.Variable("employee", cel.ObjectType("Employee")),
)
if err != nil {
log.Fatal(err)
}
// Compile a CEL expression
ast, issues := env.Compile(`employee.name == "John Doe" && employee.age >= 25 && employee.active`)
if issues != nil && issues.Err() != nil {
log.Fatal(issues.Err())
}
// Convert to SQL
sqlCondition, err := cel2sql.Convert(ast)
if err != nil {
log.Fatal(err)
}
fmt.Println("CEL Expression: employee.name == \"John Doe\" && employee.age >= 25 && employee.active")
fmt.Println("PostgreSQL SQL:", sqlCondition)
}