github.com/gogf/gf@v1.16.9/database/gdb/gdb_z_driver_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/container/gtype" 14 "github.com/gogf/gf/database/gdb" 15 "github.com/gogf/gf/frame/g" 16 "github.com/gogf/gf/test/gtest" 17 ) 18 19 // MyDriver is a custom database driver, which is used for testing only. 20 // For simplifying the unit testing case purpose, MyDriver struct inherits the mysql driver 21 // gdb.DriverMysql and overwrites its function DoCommit. 22 // So if there's any sql execution, it goes through MyDriver.DoCommit firstly and 23 // then gdb.DriverMysql.DoCommit. 24 // You can call it sql "HOOK" or "HiJack" as your will. 25 type MyDriver struct { 26 *gdb.DriverMysql 27 } 28 29 var ( 30 customDriverName = "MyDriver" 31 latestSqlString = gtype.NewString() // For simplifying unit testing only. 32 ) 33 34 // New creates and returns a database object for mysql. 35 // It implements the interface of gdb.Driver for extra database driver installation. 36 func (d *MyDriver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) { 37 return &MyDriver{ 38 &gdb.DriverMysql{ 39 Core: core, 40 }, 41 }, nil 42 } 43 44 // DoCommit handles the sql before posts it to database. 45 // It here overwrites the same method of gdb.DriverMysql and makes some custom changes. 46 func (d *MyDriver) DoCommit(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) { 47 latestSqlString.Set(sql) 48 return d.DriverMysql.DoCommit(ctx, link, sql, args) 49 } 50 51 func init() { 52 // It here registers my custom driver in package initialization function "init". 53 // You can later use this type in the database configuration. 54 gdb.Register(customDriverName, &MyDriver{}) 55 } 56 57 func Test_Custom_Driver(t *testing.T) { 58 gdb.AddConfigNode("driver-test", gdb.ConfigNode{ 59 Host: "127.0.0.1", 60 Port: "3306", 61 User: TestDbUser, 62 Pass: TestDbPass, 63 Name: "test", 64 Type: customDriverName, 65 Role: "master", 66 Charset: "utf8", 67 }) 68 gtest.C(t, func(t *gtest.T) { 69 t.Assert(latestSqlString.Val(), "") 70 sqlString := "select 10000" 71 value, err := g.DB("driver-test").GetValue(sqlString) 72 t.AssertNil(err) 73 t.Assert(value, 10000) 74 t.Assert(latestSqlString.Val(), sqlString) 75 }) 76 }