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/sqlTemplate
We 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(namespace string, templateName string) (QueryTemplate, error)
// ParseWithValuesFromMap parses a sql template with values from a map and returns the 'QueryTemplate'
ParseWithValuesFromMap(namespace string, templateName string, parameters map[string]interface{}) (QueryTemplate, error)
// ParseWithValuesFromStruct parses a sql template with values from a struct and returns the 'QueryTemplate'
ParseWithValuesFromStruct(namespace string, templateName string, parameters interface{}) (QueryTemplate, error)
// Register registers a new namespace by template filesystem and extension
Register(namespace string, filesystem fs.FS, extensions string) error
//go:embed queries/users/*.tsql
var fs embed.FS
sqlt := 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 ./pkg
For 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.