From c0f895b1444cfc55a5f6989c9a0187a1e56be023 Mon Sep 17 00:00:00 2001 From: "junzhou.guo" Date: Mon, 13 Feb 2023 16:13:03 +0800 Subject: [PATCH] support fields linked with ops --- builder/builder.go | 20 ++++++++++++++++++-- builder/builder_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/builder/builder.go b/builder/builder.go index 773664e..25a7655 100644 --- a/builder/builder.go +++ b/builder/builder.go @@ -423,8 +423,7 @@ func splitKey(key string, val interface{}) (field string, operator string, err e } idx := strings.IndexByte(key, ' ') if idx == -1 { - field = key - operator = "=" + field, operator = splitKeyNoSpace(key) if reflect.ValueOf(val).Kind() == reflect.Slice { operator = "in" } @@ -436,6 +435,23 @@ func splitKey(key string, val interface{}) (field string, operator string, err e return } +var opCanLinkedWithField = []string{opNe1, opNe2, opGte, opLte, opEq, opGt, opLt} // 2 chars op first + +func splitKeyNoSpace(key string) (field string, operator string) { + field = key + operator = "=" + for _, op := range opCanLinkedWithField { + idx := strings.Index(key, op) + if idx != -1 { + field = key[:idx] + operator = key[idx:] + break + } + continue + } + return +} + func removeInnerSpace(operator string) string { n := len(operator) firstSpace := strings.IndexByte(operator, ' ') diff --git a/builder/builder_test.go b/builder/builder_test.go index 219e39e..98ebc42 100644 --- a/builder/builder_test.go +++ b/builder/builder_test.go @@ -598,6 +598,35 @@ func Test_BuildSelect(t *testing.T) { err: nil, }, }, + { + in: inStruct{ + table: "tb", + where: map[string]interface{}{ + "foo": "bar", + "foo1>=": "bar", + "foo2<=": "bar", + "foo3<>": "bar", + "foo4!=": "bar", + "foo5>": "bar", + "foo6<": "bar", + "foo7=": "bar", + "foo11 >=": "bar", + "foo12 <=": "bar", + "foo13 <>": "bar", + "foo14 !=": "bar", + "foo15 >": "bar", + "foo16 <": "bar", + "foo17 =": "bar", + "_orderby": " ", + }, + fields: nil, + }, + out: outStruct{ + cond: "SELECT * FROM tb WHERE (foo=? AND foo17=? AND foo7=? AND foo14!=? AND foo4!=? AND foo13!=? AND foo3!=? AND foo15>? AND foo5>? AND foo1>=? AND foo11>=? AND foo16