move ut cases from package gdb to contrib/drivers/mysql

This commit is contained in:
John Guo
2022-05-10 15:38:08 +08:00
parent 2cbfdf43cf
commit dc6a9237d7
43 changed files with 945 additions and 1516 deletions

View File

@ -12,7 +12,6 @@ import (
"fmt"
"net/url"
_ "github.com/go-sql-driver/mysql"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"

View File

@ -1,76 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"context"
"testing"
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
// MyDriver is a custom database driver, which is used for testing only.
// For simplifying the unit testing case purpose, MyDriver struct inherits the mysql driver
// gdb.DriverMysql and overwrites its function DoCommit.
// So if there's any sql execution, it goes through MyDriver.DoCommit firstly and
// then gdb.DriverMysql.DoCommit.
// You can call it sql "HOOK" or "HiJack" as your will.
type MyDriver struct {
*gdb.DriverMysql
}
var (
customDriverName = "MyDriver"
latestSqlString = gtype.NewString() // For simplifying unit testing only.
)
// New creates and returns a database object for mysql.
// It implements the interface of gdb.Driver for extra database driver installation.
func (d *MyDriver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
return &MyDriver{
&gdb.DriverMysql{
Core: core,
},
}, nil
}
// DoFilter handles the sql before posts it to database.
// It here overwrites the same method of gdb.DriverMysql and makes some custom changes.
func (d *MyDriver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
latestSqlString.Set(sql)
return d.DriverMysql.DoFilter(ctx, link, sql, args)
}
func init() {
// It here registers my custom driver in package initialization function "init".
// You can later use this type in the database configuration.
gdb.Register(customDriverName, &MyDriver{})
}
func Test_Custom_Driver(t *testing.T) {
gdb.AddConfigNode("driver-test", gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: TestDbUser,
Pass: TestDbPass,
Name: "test",
Type: customDriverName,
Role: "master",
Charset: "utf8",
})
gtest.C(t, func(t *gtest.T) {
t.Assert(latestSqlString.Val(), "")
sqlString := "select 10000"
value, err := g.DB("driver-test").GetValue(ctx, sqlString)
t.AssertNil(err)
t.Assert(value, 10000)
t.Assert(latestSqlString.Val(), sqlString)
})
}

View File

