Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

我们来看一个自定义回调处理的示例,现需要将所有执行的SQL语句记录到monitor表中,以方便于进行SQL审计。为简化示例编写,以下代码实现了一个自定义的MySQL驱动,该驱动继承于driversmysql模块内已经实现的DriverMysqlDriver

Code Block
languagego
package driver

import (
	"context"
	"database/sql"
	"github.com/gogf/gf/contrib/drivers/mysql/v2"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"strconv"
)

// 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.DriverMysqlDriver and overwrites its functions DoQuery and DoExec.
// So if there's any sql execution, it goes through MyDriver.DoQuery/MyDriver.DoExec firstly
// and then gdb.DriverMysqlDriver.DoQuery/gdb.DriverMysqlDriver.DoExec.
// You can call it sql "HOOK" or "HiJack" as your will.
type MyDriver struct {
	*mysql.DriverMysqlDriver
}

var (
	// customDriverName is my driver name, which is used for registering.
	customDriverName = "MyDriver"
)

func init() {
	// It here registers my custom driver in package initialization function "init".
	// You can later use this type in the database configuration.
	if err := gdb.Register(customDriverName, &MyDriver{}); err != nil {
		panic(err)
	}
}

// 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{
		&mysql.DriverMysqlDriver{
			Core: core,
		},
	}, nil
}

// DoQueryDoCommit commits thecurrent sql string and its arguments to underlying sql driver
// through given link object and returns the execution result.
func (d *MyDriver) DoQueryDoCommit(ctx context.Context, linkin gdb.Link, sql string, args ...interface{}DoCommitInput) (rowsout gdb.ResultDoCommitOutput, err error) {
	tsMillitsMilliStart := gtime.TimestampMilli()
	rowsout, err = d.DriverMysqlCore.DoQueryDoCommit(ctx, link, sql, args...)
	_, _ = link.ExecContext(ctx,
		"INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)",
		gdb.FormatSqlWithArgs(sql, args),
		gtime.TimestampMilli()-tsMilli,
		gtime.Now(),
		err,
	)
	return
}

// DoExec commits the query string and its arguments to underlying driver
// through given link object and returns the execution result.
func (d *MyDriver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) {
	tsMilli in)
	tsMilliFinished := gtime.TimestampMilli()
	result, err = d.DriverMysql.DoExec(ctx, link, sql, args...)
	_, _ = linkin.Link.ExecContext(ctx,
		"INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)",
		gdb.FormatSqlWithArgs(sqlin.Sql, argsin.Args),
		gtime.TimestampMilli()-tsMillitsMilliFinished-tsMilliStart,
		gtime.Now(),
		err,
	)
	return
}

// DoFilter is a hook function, which filters the sql and its arguments before it's committed to underlying driver.
// The parameter `link` specifies the current database connection operation object. You can modify the sql
// string `sql` and its arguments `args` as you wish before they're committed to driver.
func (d *MyDriver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
	//Filter sql Step1
	sql_new := gstr.Replace(sql, "\n", "")

	//Filter sql Step2
	sql_new = gstr.Replace(sql_new, "\t", "")
	//... Filter what you want ...

	//Filter args Step1
	for _, v := range args {
		switch v.(type) {
		case gdb.Map:
			//Do it what you wan
		case string:
			//Do it what you wan
		}
	}
	return sql_new, args, nil
}

// ConvertDataForRecord is a very important function, which does converting for any data that
// will be inserted into table/collection as a record.
//
// The parameter `value` should be type of *map/map/*struct/struct.
// It supports embedded struct definition for struct.
func (d *MyDriver) ConvertDataForRecord(ctx context.Context, data interface{}) (map[string]interface{}, error) {
	//this hook is convert data to map[string]interface{}
	result := make(map[string]interface{}, 0)

	//like this
	switch data.(type) {
	case gdb.Map:
		result = gconv.Map(data)
	case gdb.List:
		for k, v := range data.(gdb.List) {
			result[strconv.Itoa(k)] = gconv.Map(v)
		}
		//case other type,do it what you want
	}
	return result, nil
}

我们看到,这里在包初始化方法init中使用了gdb.Register("MyDriver", &MyDriver{})来注册了了一个自定义名称的驱动。我们也可以通过gdb.Register("mysql", &MyDriver{})来覆盖已有的框架mysql驱动为自己的驱动。

...