A simple template engine for writing dynamic SQL queries.
Sometimes it can be hard to write comprehensible SQL queries with tools like SQL builders (squirrel or dbr), specially dynamic queries with optional statements and joins. It can be hard to see the overall cohesive structure of the queries, and the primary goal.
The main motivation of this library is to separate the SQL queries from the Go code, and to improve the readability of complex dynamic queries.
Check out the API Documentation http://godoc.org/github.com/NicklasWallgren/sqlTemplate
The library can be installed through go get
go get github.com/NicklasWallgren/sqlTemplateWe support the latest major Go version, which are 1.19 at the moment.
- Separates SQL and Go code.
- Keeps the templated query as close as possible to the actual SQL query.
- Extensible template language with support for https://github.com/Masterminds/sprig
- No third party dependencies
- Support for embedded filesystem
// Parse parses a sql template and returns the 'QueryTemplate'Parse(namespacestring, templateNamestring) (QueryTemplate, error)
// ParseWithValuesFromMap parses a sql template with values from a map and returns the 'QueryTemplate'ParseWithValuesFromMap(namespacestring, templateNamestring, parametersmap[string]interface{}) (QueryTemplate, error)
// ParseWithValuesFromStruct parses a sql template with values from a struct and returns the 'QueryTemplate'ParseWithValuesFromStruct(namespacestring, templateNamestring, parametersinterface{}) (QueryTemplate, error)
// Register registers a new namespace by template filesystem and extensionRegister(namespacestring, filesystemfs.FS, extensionsstring) error//go:embed queries/users/*.tsqlvarfs embed.FSsqlt:=sqlTemplate.NewQueryTemplateEngine()
sqlt.Register("users", fs, ".tsql");
criteria:=map[string]interface{}{"Name": "Bill", "Order": "id"}
tmpl, _:=sqlt.ParseWithValuesFromMap("users", "findByName", criteria)
sql.QueryRowContext(context.Background(), tmpl.GetQuery(), tmpl.GetParams())
fmt.Printf("query %v\n", tmpl.GetQuery())
fmt.Printf("query parameters %v\n", tmpl.GetParams())-- File ./queries/users/users.tsql
{{define "findByName"}}
SELECT*FROM users
WHERE name={{bind .Name}}
{{if .Order}}ORDER BY {{.Order}}{{end}}
{{end}}go test -v -race ./pkgFor benchmark :
go test ./pkg -bench=.We use GitHub Actions to make sure the codebase is consistent
(golangci-lint run) and continuously tested (go test -v -race ./pkg). We try to keep comments at a maximum of 120 characters of
length and code at 120.
If you find any problems or have suggestions about this library, please submit an issue. Moreover, any pull request, code review and feedback are welcome.