Skip to content

Instantly share code, notes, and snippets.

func GenerateQuery(params map[string]string) string {
where := "where 1=1"
if status, ok := params["status"]; ok {
where += " AND status='" + status + "'"
}
if phone_number, ok := params["phone_number"]; ok {
where += " AND phone_number='" + phone_number + "'"
}
@paragtokopedia
paragtokopedia / dqb.go
Last active July 13, 2018 05:59
Generating Dynamic Queries using DQB
func GenerateQuery(queryParams QueryParams) (string) {
var dqb DynamicQueryBuilder
query = dqb.And(
dqb.NewExp("status", "=", queryParams["status"]),
dqb.NewExp("phone_number", "=", queryParams["phone_number"]),
dqb.NewExp("email", "=", queryParams["email"]),
dqb.NewExp("created_at", ">=", queryParams["application_start_date"]), //if empty it will not be added in where clause
dqb.NewExp("created_at", "<=", queryParams["application_end_date"]),
).Limit(0,10).BindSql("select * from application")
return query
@paragtokopedia
paragtokopedia / example_dynamic_query.go
Last active July 13, 2018 06:21
Another complex query example
//select * from application a where a.created_at >= '2018-01-01' AND a.created_at <= '2019-01-01' AND a.id >=0 AND (a.status = 'some_status' OR a.id =2 )
func GenerateQuery(ctx context.Context, queryParams QueryParams) (query string) {
var dqb DynamicQueryBuilder
query = dqb.And(
dqb.NewExp("a.created_at", ">=", queryParams["start_date"]+" "+queryParams["start_time"]), //if empty it will not be added in where clause
dqb.NewExp("a.created_at", "<=", queryParams["end_date"]+" "+queryParams["end_time"]),
"a.id >= 0",
"a.status IN ('pending','complete','initiated')",
dqb.OR(
@paragtokopedia
paragtokopedia / query_builder.go
Last active January 6, 2024 18:37
Query Builder
package query_builder
import (
"strings"
"strconv"
"html/template"
"fmt"
)
type DynamicQueryBuilder string