mysql

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2021 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package mysql storage is designed to give lazy load singleton access to mysql connections it doesn't provide any cluster nor balancing support, assuming it is handled in lower level infra, i.e. proxy, cluster etc.

Index

Constants

View Source
const (
	ErrorCredential uint32 = 100 << iota
	ErrorConnection
)

Variables

View Source
var LogFormatter = func(values ...interface{}) (messages []interface{}) {
	if len(values) > 1 {
		var (
			sql             string
			formattedValues []string
			level           = values[0]
			currentTime     = "\n\033[33m[" + NowFunc().Format("2006-01-02 15:04:05") + "]\033[0m"
			source          = fmt.Sprintf("\033[35m(%v)\033[0m", values[1])
		)

		messages = []interface{}{source, currentTime}

		if level != "sql" {
			messages = append(messages, "\033[31;1m")
			messages = append(messages, values[2:]...)
			messages = append(messages, "\033[0m")

			return
		}

		for _, value := range values[3].([]interface{}) {
			indirectValue := reflect.Indirect(reflect.ValueOf(value))
			value = indirectValue.Interface()

			if !indirectValue.IsValid() {
				formattedValues = append(formattedValues, "NULL")
			}

			switch value.(type) {
			case time.Time:
				formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value.(time.Time).Format("2006-01-02 15:04:05")))
			case []byte:
				if str := string(value.([]byte)); isPrintable(str) {
					formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
				} else {
					formattedValues = append(formattedValues, "'<binary>'")
				}
			case driver.Valuer:
				if value, err := value.(driver.Valuer).Value(); err == nil && value != nil {
					formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
				} else {
					formattedValues = append(formattedValues, "NULL")
				}
			default:
				formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
			}
		}

		if numericPlaceHolderRegexp.MatchString(values[2].(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[2].(string), -1) {
				sql += value
				if index < formattedValuesLength {
					sql += formattedValues[index]
				}
			}
		}

		messages = append(messages, sql)
	}

	return
}

LogFormatter : mysql log formatter

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

NowFunc : time func

Functions

func Init

func Init() error

func Log

func Log(logMode bool, query string, args ...interface{})

Log mysql request with defaultLogger

func New

func New() error

func Shutdown

func Shutdown() (err error)

Shutdown disconnecting all established mysql client connection

Types

type Config

type Config struct {
	User        string
	Password    string
	Address     string
	DB          string
	LogMode     bool
	MaxOpen     int
	MaxIdle     int
	MaxLifetime int
}

Config struct

type Conn

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

Conn struct

type LogWriter

type LogWriter interface {
	Println(v ...interface{})
}

LogWriter log writer interface

type Logger

type Logger struct {
	LogWriter
}

Logger default logger

func (Logger) Print

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

Print format & print log

type SQL

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

SQL struct

func Read

func Read() *SQL

Read retrieve MySQL established connection client (sqlx) and panic if error

func Write

func Write() *SQL

Write retrieve MySQL established connection client (sqlx) and panic if error

func (*SQL) Begin

func (sql *SQL) Begin() (*Tx, error)

Begin begins a transaction and returns an *Tx instead of an *sql.Tx.

func (*SQL) Exec

func (sql *SQL) Exec(query string, args ...interface{}) (sql.Result, error)

Exec using master sql

func (*SQL) Get

func (sql *SQL) Get(dest interface{}, query string, args ...interface{}) error

Get using slave sql.

func (*SQL) MustBegin

func (sql *SQL) MustBegin() *Tx

MustBegin starts a transaction, and panics on error.

func (*SQL) Query

func (sql *SQL) Query(query string, args ...interface{}) (*sql.Rows, error)

Query queries the database and returns an *sql.Rows.

func (*SQL) QueryRow

func (sql *SQL) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow queries the database and returns an *sqlx.Row.

func (*SQL) QueryRowx

func (sql *SQL) QueryRowx(query string, args ...interface{}) *sqlx.Row

QueryRowx queries the database and returns an *sqlx.Row.

func (*SQL) Queryx

func (sql *SQL) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

Queryx queries the databas e and returns an *sqlx.Rows.

func (*SQL) Select

func (sql *SQL) Select(dest interface{}, query string, args ...interface{}) error

Select using slave sql.

func (*SQL) WithContext

func (sql *SQL) WithContext(ctx context.Context) *SQL

WithContext add context to sql

type SQLError

type SQLError struct {
	Errors uint32
	// contains filtered or unexported fields
}

func NewSQLError

func NewSQLError(errorFlags uint32, errorString ...interface{}) *SQLError

func (SQLError) Error

func (e SQLError) Error() string

type Tx

type Tx struct {
	Tx *sqlx.Tx
	// contains filtered or unexported fields
}

Tx struct

func (*Tx) Exec

func (db *Tx) Exec(query string, args ...interface{}) (sql.Result, error)

Exec using master db

func (*Tx) Get

func (db *Tx) Get(dest interface{}, query string, args ...interface{}) error

Get using slave db.

func (*Tx) Query

func (db *Tx) Query(query string, args ...interface{}) (*sql.Rows, error)

Query queries the database and returns an *sql.Rows.

func (*Tx) QueryRow

func (db *Tx) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow queries the database and returns an *sqlx.Row.

func (*Tx) QueryRowx

func (db *Tx) QueryRowx(query string, args ...interface{}) *sqlx.Row

QueryRowx queries the database and returns an *sqlx.Row.

func (*Tx) Queryx

func (db *Tx) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

Queryx queries the databas e and returns an *sqlx.Rows.

func (*Tx) Select

func (db *Tx) Select(dest interface{}, query string, args ...interface{}) error

Select using slave db.

Jump to

Keyboard shortcuts

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