@ -14,7 +14,7 @@ import (
)
func Example_transaction() {
db.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
// user
result, err := tx.Insert("user", g.Map{
"passport": "john",

View File

@ -1,229 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"context"
"fmt"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
)
const (
TableSize = 10
TableName = "user"
TestSchema1 = "test1"
TestSchema2 = "test2"
TableNamePrefix1 = "gf_"
TestDbUser = "root"
TestDbPass = "12345678"
CreateTime = "2018-10-24 10:00:00"
)
var (
db gdb.DB
dbPrefix gdb.DB
dbInvalid gdb.DB
configNode gdb.ConfigNode
ctx = context.TODO()
)
func init() {
parser, err := gcmd.Parse(g.MapStrBool{
"name": true,
"type": true,
}, false)
gtest.AssertNil(err)
configNode = gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: TestDbUser,
Pass: TestDbPass,
Timezone: "Asia/Shanghai", // For calculating UT cases of datetime zones in convenience.
Name: parser.GetOpt("name", "").String(),
Type: parser.GetOpt("type", "mysql").String(),
Role: "master",
Charset: "utf8",
Weight: 1,
MaxIdleConnCount: 10,
MaxOpenConnCount: 10,
MaxConnLifeTime: 600,
}
nodePrefix := configNode
nodePrefix.Prefix = TableNamePrefix1
nodeInvalid := configNode
nodeInvalid.Port = "3307"
gdb.AddConfigNode("test", configNode)
gdb.AddConfigNode("prefix", nodePrefix)
gdb.AddConfigNode("nodeinvalid", nodeInvalid)
gdb.AddConfigNode(gdb.DefaultGroupName, configNode)
// Default db.
if r, err := gdb.NewByGroup(); err != nil {
gtest.Error(err)
} else {
db = r
}
schemaTemplate := "CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET UTF8"
if _, err := db.Exec(ctx, fmt.Sprintf(schemaTemplate, TestSchema1)); err != nil {
gtest.Error(err)
}
if _, err := db.Exec(ctx, fmt.Sprintf(schemaTemplate, TestSchema2)); err != nil {
gtest.Error(err)
}
db = db.Schema(TestSchema1)
// Prefix db.
if r, err := gdb.NewByGroup("prefix"); err != nil {
gtest.Error(err)
} else {
dbPrefix = r
}
if _, err := dbPrefix.Exec(ctx, fmt.Sprintf(schemaTemplate, TestSchema1)); err != nil {
gtest.Error(err)
}
if _, err := dbPrefix.Exec(ctx, fmt.Sprintf(schemaTemplate, TestSchema2)); err != nil {
gtest.Error(err)
}
dbPrefix = dbPrefix.Schema(TestSchema1)
// Invalid db.
if r, err := gdb.NewByGroup("nodeinvalid"); err != nil {
gtest.Error(err)
} else {
dbInvalid = r
}
dbInvalid = dbInvalid.Schema(TestSchema1)
}
func createTable(table ...string) string {
return createTableWithDb(db, table...)
}
func createInitTable(table ...string) string {
return createInitTableWithDb(db, table...)
}
func dropTable(table string) {
dropTableWithDb(db, table)
}
func createTableWithDb(db gdb.DB, table ...string) (name string) {
if len(table) > 0 {
name = table[0]
} else {
name = fmt.Sprintf(`%s_%d`, TableName, gtime.TimestampNano())
}
dropTableWithDb(db, name)
switch configNode.Type {
case "sqlite":
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id bigint unsigned NOT NULL AUTO_INCREMENT,
passport varchar(45),
password char(32) NOT NULL,
nickname varchar(45) NOT NULL,
create_time timestamp NOT NULL,
PRIMARY KEY (id)
) ;`, name,
)); err != nil {
gtest.Fatal(err)
}
case "pgsql":
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id bigint NOT NULL,
passport varchar(45),
password char(32) NOT NULL,
nickname varchar(45) NOT NULL,
create_time timestamp NOT NULL,
PRIMARY KEY (id)
) ;`, name,
)); err != nil {
gtest.Fatal(err)
}
case "mssql":
if _, err := db.Exec(ctx, fmt.Sprintf(`
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='%s' and xtype='U')
CREATE TABLE %s (
ID numeric(10,0) NOT NULL,
PASSPORT VARCHAR(45) NOT NULL,
PASSWORD CHAR(32) NOT NULL,
NICKNAME VARCHAR(45) NOT NULL,
CREATE_TIME datetime NOT NULL,
PRIMARY KEY (ID))`,
name, name,
)); err != nil {
gtest.Fatal(err)
}
case "oracle":
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
ID NUMBER(10) NOT NULL,
PASSPORT VARCHAR(45) NOT NULL,
PASSWORD CHAR(32) NOT NULL,
NICKNAME VARCHAR(45) NOT NULL,
CREATE_TIME varchar(45) NOT NULL,
PRIMARY KEY (ID))
`, name,
)); err != nil {
gtest.Fatal(err)
}
case "mysql":
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
passport varchar(45) NULL,
password char(32) NULL,
nickname varchar(45) NULL,
create_time timestamp NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, name,
)); err != nil {
gtest.Fatal(err)
}
}
return
}
func createInitTableWithDb(db gdb.DB, table ...string) (name string) {
name = createTableWithDb(db, table...)
array := garray.New(true)
for i := 1; i <= TableSize; i++ {
array.Append(g.Map{
"id": i,
"passport": fmt.Sprintf(`user_%d`, i),
"password": fmt.Sprintf(`pass_%d`, i),
"nickname": fmt.Sprintf(`name_%d`, i),
"create_time": gtime.NewFromStr(CreateTime).String(),
})
}
result, err := db.Insert(ctx, name, array.Slice())
gtest.AssertNil(err)
n, e := result.RowsAffected()
gtest.Assert(e, nil)
gtest.Assert(n, TableSize)
return
}
func dropTableWithDb(db gdb.DB, table string) {
if _, err := db.Exec(ctx, fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table)); err != nil {
gtest.Error(err)
}
}

View File

@ -1,45 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/go-sql-driver/mysql"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Instance(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
_, err := gdb.Instance("none")
t.AssertNE(err, nil)
db, err := gdb.Instance()
t.AssertNil(err)
err1 := db.PingMaster()
err2 := db.PingSlave()
t.Assert(err1, nil)
t.Assert(err2, nil)
})
}
// Fix issue: https://github.com/gogf/gf/issues/819
func Test_Func_ConvertDataForRecord(t *testing.T) {
type Test struct {
ResetPasswordTokenAt mysql.NullTime `orm:"reset_password_token_at"`
}
gtest.C(t, func(t *gtest.T) {
c := &gdb.Core{}
m := c.ConvertDataForRecord(nil, new(Test))
t.Assert(len(m), 1)
t.AssertNE(m["reset_password_token_at"], nil)
t.Assert(m["reset_password_token_at"], new(mysql.NullTime))
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,64 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"context"
"testing"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Ctx(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
db, err := gdb.Instance()
t.AssertNil(err)
err1 := db.PingMaster()
err2 := db.PingSlave()
t.Assert(err1, nil)
t.Assert(err2, nil)
newDb := db.Ctx(context.Background())
t.AssertNE(newDb, nil)
})
}
func Test_Ctx_Query(t *testing.T) {
db.GetLogger().SetCtxKeys("SpanId", "TraceId")
gtest.C(t, func(t *gtest.T) {
db.SetDebug(true)
defer db.SetDebug(false)
ctx := context.WithValue(context.Background(), "TraceId", "12345678")
ctx = context.WithValue(ctx, "SpanId", "0.1")
db.Query(ctx, "select 1")
})
gtest.C(t, func(t *gtest.T) {
db.SetDebug(true)
defer db.SetDebug(false)
db.Query(ctx, "select 2")
})
}
func Test_Ctx_Model(t *testing.T) {
table := createInitTable()
defer dropTable(table)
db.GetLogger().SetCtxKeys("SpanId", "TraceId")
gtest.C(t, func(t *gtest.T) {
db.SetDebug(true)
defer db.SetDebug(false)
ctx := context.WithValue(context.Background(), "TraceId", "12345678")
ctx = context.WithValue(ctx, "SpanId", "0.1")
db.Model(table).Ctx(ctx).All()
})
gtest.C(t, func(t *gtest.T) {
db.SetDebug(true)
defer db.SetDebug(false)
db.Model(table).All()
})
}

View File

@ -1,136 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"context"
"database/sql"
"fmt"
"testing"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Model_Hook_Select(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
m := db.Model(table).Hook(gdb.HookHandler{
Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
result, err = in.Next(ctx)
if err != nil {
return
}
for i, record := range result {
record["test"] = gvar.New(100 + record["id"].Int())
result[i] = record
}
return
},
})
all, err := m.Where(`id > 6`).OrderAsc(`id`).All()
t.AssertNil(err)
t.Assert(len(all), 4)
t.Assert(all[0]["id"].Int(), 7)
t.Assert(all[0]["test"].Int(), 107)
t.Assert(all[1]["test"].Int(), 108)
t.Assert(all[2]["test"].Int(), 109)
t.Assert(all[3]["test"].Int(), 110)
})
}
func Test_Model_Hook_Insert(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
m := db.Model(table).Hook(gdb.HookHandler{
Insert: func(ctx context.Context, in *gdb.HookInsertInput) (result sql.Result, err error) {
for i, item := range in.Data {
item["passport"] = fmt.Sprintf(`test_port_%d`, item["id"])
item["nickname"] = fmt.Sprintf(`test_name_%d`, item["id"])
in.Data[i] = item
}
return in.Next(ctx)
},
})
_, err := m.Insert(g.Map{
"id": 1,
"nickname": "name_1",
})
t.AssertNil(err)
one, err := m.One()
t.AssertNil(err)
t.Assert(one["id"].Int(), 1)
t.Assert(one["passport"], `test_port_1`)
t.Assert(one["nickname"], `test_name_1`)
})
}
func Test_Model_Hook_Update(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
m := db.Model(table).Hook(gdb.HookHandler{
Update: func(ctx context.Context, in *gdb.HookUpdateInput) (result sql.Result, err error) {
switch value := in.Data.(type) {
case gdb.List:
for i, data := range value {
data["passport"] = `port`
data["nickname"] = `name`
value[i] = data
}
in.Data = value
case gdb.Map:
value["passport"] = `port`
value["nickname"] = `name`
in.Data = value
}
return in.Next(ctx)
},
})
_, err := m.Data(g.Map{
"nickname": "name_1",
}).WherePri(1).Update()
t.AssertNil(err)
one, err := m.One()
t.AssertNil(err)
t.Assert(one["id"].Int(), 1)
t.Assert(one["passport"], `port`)
t.Assert(one["nickname"], `name`)
})
}
func Test_Model_Hook_Delete(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
m := db.Model(table).Hook(gdb.HookHandler{
Delete: func(ctx context.Context, in *gdb.HookDeleteInput) (result sql.Result, err error) {
return db.Model(table).Data(g.Map{
"nickname": `deleted`,
}).Where(in.Condition).Update()
},
})
_, err := m.Where(1).Delete()
t.AssertNil(err)
all, err := m.All()
t.AssertNil(err)
for _, item := range all {
t.Assert(item["nickname"].String(), `deleted`)
}
})
}

View File

@ -1,62 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Model_Builder(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
m := db.Model(table)
b := m.Builder()
all, err := m.Where(
b.Where("id", g.Slice{1, 2, 3}).WhereOr("id", g.Slice{4, 5, 6}),
).All()
t.AssertNil(err)
t.Assert(len(all), 6)
})
// Where And
gtest.C(t, func(t *gtest.T) {
m := db.Model(table)
b := m.Builder()
all, err := m.Where(
b.Where("id", g.Slice{1, 2, 3}).WhereOr("id", g.Slice{4, 5, 6}),
).Where(
b.Where("id", g.Slice{2, 3}).WhereOr("id", g.Slice{5, 6}),
).Where(
b.Where("id", g.Slice{3}).Where("id", g.Slice{1, 2, 3}),
).All()
t.AssertNil(err)
t.Assert(len(all), 1)
})
// Where Or
gtest.C(t, func(t *gtest.T) {
m := db.Model(table)
b := m.Builder()
all, err := m.WhereOr(
b.Where("id", g.Slice{1, 2, 3}).WhereOr("id", g.Slice{4, 5, 6}),
).WhereOr(
b.Where("id", g.Slice{2, 3}).WhereOr("id", g.Slice{5, 6}),
).WhereOr(
b.Where("id", g.Slice{3}).Where("id", g.Slice{1, 2, 3}),
).All()
t.AssertNil(err)
t.Assert(len(all), 6)
})
}

View File

@ -1,286 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Model_Insert_Data_DO(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := User{
Id: 1,
Passport: "user_1",
Password: "pass_1",
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 1)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
})
}
func Test_Model_Insert_Data_LIst_DO(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := g.Slice{
User{
Id: 1,
Passport: "user_1",
Password: "pass_1",
},
User{
Id: 2,
Passport: "user_2",
Password: "pass_2",
},
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 2)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
one, err = db.Model(table).WherePri(2).One()
t.AssertNil(err)
t.Assert(one[`id`], `2`)
t.Assert(one[`passport`], `user_2`)
t.Assert(one[`password`], `pass_2`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
})
}
func Test_Model_Update_Data_DO(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := User{
Id: 1,
Passport: "user_100",
Password: "pass_100",
}
_, err := db.Model(table).Data(data).WherePri(1).Update()
t.AssertNil(err)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_100`)
t.Assert(one[`password`], `pass_100`)
t.Assert(one[`nickname`], `name_1`)
})
}
func Test_Model_Where_DO(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
where := User{
Id: 1,
Passport: "user_1",
Password: "pass_1",
}
one, err := db.Model(table).Where(where).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], `name_1`)
})
}
func Test_Model_Insert_Data_ForDao(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type UserForDao struct {
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := UserForDao{
Id: 1,
Passport: "user_1",
Password: "pass_1",
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 1)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
})
}
func Test_Model_Insert_Data_LIst_ForDao(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type UserForDao struct {
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := g.Slice{
UserForDao{
Id: 1,
Passport: "user_1",
Password: "pass_1",
},
UserForDao{
Id: 2,
Passport: "user_2",
Password: "pass_2",
},
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 2)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
one, err = db.Model(table).WherePri(2).One()
t.AssertNil(err)
t.Assert(one[`id`], `2`)
t.Assert(one[`passport`], `user_2`)
t.Assert(one[`password`], `pass_2`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
})
}
func Test_Model_Update_Data_ForDao(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type UserForDao struct {
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := UserForDao{
Id: 1,
Passport: "user_100",
Password: "pass_100",
}
_, err := db.Model(table).Data(data).WherePri(1).Update()
t.AssertNil(err)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_100`)
t.Assert(one[`password`], `pass_100`)
t.Assert(one[`nickname`], `name_1`)
})
}
func Test_Model_Where_ForDao(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type UserForDao struct {
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
where := UserForDao{
Id: 1,
Passport: "user_1",
Password: "pass_1",
}
one, err := db.Model(table).Where(where).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], `pass_1`)
t.Assert(one[`nickname`], `name_1`)
})
}

View File

@ -1,84 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Model_LeftJoinOnField(t *testing.T) {
var (
table1 = gtime.TimestampNanoStr() + "_table1"
table2 = gtime.TimestampNanoStr() + "_table2"
)
createInitTable(table1)
defer dropTable(table1)
createInitTable(table2)
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table1).
FieldsPrefix(table1, "*").
LeftJoinOnField(table2, "id").
WhereIn("id", g.Slice{1, 2}).
Order("id asc").All()
t.AssertNil(err)
t.Assert(len(r), 2)
t.Assert(r[0]["id"], "1")
t.Assert(r[1]["id"], "2")
})
}
func Test_Model_RightJoinOnField(t *testing.T) {
var (
table1 = gtime.TimestampNanoStr() + "_table1"
table2 = gtime.TimestampNanoStr() + "_table2"
)
createInitTable(table1)
defer dropTable(table1)
createInitTable(table2)
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table1).
FieldsPrefix(table1, "*").
RightJoinOnField(table2, "id").
WhereIn("id", g.Slice{1, 2}).
Order("id asc").All()
t.AssertNil(err)
t.Assert(len(r), 2)
t.Assert(r[0]["id"], "1")
t.Assert(r[1]["id"], "2")
})
}
func Test_Model_InnerJoinOnField(t *testing.T) {
var (
table1 = gtime.TimestampNanoStr() + "_table1"
table2 = gtime.TimestampNanoStr() + "_table2"
)
createInitTable(table1)
defer dropTable(table1)
createInitTable(table2)
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table1).
FieldsPrefix(table1, "*").
InnerJoinOnField(table2, "id").
WhereIn("id", g.Slice{1, 2}).
Order("id asc").All()
t.AssertNil(err)
t.Assert(len(r), 2)
t.Assert(r[0]["id"], "1")
t.Assert(r[1]["id"], "2")
})
}

View File

@ -1,597 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"database/sql"
"reflect"
"testing"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
func Test_Model_Embedded_Insert(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type Base struct {
Id int `json:"id"`
Uid int `json:"uid"`
CreateTime string `json:"create_time"`
}
type User struct {
Base
Passport string `json:"passport"`
Password string `json:"password"`
Nickname string `json:"nickname"`
}
result, err := db.Model(table).Data(User{
Passport: "john-test",
Password: "123456",
Nickname: "John",
Base: Base{
Id: 100,
Uid: 100,
CreateTime: gtime.Now().String(),
},
}).Insert()
t.AssertNil(err)
n, _ := result.RowsAffected()
t.Assert(n, 1)
value, err := db.Model(table).Fields("passport").Where("id=100").Value()
t.AssertNil(err)
t.Assert(value.String(), "john-test")
})
}
func Test_Model_Embedded_MapToStruct(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type Ids struct {
Id int `json:"id"`
Uid int `json:"uid"`
}
type Base struct {
Ids
CreateTime string `json:"create_time"`
}
type User struct {
Base
Passport string `json:"passport"`
Password string `json:"password"`
Nickname string `json:"nickname"`
}
data := g.Map{
"id": 100,
"uid": 101,
"passport": "t1",
"password": "123456",
"nickname": "T1",
"create_time": gtime.Now().String(),
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := result.RowsAffected()
t.Assert(n, 1)
one, err := db.Model(table).Where("id=100").One()
t.AssertNil(err)
user := new(User)
t.Assert(one.Struct(user), nil)
t.Assert(user.Id, data["id"])
t.Assert(user.Passport, data["passport"])
t.Assert(user.Password, data["password"])
t.Assert(user.Nickname, data["nickname"])
t.Assert(user.CreateTime, data["create_time"])
})
}
func Test_Struct_Pointer_Attribute(t *testing.T) {
table := createInitTable()
defer dropTable(table)
type User struct {
Id *int
Passport *string
Password *string
Nickname string
}
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
user := new(User)
err = one.Struct(user)
t.AssertNil(err)
t.Assert(*user.Id, 1)
t.Assert(*user.Passport, "user_1")
t.Assert(*user.Password, "pass_1")
t.Assert(user.Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
user := new(User)
err := db.Model(table).Scan(user, "id=1")
t.AssertNil(err)
t.Assert(*user.Id, 1)
t.Assert(*user.Passport, "user_1")
t.Assert(*user.Password, "pass_1")
t.Assert(user.Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
var user *User
err := db.Model(table).Scan(&user, "id=1")
t.AssertNil(err)
t.Assert(*user.Id, 1)
t.Assert(*user.Passport, "user_1")
t.Assert(*user.Password, "pass_1")
t.Assert(user.Nickname, "name_1")
})
}
func Test_Structs_Pointer_Attribute(t *testing.T) {
table := createInitTable()
defer dropTable(table)
type User struct {
Id *int
Passport *string
Password *string
Nickname string
}
// All
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).All("id < 3")
t.AssertNil(err)
users := make([]User, 0)
err = one.Structs(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).All("id < 3")
t.AssertNil(err)
users := make([]*User, 0)
err = one.Structs(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
var users []User
one, err := db.Model(table).All("id < 3")
t.AssertNil(err)
err = one.Structs(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
var users []*User
one, err := db.Model(table).All("id < 3")
t.AssertNil(err)
err = one.Structs(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
// Structs
gtest.C(t, func(t *gtest.T) {
users := make([]User, 0)
err := db.Model(table).Scan(&users, "id < 3")
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
users := make([]*User, 0)
err := db.Model(table).Scan(&users, "id < 3")
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
var users []User
err := db.Model(table).Scan(&users, "id < 3")
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
gtest.C(t, func(t *gtest.T) {
var users []*User
err := db.Model(table).Scan(&users, "id < 3")
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(*users[0].Id, 1)
t.Assert(*users[0].Passport, "user_1")
t.Assert(*users[0].Password, "pass_1")
t.Assert(users[0].Nickname, "name_1")
})
}
func Test_Struct_Empty(t *testing.T) {
table := createTable()
defer dropTable(table)
type User struct {
Id int
Passport string
Password string
Nickname string
}
gtest.C(t, func(t *gtest.T) {
user := new(User)
err := db.Model(table).Where("id=100").Scan(user)
t.Assert(err, sql.ErrNoRows)
t.AssertNE(user, nil)
})
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).Where("id=100").One()
t.AssertNil(err)
var user *User
t.Assert(one.Struct(&user), nil)
t.Assert(user, nil)
})
gtest.C(t, func(t *gtest.T) {
var user *User
err := db.Model(table).Where("id=100").Scan(&user)
t.AssertNil(err)
t.Assert(user, nil)
})
}
func Test_Structs_Empty(t *testing.T) {
table := createTable()
defer dropTable(table)
type User struct {
Id int
Passport string
Password string
Nickname string
}
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
users := make([]User, 0)
t.Assert(all.Structs(&users), nil)
})
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
users := make([]User, 10)
t.Assert(all.Structs(&users), nil)
})
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
var users []User
t.Assert(all.Structs(&users), nil)
})
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
users := make([]*User, 0)
t.Assert(all.Structs(&users), nil)
})
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
users := make([]*User, 10)
t.Assert(all.Structs(&users), nil)
})
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(table).Where("id>100").All()
t.AssertNil(err)
var users []*User
t.Assert(all.Structs(&users), nil)
})
}
type MyTime struct {
gtime.Time
}
type MyTimeSt struct {
CreateTime MyTime
}
func (st *MyTimeSt) UnmarshalValue(v interface{}) error {
m := gconv.Map(v)
t, err := gtime.StrToTime(gconv.String(m["create_time"]))
if err != nil {
return err
}
st.CreateTime = MyTime{*t}
return nil
}
func Test_Model_Scan_CustomType_Time(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
st := new(MyTimeSt)
err := db.Model(table).Fields("create_time").Scan(st)
t.AssertNil(err)
t.Assert(st.CreateTime.String(), "2018-10-24 10:00:00")
})
gtest.C(t, func(t *gtest.T) {
var stSlice []*MyTimeSt
err := db.Model(table).Fields("create_time").Scan(&stSlice)
t.AssertNil(err)
t.Assert(len(stSlice), TableSize)
t.Assert(stSlice[0].CreateTime.String(), "2018-10-24 10:00:00")
t.Assert(stSlice[9].CreateTime.String(), "2018-10-24 10:00:00")
})
}
func Test_Model_Scan_CustomType_String(t *testing.T) {
type MyString string
type MyStringSt struct {
Passport MyString
}
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
st := new(MyStringSt)
err := db.Model(table).Fields("Passport").WherePri(1).Scan(st)
t.AssertNil(err)
t.Assert(st.Passport, "user_1")
})
gtest.C(t, func(t *gtest.T) {
var sts []MyStringSt
err := db.Model(table).Fields("Passport").Order("id asc").Scan(&sts)
t.AssertNil(err)
t.Assert(len(sts), TableSize)
t.Assert(sts[0].Passport, "user_1")
})
}
type User struct {
Id int
Passport string
Password string
Nickname string
CreateTime *gtime.Time
}
func (user *User) UnmarshalValue(value interface{}) error {
if record, ok := value.(gdb.Record); ok {
*user = User{
Id: record["id"].Int(),
Passport: record["passport"].String(),
Password: "",
Nickname: record["nickname"].String(),
CreateTime: record["create_time"].GTime(),
}
return nil
}
return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported value type for UnmarshalValue: %v`, reflect.TypeOf(value))
}
func Test_Model_Scan_UnmarshalValue(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
var users []*User
err := db.Model(table).Order("id asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), TableSize)
t.Assert(users[0].Id, 1)
t.Assert(users[0].Passport, "user_1")
t.Assert(users[0].Password, "")
t.Assert(users[0].Nickname, "name_1")
t.Assert(users[0].CreateTime.String(), CreateTime)
t.Assert(users[9].Id, 10)
t.Assert(users[9].Passport, "user_10")
t.Assert(users[9].Password, "")
t.Assert(users[9].Nickname, "name_10")
t.Assert(users[9].CreateTime.String(), CreateTime)
})
}
func Test_Model_Scan_Map(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
var users []*User
err := db.Model(table).Order("id asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), TableSize)
t.Assert(users[0].Id, 1)
t.Assert(users[0].Passport, "user_1")
t.Assert(users[0].Password, "")
t.Assert(users[0].Nickname, "name_1")
t.Assert(users[0].CreateTime.String(), CreateTime)
t.Assert(users[9].Id, 10)
t.Assert(users[9].Passport, "user_10")
t.Assert(users[9].Password, "")
t.Assert(users[9].Nickname, "name_10")
t.Assert(users[9].CreateTime.String(), CreateTime)
})
}
func Test_Scan_AutoFilteringByStructAttributes(t *testing.T) {
table := createInitTable()
defer dropTable(table)
type User struct {
Id int
Passport string
}
// db.SetDebug(true)
gtest.C(t, func(t *gtest.T) {
var user *User
err := db.Model(table).OrderAsc("id").Scan(&user)
t.AssertNil(err)
t.Assert(user.Id, 1)
})
gtest.C(t, func(t *gtest.T) {
var users []User
err := db.Model(table).OrderAsc("id").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), TableSize)
t.Assert(users[0].Id, 1)
})
}
func Test_Scan_JsonAttributes(t *testing.T) {
type GiftImage struct {
Uid string `json:"uid"`
Url string `json:"url"`
Status string `json:"status"`
Name string `json:"name"`
}
type GiftComment struct {
Name string `json:"name"`
Field string `json:"field"`
Required bool `json:"required"`
}
type Prop struct {
Name string `json:"name"`
Values []string `json:"values"`
}
type Sku struct {
GiftId int64 `json:"gift_id"`
Name string `json:"name"`
ScorePrice int `json:"score_price"`
MarketPrice int `json:"market_price"`
CostPrice int `json:"cost_price"`
Stock int `json:"stock"`
}
type Covers struct {
List []GiftImage `json:"list"`
}
type GiftEntity struct {
Id int64 `json:"id"`
StoreId int64 `json:"store_id"`
GiftType int `json:"gift_type"`
GiftName string `json:"gift_name"`
Description string `json:"description"`
Covers Covers `json:"covers"`
Cover string `json:"cover"`
GiftCategoryId []int64 `json:"gift_category_id"`
HasProps bool `json:"has_props"`
OutSn string `json:"out_sn"`
IsLimitSell bool `json:"is_limit_sell"`
LimitSellType int `json:"limit_sell_type"`
LimitSellCycle string `json:"limit_sell_cycle"`
LimitSellCycleCount int `json:"limit_sell_cycle_count"`
LimitSellCustom bool `json:"limit_sell_custom"` // 只允许特定会员兑换
LimitCustomerTags []int64 `json:"limit_customer_tags"` // 允许兑换的成员
ScorePrice int `json:"score_price"`
MarketPrice float64 `json:"market_price"`
CostPrice int `json:"cost_price"`
Stock int `json:"stock"`
Props []Prop `json:"props"`
Skus []Sku `json:"skus"`
ExpressType []string `json:"express_type"`
Comments []GiftComment `json:"comments"`
Content string `json:"content"`
AtLeastRechargeCount int `json:"at_least_recharge_count"`
Status int `json:"status"`
}
type User struct {
Id int
Passport string
}
table := "jfy_gift"
array := gstr.SplitAndTrim(gtest.DataContent(`issue1380.sql`), ";")
for _, v := range array {
if _, err := db.Exec(ctx, v); err != nil {
gtest.Error(err)
}
}
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
var (
entity = new(GiftEntity)
err = db.Model(table).Where("id", 17).Scan(entity)
)
t.AssertNil(err)
t.Assert(len(entity.Skus), 2)
t.Assert(entity.Skus[0].Name, "red")
t.Assert(entity.Skus[0].Stock, 10)
t.Assert(entity.Skus[0].GiftId, 1)
t.Assert(entity.Skus[0].CostPrice, 80)
t.Assert(entity.Skus[0].ScorePrice, 188)
t.Assert(entity.Skus[0].MarketPrice, 388)
t.Assert(entity.Skus[1].Name, "blue")
t.Assert(entity.Skus[1].Stock, 100)
t.Assert(entity.Skus[1].GiftId, 2)
t.Assert(entity.Skus[1].CostPrice, 81)
t.Assert(entity.Skus[1].ScorePrice, 200)
t.Assert(entity.Skus[1].MarketPrice, 288)
t.Assert(entity.Id, 17)
t.Assert(entity.StoreId, 100004)
t.Assert(entity.GiftType, 1)
t.Assert(entity.GiftName, "GIFT")
t.Assert(entity.Description, "支持个性定制的父亲节老师长辈的专属礼物")
t.Assert(len(entity.Covers.List), 3)
t.Assert(entity.OutSn, "259402")
t.Assert(entity.LimitCustomerTags, "[]")
t.Assert(entity.ScorePrice, 10)
t.Assert(len(entity.Props), 1)
t.Assert(len(entity.Comments), 2)
t.Assert(entity.Status, 99)
t.Assert(entity.Content, `<p>礼品详情</p>`)
})
}

