2021-01-19 12:26:26 +00:00
|
|
|
package mongo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-01-19 12:35:54 +00:00
|
|
|
"strings"
|
2021-01-19 12:26:26 +00:00
|
|
|
|
|
|
|
"github.com/sunboyy/repogen/internal/spec"
|
|
|
|
)
|
|
|
|
|
2021-01-19 12:35:54 +00:00
|
|
|
type querySpec struct {
|
|
|
|
Operator spec.Operator
|
|
|
|
Predicates []predicate
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q querySpec) Code() string {
|
|
|
|
var predicateCodes []string
|
2021-01-24 08:31:21 +00:00
|
|
|
var argIndex int
|
|
|
|
for _, predicate := range q.Predicates {
|
|
|
|
predicateCodes = append(predicateCodes, predicate.Code(argIndex))
|
|
|
|
argIndex += predicate.Comparator.NumberOfArguments()
|
2021-01-19 12:35:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var lines []string
|
|
|
|
switch q.Operator {
|
|
|
|
case spec.OperatorOr:
|
|
|
|
lines = append(lines, ` "$or": []bson.M{`)
|
|
|
|
for _, predicateCode := range predicateCodes {
|
|
|
|
lines = append(lines, fmt.Sprintf(` {%s},`, predicateCode))
|
|
|
|
}
|
|
|
|
lines = append(lines, ` },`)
|
|
|
|
default:
|
|
|
|
for _, predicateCode := range predicateCodes {
|
|
|
|
lines = append(lines, fmt.Sprintf(` %s,`, predicateCode))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return strings.Join(lines, "\n")
|
|
|
|
}
|
|
|
|
|
2021-01-19 12:26:26 +00:00
|
|
|
type predicate struct {
|
2021-01-19 12:35:54 +00:00
|
|
|
Field string
|
|
|
|
Comparator spec.Comparator
|
2021-01-19 12:26:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p predicate) Code(argIndex int) string {
|
2021-01-19 12:35:54 +00:00
|
|
|
switch p.Comparator {
|
|
|
|
case spec.ComparatorEqual:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": arg%d`, p.Field, argIndex)
|
2021-01-19 12:35:54 +00:00
|
|
|
case spec.ComparatorNot:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$ne": arg%d}`, p.Field, argIndex)
|
2021-01-19 12:35:54 +00:00
|
|
|
case spec.ComparatorLessThan:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$lt": arg%d}`, p.Field, argIndex)
|
2021-01-19 12:35:54 +00:00
|
|
|
case spec.ComparatorLessThanEqual:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$lte": arg%d}`, p.Field, argIndex)
|
2021-01-19 12:35:54 +00:00
|
|
|
case spec.ComparatorGreaterThan:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$gt": arg%d}`, p.Field, argIndex)
|
2021-01-19 12:35:54 +00:00
|
|
|
case spec.ComparatorGreaterThanEqual:
|
2021-01-19 12:26:26 +00:00
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$gte": arg%d}`, p.Field, argIndex)
|
2021-01-24 08:31:21 +00:00
|
|
|
case spec.ComparatorBetween:
|
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$gte": arg%d, "$lte": arg%d}`, p.Field, argIndex, argIndex+1)
|
2021-01-22 02:56:30 +00:00
|
|
|
case spec.ComparatorIn:
|
|
|
|
return fmt.Sprintf(`"%s": bson.M{"$in": arg%d}`, p.Field, argIndex)
|
2021-01-19 12:26:26 +00:00
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|