github.com/gogf/gf@v1.16.9/database/gdb/gdb_z_mysql_ctx_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gdb_test 8 9 import ( 10 "context" 11 "testing" 12 13 "github.com/gogf/gf/database/gdb" 14 "github.com/gogf/gf/test/gtest" 15 ) 16 17 func Test_Ctx(t *testing.T) { 18 gtest.C(t, func(t *gtest.T) { 19 db, err := gdb.Instance() 20 t.AssertNil(err) 21 22 err1 := db.PingMaster() 23 err2 := db.PingSlave() 24 t.Assert(err1, nil) 25 t.Assert(err2, nil) 26 27 newDb := db.Ctx(context.Background()) 28 t.AssertNE(newDb, nil) 29 }) 30 } 31 32 func Test_Ctx_Query(t *testing.T) { 33 db.GetLogger().SetCtxKeys("SpanId", "TraceId") 34 gtest.C(t, func(t *gtest.T) { 35 db.SetDebug(true) 36 defer db.SetDebug(false) 37 ctx := context.WithValue(context.Background(), "TraceId", "12345678") 38 ctx = context.WithValue(ctx, "SpanId", "0.1") 39 db.Ctx(ctx).Query("select 1") 40 }) 41 gtest.C(t, func(t *gtest.T) { 42 db.SetDebug(true) 43 defer db.SetDebug(false) 44 db.Query("select 2") 45 }) 46 } 47 48 func Test_Ctx_Model(t *testing.T) { 49 table := createInitTable() 50 defer dropTable(table) 51 db.GetLogger().SetCtxKeys("SpanId", "TraceId") 52 gtest.C(t, func(t *gtest.T) { 53 db.SetDebug(true) 54 defer db.SetDebug(false) 55 ctx := context.WithValue(context.Background(), "TraceId", "12345678") 56 ctx = context.WithValue(ctx, "SpanId", "0.1") 57 db.Model(table).Ctx(ctx).All() 58 }) 59 gtest.C(t, func(t *gtest.T) { 60 db.SetDebug(true) 61 defer db.SetDebug(false) 62 db.Model(table).All() 63 }) 64 } 65 66 func Test_Ctx_Strict(t *testing.T) { 67 table := createInitTableWithDb(dbCtxStrict) 68 defer dropTable(table) 69 70 gtest.C(t, func(t *gtest.T) { 71 _, err := dbCtxStrict.Query("select 1") 72 t.AssertNE(err, nil) 73 }) 74 gtest.C(t, func(t *gtest.T) { 75 r, err := dbCtxStrict.Model(table).All() 76 t.AssertNE(err, nil) 77 t.Assert(len(r), 0) 78 }) 79 gtest.C(t, func(t *gtest.T) { 80 r, err := dbCtxStrict.Model(table).Ctx(context.TODO()).All() 81 t.AssertNil(err) 82 t.Assert(len(r), TableSize) 83 }) 84 }