Simple SQL template for 2 way SQL.
Template is compatible with SQL.
Use /*%
and %*/
as delimiter instead of {{
and }}
for processing template.
SELECT *
FROM users
WHERE id IN /*% in "ids" %*/(1, 2)
AND name = /*% p "name" %*/'John Doe'
/*%- if get "onlyMale" %*/
AND sex = 'MALE'
/*%- end %*/
ORDER BY /*% out "order" %*/id
- func
param
orp
replace to placeholder by name. - func
in
deploy slice values to parentheses and placeholders. - func
time
returns current time and cache it, this func always same time in same template. - func
now
returns current time each calling. - func
escape
,prefix
,inffix
,suffix
replace to placeholder with escape forLIKE
keyword. - If you want to use value for building SQL only or embedding value to SQL directly, you must use
get
orout
func. This func check that value contains prohibited character(s) for avoiding SQL injection.out
is annotative, butget
is not annotative.
Prohibited characters are:- Single quotation
- Semi colon
- Line comment (--)
- Block comment (/* or */)
- If database driver that you use supports
sql.NamedArg
, you should callExecNamed
func.
// query is generated SQL from template.
// args are arguments for generated SQL.
query, args, err := sqlt.New(sqlt.Postgres).Exec(s, map[string]interface{}{
"ids": []int{1, 2, 3},
"order": "name DESC",
"onlyMale": false,
"name": "Alex",
})
rows, err := db.Query(query, args...)
TimeFunc
: For using customized time in template.Annotation
: Output meta data for debugging to rendered SQL.
SELECT *
FROM users
WHERE id IN ($1, $2, $3)
AND name = $4
ORDER BY name DESC
Currently there are also many drivers who do not support sql.NamedArg
.
In future, driver support sql.NamedArg
, you only need to change Exec
to ExecNamed
.
SELECT *
FROM users
WHERE id IN (:ids__1, :ids__2, :ids__3)
AND name = :name
ORDER BY name DESC
$ go get github.com/pinzolo/sqlt
Go 1.9 or later
- PostgreSQL
- MySQL
- Oracle
- SQL Server
- Fork (https://github.com/pinzolo/sqlt/fork)
- Create a feature branch
- Commit your changes
- Rebase your local changes against the master branch
- Run test suite with the
go test ./...
command and confirm that it passes - Run
gofmt -s
- Create a new Pull Request