[go-nuts] I built gooogen to generate dynamic query methods

24 views
Skip to first unread message

Forb Yuan

unread,
Feb 23, 2026, 9:37:33 PM (15 hours ago) Feb 23
to golan...@googlegroups.com
Hi, all. Usually we need to write a lot of boilerplate code that builds dynamic queries through if statements. Conventional code generation methods can only generate equality conditions. I thought of solving this problem by adding a predicate suffix to fields, and created the tool gooogen. The usage is as follows:
//go:generate gooogen
type UserQuery struct {
 PageQuery
 Name    *string
 NameIn  *[]string
 ScoreGe *int
 ScoreLt *int
}

Run go generate will generate the following code:

func (q UserQuery) BuildConditions() ([]string, []any) {
 conditions := make([]string04)
 args := make([]any, 04)
 if q.Name != nil {
  conditions = append(conditions, "name = ?")
  args = append(args, *q.Name)
 }
 if q.NameIn != nil {
  phs := make([]string0len(*q.NameIn))
  for _, arg := range *q.NameIn {
   args = append(args, arg)
   phs = append(phs, "?")
  }
  conditions = append(conditions, "name IN ("+strings.Join(phs, ", ")+")")
 }
 if q.ScoreGe != nil {
  conditions = append(conditions, "score >= ?")
  args = append(args, *q.ScoreGe)
 }
 if q.ScoreLt != nil {
  conditions = append(conditions, "score < ?")
  args = append(args, *q.ScoreLt)
 }
 return conditions, args
}

Combining it with entity objects in the ORM can build complete query statements, thereby simplifying the development of dynamic queries.

GitHub: https://github.com/doytowin/goooqo

Feedback is welcome. 

Reply all
Reply to author
Forward
0 new messages