Documentation ¶
Overview ¶
gosq is a parsing engine for a simplicity-focused, template-based SQL query builder for Go.
It provides a very simple syntax to inject arbitrary conditional query piece.
q, err := gosq.Compile(` SELECT products.* {{ [if] .IncludeReviews [then] ,json_agg(reviews) AS reviews }} FROM products {{ [if] .IncludeReviews [then] LEFT JOIN reviews ON reviews.product_id = products.id }} WHERE category = $1 OFFSET 100 LIMIT 10 `, map[string]interface{}{ IncludeReviews: true, })
Limitations:
- The predicate (expression between [if] and [then]) must be a one word: either true, false or a parameter that evaluates to a boolean. There's no support to evaluate an arbitrary predicate expression yet.
- gosq does not validate nor executes the query itself. The only thing it does is build the query in string out of a template.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Compile ¶
Compile receives a query template and a map of parameters, and replaces the expressions in the query template based on the values of the parameters.
"args" can either be a map of parameters (map[string]interface{}), or a custom struct.
The parameters given in "args" must be accessed by a preceeding dot (.) in the template.
The values of the parameters can be anything, but it will be evaluated as a string, using `fmt.Sprintf("%v", v)`.
The following are the supported syntax in the expressions:
- {{ [if] predicate [then] clause }}
- {{ [if] predicate [then] clause [else] clause }}
Recursive expressions are supported, as long as they're parts of a [then] or [else] clause. For example:
{{ [if] predicate [then] {{ [if] predicate [then] clause }} }}
If you need grammar for a more complex expression and you think it's a common use case, please file an issue on GitHub.
func Execute ¶ added in v1.1.0
Execute is similar to Compile, but instead uses the syntax from the text/template package. Indeed it simply uses text/template package internally, and supports all syntax provided by it, so use at your own risk/advantage. The if-else-then expression equivalent to the Compile function would be:
{{if predicate}} clause {{else}} clause {{end}}
Types ¶
This section is empty.