View File

@ -1,66 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Model_SubQuery_Where(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).Where(
"id in ?",
db.Model(table).Fields("id").Where("id", g.Slice{1, 3, 5}),
).OrderAsc("id").All()
t.AssertNil(err)
t.Assert(len(r), 3)
t.Assert(r[0]["id"], 1)
t.Assert(r[1]["id"], 3)
t.Assert(r[2]["id"], 5)
})
}
func Test_Model_SubQuery_Having(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).Where(
"id in ?",
db.Model(table).Fields("id").Where("id", g.Slice{1, 3, 5}),
).Having(
"id > ?",
db.Model(table).Fields("MAX(id)").Where("id", g.Slice{1, 3}),
).OrderAsc("id").All()
t.AssertNil(err)
t.Assert(len(r), 1)
t.Assert(r[0]["id"], 5)
})
}
func Test_Model_SubQuery_Model(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
subQuery1 := db.Model(table).Where("id", g.Slice{1, 3, 5})
subQuery2 := db.Model(table).Where("id", g.Slice{5, 7, 9})
r, err := db.Model("? AS a, ? AS b", subQuery1, subQuery2).Fields("a.id").Where("a.id=b.id").OrderAsc("id").All()
t.AssertNil(err)
t.Assert(len(r), 1)
t.Assert(r[0]["id"], 5)
})
}

