Annotations are comments at interface’s methods, Gen will parse them and generate the query API for the applied structs.
Gen provies some conventions for dynamic conditionally SQL support, let us introduce them from three aspects:
- Returning Results
- Template Placeholder
- Template Expression
Returning Results
Gen allows to configure returning result type, it supports following four basic types for now
Option | Description |
---|---|
gen.T | returns struct |
gen.M | returns map |
gen.RowsAffected | returns rowsAffected returned from database (type: int64) |
error | returns error if any |
e.g:
type Querier interface { |
These basic types can be combined with other symbols like *
, []
, for example:
type Querier interface { |
Template Placeholder
Gen provides some placeholders to generate dynamic & safe SQL
Name | Description |
---|---|
@@table |
escaped & quoted table name |
@@<name> |
escaped & quoted table/column name from params |
@<name> |
SQL query params from params |
e.g:
type Filter interface { |
After generate the code, you can use it like this in your application.
import "your_project/query" |
Template Expression
Gen provides powerful expressions support for dynamic conditional SQL, currently support following expressions:
if/else
where
set
for
if/else
The if/else
expression allows to use golang syntax as condition, it can be written like:
For example:
type Querier interface { |
A more complicated case:
type Querier interface { |
How it can be used:
query.User.QueryWith(&User{Name: "zhangqiang"}) |
where
The where
expression make you write the WHERE
clause for the SQL query easier, let take a simple case as example:
type Querier interface { |
With the generated code, you can use it like:
query.User.Query(10) |
Here is another complicated case, in this case, you will learn the WHERE
clause only be inserted if there are any children expressions matched and it can smartly trim uncessary and
, or
, xor
, ,
inside the where
clause.
type Querier interface { |
The generated code can be used like:
var ( |
set
The set
expression used to generate the SET
clause for the SQL query, it will trim uncessary ,
automatically, for example:
// UPDATE @@table |
The generated code can be used like:
query.User.Update(User{Name: "jinzhu", Age: 18}, 10) |
for
The for
expression iterates over a slice to generate the SQL, let’s explain by example
// SELECT * FROM @@table |
Usage:
query.User.Filter([]User{ |