93 lines
2.1 KiB
Go
93 lines
2.1 KiB
Go
package utpl
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gitea.1216.top/lxy/u-tpl/internal"
|
|
)
|
|
|
|
type Result struct {
|
|
SQL string
|
|
Args []any
|
|
}
|
|
|
|
type Template struct {
|
|
name string
|
|
engine *Engine
|
|
nodes []internal.Node
|
|
blocks map[string][]internal.Node
|
|
hasBlocks bool
|
|
namespace string
|
|
}
|
|
|
|
func (t *Template) Execute(vars map[string]any) (*Result, error) {
|
|
if t.hasBlocks {
|
|
return nil, &ExecError{
|
|
Pos: Position{},
|
|
Message: fmt.Sprintf("template %q has named blocks, use ExecuteBlock instead", t.name),
|
|
}
|
|
}
|
|
return t.executeNodes(t.nodes, vars)
|
|
}
|
|
|
|
func (t *Template) ExecuteBlock(blockName string, vars map[string]any) (*Result, error) {
|
|
nodes, ok := t.blocks[blockName]
|
|
if !ok {
|
|
if t.namespace != "" {
|
|
nodes, ok = t.blocks[t.namespace+"."+blockName]
|
|
}
|
|
}
|
|
if !ok {
|
|
return nil, &ExecError{
|
|
Pos: Position{},
|
|
Message: fmt.Sprintf("block %q not found in template %q", blockName, t.name),
|
|
}
|
|
}
|
|
return t.executeNodes(nodes, vars)
|
|
}
|
|
|
|
func (t *Template) ExecuteString(vars map[string]any) (string, error) {
|
|
result, err := t.Execute(vars)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return result.SQL, nil
|
|
}
|
|
|
|
func (t *Template) ExecuteBlockString(blockName string, vars map[string]any) (string, error) {
|
|
result, err := t.ExecuteBlock(blockName, vars)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return result.SQL, nil
|
|
}
|
|
|
|
func (t *Template) executeNodes(nodes []internal.Node, vars map[string]any) (*Result, error) {
|
|
executor := internal.NewExecutor(t.engine.style, t.engine.rawPolicy, t.engine.strict, t.blocks)
|
|
result, err := executor.Execute(nodes, vars)
|
|
if err != nil {
|
|
return nil, wrapExecError(err)
|
|
}
|
|
return &Result{SQL: result.SQL, Args: result.Args}, nil
|
|
}
|
|
|
|
func wrapExecError(err error) error {
|
|
var execErr *ExecError
|
|
if errors.As(err, &execErr) {
|
|
return err
|
|
}
|
|
var unsafeErr *UnsafeRawError
|
|
if errors.As(err, &unsafeErr) {
|
|
return err
|
|
}
|
|
var posErr *internal.PosError
|
|
if errors.As(err, &posErr) {
|
|
return &ExecError{
|
|
Pos: Position{Line: posErr.Line, Column: posErr.Col},
|
|
Message: err.Error(),
|
|
}
|
|
}
|
|
return &ExecError{Message: err.Error()}
|
|
}
|