github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/query_gen/utils_test.go (about) 1 package qgen 2 3 import ( 4 "strings" 5 "testing" 6 ) 7 8 type MT struct { 9 Type int 10 Contents string 11 } 12 13 func expectTokens(t *testing.T, whs []DBWhere, tokens ...MT) { 14 i := 0 15 for _, wh := range whs { 16 for _, expr := range wh.Expr { 17 if expr.Type != tokens[i].Type || expr.Contents != tokens[i].Contents { 18 t.Fatalf("token mismatch: %+v - %+v\n", expr, tokens[i]) 19 } 20 i++ 21 } 22 } 23 } 24 25 func TestProcessWhere(t *testing.T) { 26 whs := processWhere("uid = ?") 27 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenSub, "?"}) 28 whs = processWhere("uid = 1") 29 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenNumber, "1"}) 30 whs = processWhere("uid = 0") 31 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenNumber, "0"}) 32 whs = processWhere("uid = '1'") 33 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, "1"}) 34 whs = processWhere("uid = 't'") 35 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, "t"}) 36 whs = processWhere("uid = ''") 37 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, ""}) 38 whs = processWhere("uid = '") 39 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, ""}) 40 41 whs = processWhere("uid=?") 42 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenSub, "?"}) 43 whs = processWhere("uid=1") 44 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenNumber, "1"}) 45 whs = processWhere("uid=0") 46 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenNumber, "0"}) 47 whs = processWhere("uid=20") 48 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenNumber, "20"}) 49 whs = processWhere("uid=uid+1") 50 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenColumn, "uid"}, MT{TokenOp, "+"}, MT{TokenNumber, "1"}) 51 whs = processWhere("uid='1'") 52 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, "1"}) 53 whs = processWhere("uid='t'") 54 expectTokens(t, whs, MT{TokenColumn, "uid"}, MT{TokenOp, "="}, MT{TokenString, "t"}) 55 56 whs = processWhere("uid") 57 expectTokens(t, whs, MT{TokenColumn, "uid"}) 58 } 59 60 func TestMySQLBuildWhere(t *testing.T) { 61 a := &MysqlAdapter{Name: "mysql", Buffer: make(map[string]DBStmt)} 62 reap := func(wh, ex string) { 63 sb := &strings.Builder{} 64 a.buildWhere(wh, sb) 65 res := sb.String() 66 if res != ex { 67 t.Fatalf("build where mismatch: '%+v' - '%+v'\n", ex, res) 68 } 69 } 70 reap("uid = 0", " WHERE `uid`= 0 ") 71 reap("uid = '0'", " WHERE `uid`= '0'") 72 reap("uid=0", " WHERE `uid`= 0 ") 73 }