add is null and is not null feature like gorm in mongodb, use mongodb's exist

This commit is contained in:
soluty 2025-06-23 16:45:04 +08:00
parent 32b1142d38
commit d2f4a82b16
1 changed files with 34 additions and 20 deletions

View File

@ -37,6 +37,10 @@ const (
In = "in" In = "in"
// NotIn exclude // NotIn exclude
NotIn = "nin" NotIn = "nin"
// IsNull is null
IsNull = "isnull"
// IsNotNull is not null
IsNotNull = "isnotnull"
// AND logic and // AND logic and
AND string = "and" //nolint AND string = "and" //nolint
@ -49,23 +53,27 @@ const (
) )
var expMap = map[string]string{ var expMap = map[string]string{
Eq: eqSymbol, Eq: eqSymbol,
eqSymbol: eqSymbol, eqSymbol: eqSymbol,
Neq: neqSymbol, Neq: neqSymbol,
neqSymbol: neqSymbol, neqSymbol: neqSymbol,
Gt: gtSymbol, Gt: gtSymbol,
gtSymbol: gtSymbol, gtSymbol: gtSymbol,
Gte: gteSymbol, Gte: gteSymbol,
gteSymbol: gteSymbol, gteSymbol: gteSymbol,
Lt: ltSymbol, Lt: ltSymbol,
ltSymbol: ltSymbol, ltSymbol: ltSymbol,
Lte: lteSymbol, Lte: lteSymbol,
lteSymbol: lteSymbol, lteSymbol: lteSymbol,
Like: Like, Like: Like,
In: In, In: In,
NotIn: NotIn, NotIn: NotIn,
"notin": NotIn, "notin": NotIn,
"not in": NotIn, "not in": NotIn,
IsNull: IsNull,
IsNotNull: IsNotNull,
"is null": IsNull,
"is not null": IsNotNull,
} }
var logicMap = map[string]string{ var logicMap = map[string]string{
@ -207,7 +215,7 @@ func (c *Column) convertValue() error {
if v, ok := expMap[strings.ToLower(c.Exp)]; ok { //nolint if v, ok := expMap[strings.ToLower(c.Exp)]; ok { //nolint
c.Exp = v c.Exp = v
switch c.Exp { switch c.Exp {
//case eqSymbol: // case eqSymbol:
case neqSymbol: case neqSymbol:
c.Value = bson.M{"$ne": c.Value} c.Value = bson.M{"$ne": c.Value}
case gtSymbol: case gtSymbol:
@ -218,6 +226,10 @@ func (c *Column) convertValue() error {
c.Value = bson.M{"$lt": c.Value} c.Value = bson.M{"$lt": c.Value}
case lteSymbol: case lteSymbol:
c.Value = bson.M{"$lte": c.Value} c.Value = bson.M{"$lte": c.Value}
case IsNull:
c.Value = bson.M{"$exist": false}
case IsNotNull:
c.Value = bson.M{"$exist": true}
case Like: case Like:
escapedValue := regexp.QuoteMeta(fmt.Sprintf("%v", c.Value)) escapedValue := regexp.QuoteMeta(fmt.Sprintf("%v", c.Value))
c.Value = bson.M{"$regex": escapedValue, "$options": "i"} c.Value = bson.M{"$regex": escapedValue, "$options": "i"}
@ -312,11 +324,13 @@ func (p *Params) ConvertToMongoFilter(opts ...RulerOption) (bson.M, error) {
if p.Columns[0].Logic == AND { if p.Columns[0].Logic == AND {
filter = bson.M{"$and": []bson.M{ filter = bson.M{"$and": []bson.M{
{p.Columns[0].Name: p.Columns[0].Value}, {p.Columns[0].Name: p.Columns[0].Value},
{p.Columns[1].Name: p.Columns[1].Value}}} {p.Columns[1].Name: p.Columns[1].Value},
}}
} else { } else {
filter = bson.M{"$or": []bson.M{ filter = bson.M{"$or": []bson.M{
{p.Columns[0].Name: p.Columns[0].Value}, {p.Columns[0].Name: p.Columns[0].Value},
{p.Columns[1].Name: p.Columns[1].Value}}} {p.Columns[1].Name: p.Columns[1].Value},
}}
} }
return filter, nil return filter, nil