View File

@ -1,86 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Insert_Raw(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
user := db.Model(table)
result, err := user.Data(g.Map{
"id": gdb.Raw("id+2"),
"passport": "port_1",
"password": "pass_1",
"nickname": "name_1",
"create_time": gdb.Raw("now()"),
}).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 2)
})
}
func Test_BatchInsert_Raw(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
user := db.Model(table)
result, err := user.Data(
g.List{
g.Map{
"id": gdb.Raw("id+2"),
"passport": "port_2",
"password": "pass_2",
"nickname": "name_2",
"create_time": gdb.Raw("now()"),
},
g.Map{
"id": gdb.Raw("id+4"),
"passport": "port_4",
"password": "pass_4",
"nickname": "name_4",
"create_time": gdb.Raw("now()"),
},
},
).Insert()
t.AssertNil(err)
n, _ := result.LastInsertId()
t.Assert(n, 4)
})
}
func Test_Update_Raw(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
user := db.Model(table)
result, err := user.Data(g.Map{
"id": gdb.Raw("id+100"),
"create_time": gdb.Raw("now()"),
}).Where("id", 1).Update()
t.AssertNil(err)
n, _ := result.RowsAffected()
t.Assert(n, 1)
})
gtest.C(t, func(t *gtest.T) {
user := db.Model(table)
n, err := user.Where("id", 101).Count()
t.AssertNil(err)
t.Assert(n, 1)
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,857 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
)
// CreateAt/UpdateAt/DeleteAt.
func Test_SoftCreateUpdateDeleteTime(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := g.Map{
"id": 1,
"name": "name_1",
}
r, err := db.Model(table).Data(dataInsert).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInsert, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInsert["id"].Int(), 1)
t.Assert(oneInsert["name"].String(), "name_1")
t.Assert(oneInsert["delete_at"].String(), "")
t.AssertGE(oneInsert["create_at"].GTime().Timestamp(), gtime.Timestamp()-2)
t.AssertGE(oneInsert["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Save
dataSave := g.Map{
"id": 1,
"name": "name_10",
}
r, err = db.Model(table).Data(dataSave).Save()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneSave, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneSave["id"].Int(), 1)
t.Assert(oneSave["name"].String(), "name_10")
t.Assert(oneSave["delete_at"].String(), "")
t.Assert(oneSave["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertNE(oneSave["update_at"].GTime().Timestamp(), oneInsert["update_at"].GTime().Timestamp())
t.AssertGE(oneSave["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Update
dataUpdate := g.Map{
"name": "name_1000",
}
r, err = db.Model(table).Data(dataUpdate).WherePri(1).Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
oneUpdate, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneUpdate["id"].Int(), 1)
t.Assert(oneUpdate["name"].String(), "name_1000")
t.Assert(oneUpdate["delete_at"].String(), "")
t.Assert(oneUpdate["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertGE(oneUpdate["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Replace
dataReplace := g.Map{
"id": 1,
"name": "name_100",
}
r, err = db.Model(table).Data(dataReplace).Replace()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneReplace, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneReplace["id"].Int(), 1)
t.Assert(oneReplace["name"].String(), "name_100")
t.Assert(oneReplace["delete_at"].String(), "")
t.AssertGE(oneReplace["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertGE(oneReplace["update_at"].GTime().Timestamp(), oneInsert["update_at"].GTime().Timestamp())
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Delete
r, err = db.Model(table).Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
// Delete Select
one4, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one4), 0)
one5, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(one5["id"].Int(), 1)
t.AssertGE(one5["delete_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Delete Count
i, err := db.Model(table).Count()
t.AssertNil(err)
t.Assert(i, 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 1)
// Delete Unscoped
r, err = db.Model(table).Unscoped().Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one6, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one6), 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 0)
})
}
// CreatedAt/UpdatedAt/DeletedAt.
func Test_SoftCreatedUpdatedDeletedTime_Map(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
created_at datetime DEFAULT NULL,
updated_at datetime DEFAULT NULL,
deleted_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := g.Map{
"id": 1,
"name": "name_1",
}
r, err := db.Model(table).Data(dataInsert).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInsert, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInsert["id"].Int(), 1)
t.Assert(oneInsert["name"].String(), "name_1")
t.Assert(oneInsert["deleted_at"].String(), "")
t.AssertGE(oneInsert["created_at"].GTime().Timestamp(), gtime.Timestamp()-2)
t.AssertGE(oneInsert["updated_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Save
dataSave := g.Map{
"id": 1,
"name": "name_10",
}
r, err = db.Model(table).Data(dataSave).Save()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneSave, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneSave["id"].Int(), 1)
t.Assert(oneSave["name"].String(), "name_10")
t.Assert(oneSave["deleted_at"].String(), "")
t.Assert(oneSave["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertNE(oneSave["updated_at"].GTime().Timestamp(), oneInsert["updated_at"].GTime().Timestamp())
t.AssertGE(oneSave["updated_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Update
dataUpdate := g.Map{
"name": "name_1000",
}
r, err = db.Model(table).Data(dataUpdate).WherePri(1).Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
oneUpdate, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneUpdate["id"].Int(), 1)
t.Assert(oneUpdate["name"].String(), "name_1000")
t.Assert(oneUpdate["deleted_at"].String(), "")
t.Assert(oneUpdate["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertGE(oneUpdate["updated_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Replace
dataReplace := g.Map{
"id": 1,
"name": "name_100",
}
r, err = db.Model(table).Data(dataReplace).Replace()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneReplace, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneReplace["id"].Int(), 1)
t.Assert(oneReplace["name"].String(), "name_100")
t.Assert(oneReplace["deleted_at"].String(), "")
t.AssertGE(oneReplace["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertGE(oneReplace["updated_at"].GTime().Timestamp(), oneInsert["updated_at"].GTime().Timestamp())
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Delete
r, err = db.Model(table).Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
// Delete Select
one4, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one4), 0)
one5, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(one5["id"].Int(), 1)
t.AssertGE(one5["deleted_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Delete Count
i, err := db.Model(table).Count()
t.AssertNil(err)
t.Assert(i, 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 1)
// Delete Unscoped
r, err = db.Model(table).Unscoped().Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one6, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one6), 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 0)
})
}
// CreatedAt/UpdatedAt/DeletedAt.
func Test_SoftCreatedUpdatedDeletedTime_Struct(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
created_at datetime DEFAULT NULL,
updated_at datetime DEFAULT NULL,
deleted_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
type User struct {
Id int
Name string
CreatedAT *gtime.Time
UpdatedAT *gtime.Time
DeletedAT *gtime.Time
}
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := User{
Id: 1,
Name: "name_1",
}
r, err := db.Model(table).Data(dataInsert).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInsert, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInsert["id"].Int(), 1)
t.Assert(oneInsert["name"].String(), "name_1")
t.Assert(oneInsert["deleted_at"].String(), "")
t.AssertGE(oneInsert["created_at"].GTime().Timestamp(), gtime.Timestamp()-2)
t.AssertGE(oneInsert["updated_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Save
dataSave := User{
Id: 1,
Name: "name_10",
}
r, err = db.Model(table).Data(dataSave).OmitEmpty().Save()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneSave, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneSave["id"].Int(), 1)
t.Assert(oneSave["name"].String(), "name_10")
t.Assert(oneSave["deleted_at"].String(), "")
t.Assert(oneSave["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertNE(oneSave["updated_at"].GTime().Timestamp(), oneInsert["updated_at"].GTime().Timestamp())
t.AssertGE(oneSave["updated_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Update
dataUpdate := User{
Name: "name_1000",
}
r, err = db.Model(table).Data(dataUpdate).OmitEmpty().WherePri(1).Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
oneUpdate, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneUpdate["id"].Int(), 1)
t.Assert(oneUpdate["name"].String(), "name_1000")
t.Assert(oneUpdate["deleted_at"].String(), "")
t.Assert(oneUpdate["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertGE(oneUpdate["updated_at"].GTime().Timestamp(), gtime.Timestamp()-4)
// Replace
dataReplace := User{
Id: 1,
Name: "name_100",
}
r, err = db.Model(table).Data(dataReplace).OmitEmpty().Replace()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneReplace, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneReplace["id"].Int(), 1)
t.Assert(oneReplace["name"].String(), "name_100")
t.Assert(oneReplace["deleted_at"].String(), "")
t.AssertGE(oneReplace["created_at"].GTime().Timestamp(), oneInsert["created_at"].GTime().Timestamp())
t.AssertGE(oneReplace["updated_at"].GTime().Timestamp(), oneInsert["updated_at"].GTime().Timestamp())
// For time asserting purpose.
time.Sleep(2 * time.Second)
// Delete
r, err = db.Model(table).Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
// Delete Select
one4, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one4), 0)
one5, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(one5["id"].Int(), 1)
t.AssertGE(one5["deleted_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Delete Count
i, err := db.Model(table).Count()
t.AssertNil(err)
t.Assert(i, 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 1)
// Delete Unscoped
r, err = db.Model(table).Unscoped().Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one6, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one6), 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 0)
})
}
func Test_SoftUpdateTime(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
num int(11) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := g.Map{
"id": 1,
"num": 10,
}
r, err := db.Model(table).Data(dataInsert).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInsert, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInsert["id"].Int(), 1)
t.Assert(oneInsert["num"].Int(), 10)
// Update.
r, err = db.Model(table).Data("num=num+1").Where("id=?", 1).Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
})
}
func Test_SoftUpdateTime_WithDO(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
num int(11) DEFAULT NULL,
created_at datetime DEFAULT NULL,
updated_at datetime DEFAULT NULL,
deleted_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := g.Map{
"id": 1,
"num": 10,
}
r, err := db.Model(table).Data(dataInsert).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInserted, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInserted["id"].Int(), 1)
t.Assert(oneInserted["num"].Int(), 10)
// Update.
time.Sleep(2 * time.Second)
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Num interface{}
CreatedAt interface{}
UpdatedAt interface{}
DeletedAt interface{}
}
r, err = db.Model(table).Data(User{
Num: 100,
}).Where("id=?", 1).Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
oneUpdated, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneUpdated["num"].Int(), 100)
t.Assert(oneUpdated["created_at"].String(), oneInserted["created_at"].String())
t.AssertNE(oneUpdated["updated_at"].String(), oneInserted["updated_at"].String())
})
}
func Test_SoftDelete(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
// db.SetDebug(true)
gtest.C(t, func(t *gtest.T) {
for i := 1; i <= 10; i++ {
data := g.Map{
"id": i,
"name": fmt.Sprintf("name_%d", i),
}
r, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
}
})
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.AssertNE(one["create_at"].String(), "")
t.AssertNE(one["update_at"].String(), "")
t.Assert(one["delete_at"].String(), "")
})
gtest.C(t, func(t *gtest.T) {
one, err := db.Model(table).WherePri(10).One()
t.AssertNil(err)
t.AssertNE(one["create_at"].String(), "")
t.AssertNE(one["update_at"].String(), "")
t.Assert(one["delete_at"].String(), "")
})
gtest.C(t, func(t *gtest.T) {
ids := g.SliceInt{1, 3, 5}
r, err := db.Model(table).Where("id", ids).Delete()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 3)
count, err := db.Model(table).Where("id", ids).Count()
t.AssertNil(err)
t.Assert(count, 0)
all, err := db.Model(table).Unscoped().Where("id", ids).All()
t.AssertNil(err)
t.Assert(len(all), 3)
t.AssertNE(all[0]["create_at"].String(), "")
t.AssertNE(all[0]["update_at"].String(), "")
t.AssertNE(all[0]["delete_at"].String(), "")
t.AssertNE(all[1]["create_at"].String(), "")
t.AssertNE(all[1]["update_at"].String(), "")
t.AssertNE(all[1]["delete_at"].String(), "")
t.AssertNE(all[2]["create_at"].String(), "")
t.AssertNE(all[2]["update_at"].String(), "")
t.AssertNE(all[2]["delete_at"].String(), "")
})
}
func Test_SoftDelete_Join(t *testing.T) {
table1 := "time_test_table1"
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table1)); err != nil {
gtest.Error(err)
}
defer dropTable(table1)
table2 := "time_test_table2"
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
createat datetime DEFAULT NULL,
updateat datetime DEFAULT NULL,
deleteat datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table2)); err != nil {
gtest.Error(err)
}
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
// db.SetDebug(true)
dataInsert1 := g.Map{
"id": 1,
"name": "name_1",
}
r, err := db.Model(table1).Data(dataInsert1).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
dataInsert2 := g.Map{
"id": 1,
"name": "name_2",
}
r, err = db.Model(table2).Data(dataInsert2).Insert()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one, err := db.Model(table1, "t1").LeftJoin(table2, "t2", "t2.id=t1.id").Fields("t1.name").One()
t.AssertNil(err)
t.Assert(one["name"], "name_1")
// Soft deleting.
r, err = db.Model(table1).Delete()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one, err = db.Model(table1, "t1").LeftJoin(table2, "t2", "t2.id=t1.id").Fields("t1.name").One()
t.AssertNil(err)
t.Assert(one.IsEmpty(), true)
one, err = db.Model(table2, "t2").LeftJoin(table1, "t1", "t2.id=t1.id").Fields("t2.name").One()
t.AssertNil(err)
t.Assert(one.IsEmpty(), true)
})
}
func Test_SoftDelete_WhereAndOr(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
// db.SetDebug(true)
// Add datas.
gtest.C(t, func(t *gtest.T) {
for i := 1; i <= 10; i++ {
data := g.Map{
"id": i,
"name": fmt.Sprintf("name_%d", i),
}
r, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
}
})
gtest.C(t, func(t *gtest.T) {
ids := g.SliceInt{1, 3, 5}
r, err := db.Model(table).Where("id", ids).Delete()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 3)
count, err := db.Model(table).Where("id", 1).WhereOr("id", 3).Count()
t.AssertNil(err)
t.Assert(count, 0)
})
}
func Test_CreateUpdateTime_Struct(t *testing.T) {
table := "time_test_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table)); err != nil {
gtest.Error(err)
}
defer dropTable(table)
// db.SetDebug(true)
// defer db.SetDebug(false)
type Entity struct {
Id uint64 `orm:"id,primary" json:"id"`
Name string `orm:"name" json:"name"`
CreateAt *gtime.Time `orm:"create_at" json:"create_at"`
UpdateAt *gtime.Time `orm:"update_at" json:"update_at"`
DeleteAt *gtime.Time `orm:"delete_at" json:"delete_at"`
}
gtest.C(t, func(t *gtest.T) {
// Insert
dataInsert := &Entity{
Id: 1,
Name: "name_1",
CreateAt: nil,
UpdateAt: nil,
DeleteAt: nil,
}
r, err := db.Model(table).Data(dataInsert).OmitEmpty().Insert()
t.AssertNil(err)
n, _ := r.RowsAffected()
t.Assert(n, 1)
oneInsert, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneInsert["id"].Int(), 1)
t.Assert(oneInsert["name"].String(), "name_1")
t.Assert(oneInsert["delete_at"].String(), "")
t.AssertGE(oneInsert["create_at"].GTime().Timestamp(), gtime.Timestamp()-2)
t.AssertGE(oneInsert["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
time.Sleep(2 * time.Second)
// Save
dataSave := &Entity{
Id: 1,
Name: "name_10",
CreateAt: nil,
UpdateAt: nil,
DeleteAt: nil,
}
r, err = db.Model(table).Data(dataSave).OmitEmpty().Save()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneSave, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneSave["id"].Int(), 1)
t.Assert(oneSave["name"].String(), "name_10")
t.Assert(oneSave["delete_at"].String(), "")
t.Assert(oneSave["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertNE(oneSave["update_at"].GTime().Timestamp(), oneInsert["update_at"].GTime().Timestamp())
t.AssertGE(oneSave["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
time.Sleep(2 * time.Second)
// Update
dataUpdate := &Entity{
Id: 1,
Name: "name_1000",
CreateAt: nil,
UpdateAt: nil,
DeleteAt: nil,
}
r, err = db.Model(table).Data(dataUpdate).WherePri(1).OmitEmpty().Update()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
oneUpdate, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneUpdate["id"].Int(), 1)
t.Assert(oneUpdate["name"].String(), "name_1000")
t.Assert(oneUpdate["delete_at"].String(), "")
t.Assert(oneUpdate["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertGE(oneUpdate["update_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Replace
dataReplace := &Entity{
Id: 1,
Name: "name_100",
CreateAt: nil,
UpdateAt: nil,
DeleteAt: nil,
}
r, err = db.Model(table).Data(dataReplace).OmitEmpty().Replace()
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 2)
oneReplace, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(oneReplace["id"].Int(), 1)
t.Assert(oneReplace["name"].String(), "name_100")
t.Assert(oneReplace["delete_at"].String(), "")
t.AssertGE(oneReplace["create_at"].GTime().Timestamp(), oneInsert["create_at"].GTime().Timestamp())
t.AssertGE(oneReplace["update_at"].GTime().Timestamp(), oneInsert["update_at"].GTime().Timestamp())
time.Sleep(2 * time.Second)
// Delete
r, err = db.Model(table).Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
// Delete Select
one4, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one4), 0)
one5, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(one5["id"].Int(), 1)
t.AssertGE(one5["delete_at"].GTime().Timestamp(), gtime.Timestamp()-2)
// Delete Count
i, err := db.Model(table).Count()
t.AssertNil(err)
t.Assert(i, 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 1)
// Delete Unscoped
r, err = db.Model(table).Unscoped().Delete("id", 1)
t.AssertNil(err)
n, _ = r.RowsAffected()
t.Assert(n, 1)
one6, err := db.Model(table).Unscoped().WherePri(1).One()
t.AssertNil(err)
t.Assert(len(one6), 0)
i, err = db.Model(table).Unscoped().Count()
t.AssertNil(err)
t.Assert(i, 0)
})
}

View File

@ -1,146 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb_test
import (
"testing"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_Union(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.Union(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").All()
t.AssertNil(err)
t.Assert(len(r), 3)
t.Assert(r[0]["id"], 3)
t.Assert(r[1]["id"], 2)
t.Assert(r[2]["id"], 1)
})
gtest.C(t, func(t *gtest.T) {
r, err := db.Union(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").One()
t.AssertNil(err)
t.Assert(r["id"], 3)
})
}
func Test_UnionAll(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.UnionAll(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").All()
t.AssertNil(err)
t.Assert(len(r), 5)
t.Assert(r[0]["id"], 3)
t.Assert(r[1]["id"], 2)
t.Assert(r[2]["id"], 2)
t.Assert(r[3]["id"], 1)
t.Assert(r[4]["id"], 1)
})
gtest.C(t, func(t *gtest.T) {
r, err := db.UnionAll(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").One()
t.AssertNil(err)
t.Assert(r["id"], 3)
})
}
func Test_Model_Union(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).Union(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").All()
t.AssertNil(err)
t.Assert(len(r), 3)
t.Assert(r[0]["id"], 3)
t.Assert(r[1]["id"], 2)
t.Assert(r[2]["id"], 1)
})
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).Union(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").One()
t.AssertNil(err)
t.Assert(r["id"], 3)
})
}
func Test_Model_UnionAll(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).UnionAll(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").All()
t.AssertNil(err)
t.Assert(len(r), 5)
t.Assert(r[0]["id"], 3)
t.Assert(r[1]["id"], 2)
t.Assert(r[2]["id"], 2)
t.Assert(r[3]["id"], 1)
t.Assert(r[4]["id"], 1)
})
gtest.C(t, func(t *gtest.T) {
r, err := db.Model(table).UnionAll(
db.Model(table).Where("id", 1),
db.Model(table).Where("id", 2),
db.Model(table).WhereIn("id", g.Slice{1, 2, 3}).OrderDesc("id"),
).OrderDesc("id").One()
t.AssertNil(err)
t.Assert(r["id"], 3)
})
}

