I Built Gooogen to generate dynamic query methods

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.

Feedback is welcome.

GitHub: GitHub - doytowin/goooqo: GoooQo is a database access framework implemented in Go, based on OQM technique.