From 63f33d1d8c6d875d3807d87d86ba218252dbb410 Mon Sep 17 00:00:00 2001 From: John Date: Wed, 15 Apr 2020 18:02:32 +0800 Subject: [PATCH] improve package gdb supporting gtime.Time parameter for Where condition --- .example/other/test.go | 19 +++++++++++---- database/gdb/gdb_func.go | 27 +++++++++++++++++---- database/gdb/gdb_unit_z_mysql_model_test.go | 5 ++++ 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/.example/other/test.go b/.example/other/test.go index d110a510c..d1c90d218 100644 --- a/.example/other/test.go +++ b/.example/other/test.go @@ -1,10 +1,19 @@ package main -import ( - "fmt" -) +import "fmt" + +// apiString is the type assert api for String. +type apiString interface { + String() string +} func main() { - a := []interface{}{1} - fmt.Println(a[1]) + for i := 0; i < 10; i++ { + switch 1 { + case 1: + continue + } + fmt.Println(i) + } + } diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index 54a611421..f18f3951f 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -206,8 +206,13 @@ func GetPrimaryKey(pointer interface{}) string { // GetPrimaryKeyCondition returns a new where condition by primary field name. // The optional parameter is like follows: -// 123, []int{1, 2, 3}, "john", []string{"john", "smith"} -// g.Map{"id": g.Slice{1,2,3}}, g.Map{"id": 1, "name": "john"}, etc. +// 123 +// []int{1, 2, 3} +// "john" +// []string{"john", "smith"} +// g.Map{"id": g.Slice{1,2,3}} +// g.Map{"id": 1, "name": "john"} +// etc. // // Note that it returns the given parameter directly if there's the is empty. func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondition []interface{}) { @@ -448,11 +453,23 @@ func handleArguments(sql string, args []interface{}) (newSql string, newArgs []i newArgs = append(newArgs, arg) continue } - // It converts the struct to string in default - // if it implements the String interface. - if v, ok := arg.(apiString); ok { + switch v := arg.(type) { + case time.Time, *time.Time: + newArgs = append(newArgs, arg) + continue + + // Special handling for gtime.Time. + case gtime.Time: newArgs = append(newArgs, v.String()) continue + + default: + // It converts the struct to string in default + // if it implements the String interface. + if v, ok := arg.(apiString); ok { + newArgs = append(newArgs, v.String()) + continue + } } newArgs = append(newArgs, arg) diff --git a/database/gdb/gdb_unit_z_mysql_model_test.go b/database/gdb/gdb_unit_z_mysql_model_test.go index bc5ad7cb3..3e8f3ac7d 100644 --- a/database/gdb/gdb_unit_z_mysql_model_test.go +++ b/database/gdb/gdb_unit_z_mysql_model_test.go @@ -1274,6 +1274,11 @@ func Test_Model_Where_GTime(t *testing.T) { t.Assert(err, nil) t.Assert(len(result), 10) }) + gtest.C(t, func(t *gtest.T) { + result, err := db.Table(table).Where("create_time>?", *gtime.NewFromStr("2010-09-01")).All() + t.Assert(err, nil) + t.Assert(len(result), 10) + }) } func Test_Model_WherePri(t *testing.T) {