File diff suppressed because it is too large Load Diff

View File

@ -8,95 +8,16 @@ package gdb
import (
"context"
"fmt"
"testing"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
)
const (
SCHEMA = "test_internal"
TestDbUser = "root"
TestDbPass = "12345678"
)
var (
db DB
ctx = context.TODO()
configNode ConfigNode
db DB
ctx = context.TODO()
)
func init() {
parser, err := gcmd.Parse(map[string]bool{
"name": true,
"type": true,
}, false)
gtest.AssertNil(err)
configNode = ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: TestDbUser,
Pass: TestDbPass,
Timezone: "Asia/Shanghai", // For calculating UT cases of datetime zones in convenience.
Name: parser.GetOpt("name", "").String(),
Type: parser.GetOpt("type", "mysql").String(),
Role: "master",
Charset: "utf8",
Weight: 1,
MaxIdleConnCount: 10,
MaxOpenConnCount: 10,
MaxConnLifeTime: 600,
}
AddConfigNode(DefaultGroupName, configNode)
// Default db.
if r, err := NewByGroup(); err != nil {
gtest.Error(err)
} else {
db = r
}
schemaTemplate := "CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET UTF8"
if _, err = db.Exec(ctx, fmt.Sprintf(schemaTemplate, SCHEMA)); err != nil {
gtest.Error(err)
}
db = db.Schema(SCHEMA)
}
func dropTable(table string) {
if _, err := db.Exec(ctx, fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table)); err != nil {
gtest.Error(err)
}
}
func Test_Func_FormatSqlWithArgs(t *testing.T) {
// mysql
gtest.C(t, func(t *gtest.T) {
var s string
s = FormatSqlWithArgs("select * from table where id>=? and sex=?", []interface{}{100, 1})
t.Assert(s, "select * from table where id>=100 and sex=1")
})
// mssql
gtest.C(t, func(t *gtest.T) {
var s string
s = FormatSqlWithArgs("select * from table where id>=@p1 and sex=@p2", []interface{}{100, 1})
t.Assert(s, "select * from table where id>=100 and sex=1")
})
// pgsql
gtest.C(t, func(t *gtest.T) {
var s string
s = FormatSqlWithArgs("select * from table where id>=$1 and sex=$2", []interface{}{100, 1})
t.Assert(s, "select * from table where id>=100 and sex=1")
})
// oracle
gtest.C(t, func(t *gtest.T) {
var s string
s = FormatSqlWithArgs("select * from table where id>=:v1 and sex=:v2", []interface{}{100, 1})
t.Assert(s, "select * from table where id>=100 and sex=1")
})
}
func Test_Func_doQuoteWord(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
array := map[string]string{
@ -175,127 +96,6 @@ func Test_Func_addTablePrefix(t *testing.T) {
})
}
func Test_Model_getSoftFieldName(t *testing.T) {
table1 := "soft_deleting_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table1)); err != nil {
gtest.Error(err)
}
defer dropTable(table1)
table2 := "soft_deleting_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
createat datetime DEFAULT NULL,
updateat datetime DEFAULT NULL,
deleteat datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table2)); err != nil {
gtest.Error(err)
}
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
model := db.Model(table1)
gtest.Assert(model.getSoftFieldNameCreated(table2), "createat")
gtest.Assert(model.getSoftFieldNameUpdated(table2), "updateat")
gtest.Assert(model.getSoftFieldNameDeleted(table2), "deleteat")
})
}
func Test_Model_getConditionForSoftDeleting(t *testing.T) {
table1 := "soft_deleting_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id1 int(11) NOT NULL,
name1 varchar(45) DEFAULT NULL,
create_at datetime DEFAULT NULL,
update_at datetime DEFAULT NULL,
delete_at datetime DEFAULT NULL,
PRIMARY KEY (id1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table1)); err != nil {
gtest.Error(err)
}
defer dropTable(table1)
table2 := "soft_deleting_table_" + gtime.TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id2 int(11) NOT NULL,
name2 varchar(45) DEFAULT NULL,
createat datetime DEFAULT NULL,
updateat datetime DEFAULT NULL,
deleteat datetime DEFAULT NULL,
PRIMARY KEY (id2)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, table2)); err != nil {
gtest.Error(err)
}
defer dropTable(table2)
gtest.C(t, func(t *gtest.T) {
model := db.Model(table1)
t.Assert(model.getConditionForSoftDeleting(), "`delete_at` IS NULL")
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s as t`, table1))
t.Assert(model.getConditionForSoftDeleting(), "`delete_at` IS NULL")
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s, %s`, table1, table2))
t.Assert(model.getConditionForSoftDeleting(), fmt.Sprintf(
"`%s`.`delete_at` IS NULL AND `%s`.`deleteat` IS NULL",
table1, table2,
))
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s t1, %s as t2`, table1, table2))
t.Assert(model.getConditionForSoftDeleting(), "`t1`.`delete_at` IS NULL AND `t2`.`deleteat` IS NULL")
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s as t1, %s as t2`, table1, table2))
t.Assert(model.getConditionForSoftDeleting(), "`t1`.`delete_at` IS NULL AND `t2`.`deleteat` IS NULL")
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s as t1`, table1)).LeftJoin(table2+" t2", "t2.id2=t1.id1")
t.Assert(model.getConditionForSoftDeleting(), "`t1`.`delete_at` IS NULL AND `t2`.`deleteat` IS NULL")
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s`, table1)).LeftJoin(table2, "t2.id2=t1.id1")
t.Assert(model.getConditionForSoftDeleting(), fmt.Sprintf(
"`%s`.`delete_at` IS NULL AND `%s`.`deleteat` IS NULL",
table1, table2,
))
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(fmt.Sprintf(`%s`, table1)).LeftJoin(table2, "t2.id2=t1.id1").RightJoin(table2, "t2.id2=t1.id1")
t.Assert(model.getConditionForSoftDeleting(), fmt.Sprintf(
"`%s`.`delete_at` IS NULL AND `%s`.`deleteat` IS NULL AND `%s`.`deleteat` IS NULL",
table1, table2, table2,
))
})
gtest.C(t, func(t *gtest.T) {
model := db.Model(table1+" as t1").LeftJoin(table2+" as t2", "t2.id2=t1.id1").RightJoin(table2+" as t3 ", "t2.id2=t1.id1")
t.Assert(
model.getConditionForSoftDeleting(),
"`t1`.`delete_at` IS NULL AND `t2`.`deleteat` IS NULL AND `t3`.`deleteat` IS NULL",
)
})
}
func Test_isSubQuery(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.Assert(isSubQuery("user"), false)
@ -304,346 +104,3 @@ func Test_isSubQuery(t *testing.T) {
t.Assert(isSubQuery("select 1"), true)
})
}
func TestResult_Structs1(t *testing.T) {
type A struct {
Id int `orm:"id"`
}
type B struct {
*A
Name string
}
gtest.C(t, func(t *gtest.T) {
r := Result{
Record{"id": gvar.New(nil), "name": gvar.New("john")},
Record{"id": gvar.New(nil), "name": gvar.New("smith")},
}
array := make([]*B, 2)
err := r.Structs(&array)
t.AssertNil(err)
t.Assert(array[0].Id, 0)
t.Assert(array[1].Id, 0)
t.Assert(array[0].Name, "john")
t.Assert(array[1].Name, "smith")
})
}
// https://github.com/gogf/gf/issues/1159
func Test_ScanList_NoRecreate_PtrAttribute(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
type S1 struct {
Id int
Name string
Age int
Score int
}
type S3 struct {
One *S1
}
var (
s []*S3
err error
)
r1 := Result{
Record{
"id": gvar.New(1),
"name": gvar.New("john"),
"age": gvar.New(16),
},
Record{
"id": gvar.New(2),
"name": gvar.New("smith"),
"age": gvar.New(18),
},
}
err = r1.ScanList(&s, "One")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
r2 := Result{
Record{
"id": gvar.New(1),
"age": gvar.New(20),
},
Record{
"id": gvar.New(2),
"age": gvar.New(21),
},
}
err = r2.ScanList(&s, "One", "One", "id:Id")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 20)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 21)
})
}
// https://github.com/gogf/gf/issues/1159
func Test_ScanList_NoRecreate_StructAttribute(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
type S1 struct {
Id int
Name string
Age int
Score int
}
type S3 struct {
One S1
}
var (
s []*S3
err error
)
r1 := Result{
Record{
"id": gvar.New(1),
"name": gvar.New("john"),
"age": gvar.New(16),
},
Record{
"id": gvar.New(2),
"name": gvar.New("smith"),
"age": gvar.New(18),
},
}
err = r1.ScanList(&s, "One")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
r2 := Result{
Record{
"id": gvar.New(1),
"age": gvar.New(20),
},
Record{
"id": gvar.New(2),
"age": gvar.New(21),
},
}
err = r2.ScanList(&s, "One", "One", "id:Id")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 20)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 21)
})
}
// https://github.com/gogf/gf/issues/1159
func Test_ScanList_NoRecreate_SliceAttribute_Ptr(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
type S1 struct {
Id int
Name string
Age int
Score int
}
type S2 struct {
Id int
Pid int
Name string
Age int
Score int
}
type S3 struct {
One *S1
Many []*S2
}
var (
s []*S3
err error
)
r1 := Result{
Record{
"id": gvar.New(1),
"name": gvar.New("john"),
"age": gvar.New(16),
},
Record{
"id": gvar.New(2),
"name": gvar.New("smith"),
"age": gvar.New(18),
},
}
err = r1.ScanList(&s, "One")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
r2 := Result{
Record{
"id": gvar.New(100),
"pid": gvar.New(1),
"age": gvar.New(30),
"name": gvar.New("john"),
},
Record{
"id": gvar.New(200),
"pid": gvar.New(1),
"age": gvar.New(31),
"name": gvar.New("smith"),
},
}
err = r2.ScanList(&s, "Many", "One", "pid:Id")
// fmt.Printf("%+v", err)
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(len(s[0].Many), 2)
t.Assert(s[0].Many[0].Name, "john")
t.Assert(s[0].Many[0].Age, 30)
t.Assert(s[0].Many[1].Name, "smith")
t.Assert(s[0].Many[1].Age, 31)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
t.Assert(len(s[1].Many), 0)
r3 := Result{
Record{
"id": gvar.New(100),
"pid": gvar.New(1),
"age": gvar.New(40),
},
Record{
"id": gvar.New(200),
"pid": gvar.New(1),
"age": gvar.New(41),
},
}
err = r3.ScanList(&s, "Many", "One", "pid:Id")
// fmt.Printf("%+v", err)
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(len(s[0].Many), 2)
t.Assert(s[0].Many[0].Name, "john")
t.Assert(s[0].Many[0].Age, 40)
t.Assert(s[0].Many[1].Name, "smith")
t.Assert(s[0].Many[1].Age, 41)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
t.Assert(len(s[1].Many), 0)
})
}
// https://github.com/gogf/gf/issues/1159
func Test_ScanList_NoRecreate_SliceAttribute_Struct(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
type S1 struct {
Id int
Name string
Age int
Score int
}
type S2 struct {
Id int
Pid int
Name string
Age int
Score int
}
type S3 struct {
One S1
Many []S2
}
var (
s []S3
err error
)
r1 := Result{
Record{
"id": gvar.New(1),
"name": gvar.New("john"),
"age": gvar.New(16),
},
Record{
"id": gvar.New(2),
"name": gvar.New("smith"),
"age": gvar.New(18),
},
}
err = r1.ScanList(&s, "One")
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
r2 := Result{
Record{
"id": gvar.New(100),
"pid": gvar.New(1),
"age": gvar.New(30),
"name": gvar.New("john"),
},
Record{
"id": gvar.New(200),
"pid": gvar.New(1),
"age": gvar.New(31),
"name": gvar.New("smith"),
},
}
err = r2.ScanList(&s, "Many", "One", "pid:Id")
// fmt.Printf("%+v", err)
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(len(s[0].Many), 2)
t.Assert(s[0].Many[0].Name, "john")
t.Assert(s[0].Many[0].Age, 30)
t.Assert(s[0].Many[1].Name, "smith")
t.Assert(s[0].Many[1].Age, 31)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
t.Assert(len(s[1].Many), 0)
r3 := Result{
Record{
"id": gvar.New(100),
"pid": gvar.New(1),
"age": gvar.New(40),
},
Record{
"id": gvar.New(200),
"pid": gvar.New(1),
"age": gvar.New(41),
},
}
err = r3.ScanList(&s, "Many", "One", "pid:Id")
// fmt.Printf("%+v", err)
t.AssertNil(err)
t.Assert(len(s), 2)
t.Assert(s[0].One.Name, "john")
t.Assert(s[0].One.Age, 16)
t.Assert(len(s[0].Many), 2)
t.Assert(s[0].Many[0].Name, "john")
t.Assert(s[0].Many[0].Age, 40)
t.Assert(s[0].Many[1].Name, "smith")
t.Assert(s[0].Many[1].Age, 41)
t.Assert(s[1].One.Name, "smith")
t.Assert(s[1].One.Age, 18)
t.Assert(len(s[1].Many), 0)
})
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff