gormutil

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 4, 2020 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LogFieldLevel   = "gorm-level"
	LogFieldTime    = "gorm-time"
	LogFieldFile    = "gorm-file"
	LogFieldLatency = "gorm-latency"
	LogFieldSQL     = "gorm-sql"
	LogFieldRows    = "gorm-rows"
	LogFieldMsg     = "gorm-msg"
)

gorm 查询日志字段key定义

View Source
const (
	LogLevelSQL = "sql"
)

gorm 日志级别

Variables

View Source
var LogFormatter = func(values ...interface{}) (fields map[string]interface{}) {
	if len(values) > 1 {
		var (
			sql             string
			formattedValues []string
			level           = values[0]
			currentTime     = NowFunc().Format(time.RFC3339Nano)
			source          = values[1]
		)

		fields = map[string]interface{}{
			LogFieldLevel: level,
			LogFieldTime:  currentTime,
			LogFieldFile:  source,
		}

		if level == LogLevelSQL {

			fields[LogFieldLatency] = fmt.Sprintf("%.2fms", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)

			for _, value := range values[4].([]interface{}) {
				indirectValue := reflect.Indirect(reflect.ValueOf(value))
				if indirectValue.IsValid() {
					value = indirectValue.Interface()
					if t, ok := value.(time.Time); ok {
						if t.IsZero() {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", "0000-00-00 00:00:00"))
						} else {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
						}
					} else if b, ok := value.([]byte); ok {
						if str := string(b); isPrintable(str) {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
						} else {
							formattedValues = append(formattedValues, "'<binary>'")
						}
					} else if r, ok := value.(driver.Valuer); ok {
						if value, err := r.Value(); err == nil && value != nil {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						} else {
							formattedValues = append(formattedValues, "NULL")
						}
					} else {
						switch value.(type) {
						case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool:
							formattedValues = append(formattedValues, fmt.Sprintf("%v", value))
						default:
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						}
					}
				} else {
					formattedValues = append(formattedValues, "NULL")
				}
			}

			if numericPlaceHolderRegexp.MatchString(values[3].(string)) {
				sql = values[3].(string)
				for index, value := range formattedValues {
					placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1)
					sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1")
				}
			} else {
				formattedValuesLength := len(formattedValues)
				for index, value := range sqlRegexp.Split(values[3].(string), -1) {
					sql += value
					if index < formattedValuesLength {
						sql += formattedValues[index]
					}
				}
			}

			sql = strings.Join(strings.Fields(strings.TrimSpace(sql)), " ")

			affectedRows := fmt.Sprintf("%v rows affected or returned", values[5])

			fields[LogFieldSQL] = sql
			fields[LogFieldRows] = affectedRows
		} else {
			fields[LogFieldMsg] = values[2:]
		}
	}

	return
}

LogFormatter gorm log formatter

View Source
var NowFunc = func() time.Time {
	return time.Now()
}

NowFunc returns current time, this function is exported in order to be able to give the flexibility to the developer to customize it according to their needs, e.g:

gorm.NowFunc = func() time.Time {
  return time.Now().UTC()
}

Functions

func DefaultContextFunc

func DefaultContextFunc() func(ctx context.Context, db *gorm.DB)

Types

type Config

type Config struct {
	database.Config
	Debug    bool
	Unscoped bool
}

Config 根据 Driver 不同,在引用侧自行按 driver 类型,导入驱动注册包;如mysql驱动,则 import _ "github.com/go-sql-driver/mysql"

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn gorm.DB

func NewConn

func NewConn(mc, sc *Config) (*Conn, error)

NewConn return new Conn

func (*Conn) Master

func (c *Conn) Master() *DB

Master 返回 master 连接

func (*Conn) SetContextFunc

func (c *Conn) SetContextFunc(fn func(ctx context.Context, db *gorm.DB))

SetContextFunc 设置 gorm.DB 的 WithContext 方法

func (*Conn) Slave

func (c *Conn) Slave() *DB

Slave 返回 slave 连接

type DB

type DB struct {
	*gorm.DB
	// contains filtered or unexported fields
}

DB gorm.DB

func NewDB

func NewDB(c *Config) (*DB, error)

NewDB new DB

func (*DB) SetContextFunc

func (d *DB) SetContextFunc(fn func(ctx context.Context, db *gorm.DB))

SetContextFunc 设置 gorm.DB 的 WithContext 方法

func (*DB) WithContext

func (d *DB) WithContext(ctx context.Context) *gorm.DB

WithContext return a new *gorm.DB with context

type LogWriter

type LogWriter interface {
	Infof(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

LogWriter

type Logger

type Logger struct {
	LogWriter
}

func NewLogger

func NewLogger(w LogWriter) *Logger

func (Logger) Print

func (l Logger) Print(values ...interface{})

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL