跳至内容

sqltmplx 示例

sqltmplx 示例

这一页汇总了 examples/sqltmplx 下的可运行程序,并说明它们分别覆盖哪些 API 场景。

本地运行

examples/sqltmplx 模块目录下执行:

cd examples/sqltmplx
go run ./basic
go run ./postgres
go run ./sqlite_update
go run ./precompile

示例矩阵

示例重点目录
basicMySQL 方言、注册式 validator 选择、map 参数examples/sqltmplx/basic
postgresPostgreSQL bind 变量、结构体 tag 绑定、parser 校验examples/sqltmplx/postgres
sqlite_update动态 set 语句清理examples/sqltmplx/sqlite_update
precompileCompile() 一次,多次渲染examples/sqltmplx/precompile

示例:动态 WHERE

engine := sqltmplx.New(
    postgres.New(),
    sqltmplx.WithValidator(validate.NewSQLParser(postgres.New())),
)

bound, err := engine.Render(tpl, Query{
    Tenant: "acme",
    Name:   "alice",
    IDs:    []int{1, 2, 3},
})
if err != nil {
    panic(err)
}

示例:动态 SET

engine := sqltmplx.New(sqlite.New())

bound, err := engine.Render(tpl, UpdateCommand{
    ID:     42,
    Name:   "alice",
    Status: "active",
})
if err != nil {
    panic(err)
}

示例:模板复用

engine := sqltmplx.New(mysql.New())
tpl, err := engine.Compile(queryText)
if err != nil {
    panic(err)
}

bound1, _ := tpl.Render(map[string]any{"Tenant": "acme", "Status": "PAID"})
bound2, _ := tpl.Render(map[string]any{"Tenant": "acme", "Status": "SHIPPED"})