gf/database/gdb/gdb_driver_mysql.go

166 lines
4.8 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
2017-11-23 10:21:28 +08:00
package gdb
import (
"context"
"database/sql"
"fmt"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"net/url"
2019-07-29 21:01:19 +08:00
2021-08-27 20:26:07 +08:00
_ "github.com/go-sql-driver/mysql"
2017-11-23 10:21:28 +08:00
)
2020-03-08 00:17:42 +08:00
// DriverMysql is the driver for mysql database.
type DriverMysql struct {
*Core
}
// New creates and returns a database object for mysql.
// It implements the interface of gdb.Driver for extra database driver installation.
2020-03-08 00:17:42 +08:00
func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error) {
return &DriverMysql{
Core: core,
}, nil
2017-11-23 10:21:28 +08:00
}
2021-08-27 20:26:07 +08:00
// Open creates and returns an underlying sql.DB object for mysql.
// Note that it converts time.Time argument to local timezone in default.
2020-03-08 00:17:42 +08:00
func (d *DriverMysql) Open(config *ConfigNode) (*sql.DB, error) {
2019-06-19 09:06:52 +08:00
var source string
if config.Link != "" {
source = config.Link
// Custom changing the schema in runtime.
if config.Name != "" {
source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source)
}
2019-06-19 09:06:52 +08:00
} else {
2020-01-07 22:14:32 +08:00
source = fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=%s",
2020-01-07 22:14:32 +08:00
config.User, config.Pass, config.Host, config.Port, config.Name, config.Charset,
)
if config.Timezone != "" {
source = fmt.Sprintf("%s&loc=%s", source, url.QueryEscape(config.Timezone))
}
2019-06-19 09:06:52 +08:00
}
intlog.Printf(d.GetCtx(), "Open: %s", source)
2020-03-08 00:17:42 +08:00
if db, err := sql.Open("mysql", source); err == nil {
2019-06-19 09:06:52 +08:00
return db, nil
} else {
return nil, err
}
2017-11-23 10:21:28 +08:00
}
// FilteredLink retrieves and returns filtered `linkInfo` that can be using for
2021-01-25 21:17:32 +08:00
// logging or tracing purpose.
func (d *DriverMysql) FilteredLink() string {
linkInfo := d.GetConfig().Link
2021-01-25 21:17:32 +08:00
if linkInfo == "" {
return ""
}
s, _ := gregex.ReplaceString(
`(.+?):(.+)@tcp(.+)`,
`$1:xxx@tcp$3`,
linkInfo,
)
return s
}
2020-03-08 00:17:42 +08:00
// GetChars returns the security char for this type of database.
func (d *DriverMysql) GetChars() (charLeft string, charRight string) {
2019-06-19 09:06:52 +08:00
return "`", "`"
2017-11-23 10:21:28 +08:00
}
// DoCommit handles the sql before posts it to database.
2021-06-26 18:20:55 +08:00
func (d *DriverMysql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
return d.Core.DoCommit(ctx, link, sql, args)
2019-06-19 09:06:52 +08:00
}
// Tables retrieves and returns the tables of current schema.
// It's mainly used in cli tool chain for automatically generating the models.
func (d *DriverMysql) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
var result Result
2021-05-21 15:30:21 +08:00
link, err := d.SlaveLink(schema...)
if err != nil {
return nil, err
}
result, err = d.DoGetAll(ctx, link, `SHOW TABLES`)
if err != nil {
return
}
for _, m := range result {
for _, v := range m {
tables = append(tables, v.String())
}
}
return
}
// TableFields retrieves and returns the fields information of specified table of current
// schema.
//
// The parameter `link` is optional, if given nil it automatically retrieves a raw sql connection
// as its link to proceed necessary sql query.
//
// Note that it returns a map containing the field name and its corresponding fields.
// As a map is unsorted, the TableField struct has a "Index" field marks its sequence in
// the fields.
//
// It's using cache feature to enhance the performance, which is never expired util the
// process restarts.
func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error) {
charL, charR := d.GetChars()
table = gstr.Trim(table, charL+charR)
if gstr.Contains(table, " ") {
return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations")
}
2021-05-21 15:30:21 +08:00
useSchema := d.schema.Val()
if len(schema) > 0 && schema[0] != "" {
2021-05-21 15:30:21 +08:00
useSchema = schema[0]
}
tableFieldsCacheKey := fmt.Sprintf(
`mysql_table_fields_%s_%s@group:%s`,
2021-05-21 15:30:21 +08:00
table, useSchema, d.GetGroup(),
)
v := tableFieldsMap.GetOrSetFuncLock(tableFieldsCacheKey, func() interface{} {
var (
result Result
2021-05-21 15:30:21 +08:00
link, err = d.SlaveLink(useSchema)
)
if err != nil {
return nil
}
result, err = d.DoGetAll(ctx, link, fmt.Sprintf(`SHOW FULL COLUMNS FROM %s`, d.QuoteWord(table)))
if err != nil {
return nil
}
fields = make(map[string]*TableField)
for i, m := range result {
fields[m["Field"].String()] = &TableField{
Index: i,
Name: m["Field"].String(),
Type: m["Type"].String(),
Null: m["Null"].Bool(),
Key: m["Key"].String(),
Default: m["Default"].Val(),
Extra: m["Extra"].String(),
Comment: m["Comment"].String(),
}
}
return fields
})
if v != nil {
fields = v.(map[string]*TableField)
}
return
}