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([]string, 0, 4)
 args := make([]any, 0, 4)
 if q.Name != nil {
  conditions = append(conditions, "name = ?")
  args = append(args, *q.Name)
 }
 if q.NameIn != nil {
  phs := make([]string, 0, len(*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.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/CAKCiqKui0ioNrtN%3DnHdfiyWvvQz2dB5T27TKHryF5ev4kBTdOw%40mail.gmail.com.

Reply via email to