Created
October 18, 2021 10:53
-
-
Save watain666/e4bee68c768d3a0314b52beec5d3d9ff to your computer and use it in GitHub Desktop.
orm where builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
func main() { | |
fmt.Println("Hello, playground") | |
TestWhereBuild() | |
} | |
type NullType byte | |
const ( | |
_ NullType = iota | |
// IsNull the same as `is null` | |
IsNull | |
// IsNotNull the same as `is not null` | |
IsNotNull | |
) | |
func TestWhereBuild() { | |
cond, vals, err := whereBuild(map[string]interface{}{ | |
"name =": "jinzhu", | |
"age in": []int{20, 19, 18}, | |
"age >": "19", | |
}) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(cond) | |
fmt.Println(vals) | |
//db.Where(cond, vals...).Find(&users) | |
} | |
// sql build where | |
func whereBuild(where map[string]interface{}) (whereSQL string, vals []interface{}, err error) { | |
for k, v := range where { | |
ks := strings.Split(k, " ") | |
if len(ks) > 2 { | |
return "", nil, fmt.Errorf("Error in query condition: %s. ", k) | |
} | |
if whereSQL != "" { | |
whereSQL += " AND " | |
} | |
fmt.Println(strings.Join(ks, ",")) | |
switch len(ks) { | |
case 1: | |
//fmt.Println(reflect.TypeOf(v)) | |
switch v := v.(type) { | |
case NullType: | |
fmt.Println() | |
if v == IsNotNull { | |
whereSQL += fmt.Sprint(k, " IS NOT NULL") | |
} else { | |
whereSQL += fmt.Sprint(k, " IS NULL") | |
} | |
default: | |
whereSQL += fmt.Sprint(k, "=?") | |
vals = append(vals, v) | |
} | |
break | |
case 2: | |
k = ks[0] | |
switch ks[1] { | |
case "=": | |
whereSQL += fmt.Sprint(k, "=?") | |
vals = append(vals, v) | |
break | |
case ">": | |
whereSQL += fmt.Sprint(k, ">?") | |
vals = append(vals, v) | |
break | |
case ">=": | |
whereSQL += fmt.Sprint(k, ">=?") | |
vals = append(vals, v) | |
break | |
case "<": | |
whereSQL += fmt.Sprint(k, "<?") | |
vals = append(vals, v) | |
break | |
case "<=": | |
whereSQL += fmt.Sprint(k, "<=?") | |
vals = append(vals, v) | |
break | |
case "!=": | |
whereSQL += fmt.Sprint(k, "!=?") | |
vals = append(vals, v) | |
break | |
case "<>": | |
whereSQL += fmt.Sprint(k, "!=?") | |
vals = append(vals, v) | |
break | |
case "in": | |
whereSQL += fmt.Sprint("k", "in (?)") | |
vals = append(vals, v) | |
break | |
case "like": | |
whereSQL += fmt.Sprint("k", "like ?") | |
vals = append(vals, v) | |
} | |
break | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment